0

Using the hint in this question one can print DOCX, PDF, ... by loading it into UIWebView:

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

Now, to get the filePath, I write the document-to-be-printed into app's tmp/ directory:

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

I just need to load NSData (the document) into UIWebView in order to print it. Can I get the document's filePath directly (and avoid writing the disk)?

Already tried [webView loadData:documentData MIMEType:mimeType textEncodingName:nil baseURL:nil]; and its variations.


The whole thing:

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];
}
Community
  • 1
  • 1
Blaz
  • 3,548
  • 5
  • 26
  • 40
  • Does your current approach work? Because I have the same problem (print doc(x), xls(x) etc), and even writing the files on disk did not work. But no, you can only get the filepath if the file is written on disk. – Marc Nov 01 '13 at 07:57
  • @MarcMosby, yes, the above approach works: the formatting on paper isn't perfect, but at least the content is there. The question was put only because the approach smells ... unless there really is no better way to get to the `filePath` (or some other usable handle). – Blaz Nov 01 '13 at 10:18

0 Answers0