Search code examples
iosobjective-ccocoa-touchpdfuiwebview

How to check if a PDF is valid and can be open in UIWebView


I want to know if there is a quick way to check if the format of a PDF file is correct and that can be opened by UIWebView before even feeding it to UIWebView?

If PDF file cannot be opened, I end up getting this delegate call back but I want to take a decision of passing this PDF to UIWebView based on whether it would be opening. I tried with NSFileManager but couldn't come across any solid API for this. Any idea how this can be achieved?

public func webView(_ webView: UIWebView, didFailLoadWithError error: Error)

Please Note: I am loading this PDF from Documents directory. This PDF might be invalid due to incomplete data download.


Solution

  • May be because it is invalid/corrupted or something else it can't be opened, you can try below lines of code and check if it is valid pdf document and it can be opened:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"example_PDF" ofType:@"pdf"];//Path of your PDF
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
    
    CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
    CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(provider);
    
    if (document == nil) {
        NSLog(@"The PDF is corrupted");//Can't be opened
    }
    CGDataProviderRelease(provider);
    CGPDFDocumentRelease(document);