0

使用此问题中的提示,可以打印 DOCX、PDF、...,方法是将其加载到UIWebView

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];

现在,为了得到filePath,我将要打印的文档写入应用程序的tmp/目录:

NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* filePath = [NSString stringWithFormat:@"%@/%@.%@", NSTemporaryDirectory(), documentName, mimeType];
[fileManager createFileAtPath:filePath contents:documentData attributes:nil];

我只需要将 NSData(文档)加载到 UIWebView 中即可打印。我可以filePath 直接获取文档(并避免写入磁盘)吗?

已经尝试过[webView loadData:documentData MIMEType:mimeType textEncodingName:nil baseURL:nil];及其变体。


整个东西:

UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
if (pic)
{
    [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackOpaque];
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.jobName = documentName;
    pic.printInfo = printInfo;

    // Apple-supported formats (.pdf & some images)
    if ([UIPrintInteractionController canPrintData:documentData]) 
        pic.printingItem = documentData;
    // Apple-un-supported formats (.doc, .xls, .ppt, ...)
    else 
    {
        NSFileManager* fileManager = [NSFileManager defaultManager];
        NSString* filePath = [NSString stringWithFormat:@"%@/%@.%@", NSTemporaryDirectory(), documentName, mimeType];
        [fileManager createFileAtPath:filePath contents:documentData attributes:nil];

        UIWebView* webView = [UIWebView new];
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
        pic.printFormatter = webView.viewPrintFormatter;
    }

    void (^completionHandler)(UIPrintInteractionController *,    BOOL,           NSError *) =
                            ^(UIPrintInteractionController *pic, BOOL completed, NSError *error)
    {
        if (!completed && error)
            NSLog(@"Printing error in domain %@ with error code %u", error.domain, error.code);
    };
    [pic presentAnimated:YES completionHandler:completionHandler];
}
4

0 回答 0