CyberK
CyberK

Reputation: 1578

Create PDF on the fly from NSMutableData

I have a NSMutableData object which contains a PDF file. I know how to open an PDF stored on the system, which can me done like this:

CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), (CFStringRef)pathToPDF, NULL, NULL);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);

But now I don't want to store the file on the system, but create the PDF object on the fly (because the PDF is stored on the system as an encrypted PDF, and I don't want to save the decrypted file for security reasons.)

So instead of loading the CGPDFDocumentRef pdf from a file, I want to directly load it from an NSMutableData object.

How can I do this?

Thanks in advance!

Upvotes: 2

Views: 529

Answers (1)

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

Use CGDataProvider to get bytes from an arbitrary source:

NSData *encrypted = [NSData dataWithContentsOfFile: ...];
if (encrypted) {
    NSData *decrypted = MyDecrypt(encrypted);
    if (decrypted) {
        CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFDataRef)decrypted);
        if (dataProvider) {
            CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(dataProvider);
            CGDataProviderRelease(dataProvider);
        }
    }
}

You could also create an instance of CGDataProvider that decrypts on-the-fly using callbacks, if that fits your flow better. See the documentation for details.

Upvotes: 2

Related Questions