IOS reads text from MS Word

I am trying to read text from MS Word documents (.doc, .docx, .docs). I searched the last day, but did not find a solution for this. Please tell me what should I do? I already tried UIWebview to get text from javascript, this does not work either.

- (NSString *)textFromWordDocument:(NSString *)path { UIWebView *theWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; NSURL *url = [NSURL fileURLWithPath:path]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [theWebView loadRequest:request ]; NSString *document = [theWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerText"]; [theWebView release]; return document; } 

If someone can tell me what I should do or where to look, it will be really useful for me, thanks.

+4
source share
2 answers

Download UIWebView and then immediately try to access dom, it may not be ready yet.

Do not call stringByEvaluatingJavaScriptFromString: until UIWebViewDelegate didFinishLoad is called:

+5
source

The code below saves the Word.docx file in the application document directory at startup. Then it reads this file into the UIWebView while viewing the DidLoad. Finally, he expects the UIWebView to load the document before extracting text from the UIWebView. Remember to execute the UIWebViewDelegate protocol in your View controller header file. And, of course, a Word document should be included in your project. Be sure to add the document to Phase Build> Copy Package Resources.

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { /* WRITE WORD FILE TO DOCUMENT DIRECTORY */ NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [docsDirectory stringByAppendingPathComponent:@"Text.docx"]; NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/Text.docx"]]; [data writeToFile:path atomically:YES]; } - (void)viewDidLoad { [super viewDidLoad]; /* READ WORD FILE FROM DOCUMENT DIRECTORY TO WEB VIEW */ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *wordFilePath = [documentsDirectory stringByAppendingPathComponent:@"Text.docx"]; UIWebView *theWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; NSURL *wordFileUrl = [NSURL fileURLWithPath:wordFilePath]; NSURLRequest *request = [NSURLRequest requestWithURL:wordFileUrl]; [theWebView loadRequest:request]; theWebView.delegate = self; [self.view addSubview:theWebView]; } - (void)webViewDidFinishLoad:(UIWebView *)webView { /* GET TEXT FROM WEB VIEW */ NSString *text = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerText"]; } 
+2
source

Source: https://habr.com/ru/post/1415334/


All Articles