4

我正在尝试从 MS Word 文档(.doc、.docx、.docs)中读取文本。我从昨天开始一直在搜索,但没有找到任何解决方案。请任何人告诉我我该怎么办?我已经尝试过 UIWebview 从 javascript 获取文本,但效果不佳。

- (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;
}

如果有人能告诉我应该做什么或去哪里看看,那对我真的很有帮助,谢谢

4

2 回答 2

5

您加载 UIWebView 然后立即尝试访问 dom,它可能还没有准备好。

在调用 UIWebViewDelegate didFinishLoad: 之前,不要调用 stringByEvaluatingJavaScriptFromString:。

于 2012-05-31T14:11:01.953 回答
3

下面的代码在启动时将 Word .docx 文件保存到应用程序的文档目录中。然后它在 viewDidLoad 期间将该文件读入 UIWebView。最后,它在从 UIWebView 获取文本之前等待 UIWebView 加载文档。不要忘记在视图控制器的头文件中遵守 UIWebViewDelegate 协议。当然,Word 文档必须包含在您的项目中。确保将文档添加到 Build Phases > Copy Bundle 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"];
}
于 2014-02-25T11:07:05.430 回答