4

I am working on pdf in my new iPhone app. I am checking PDF is lock(password protected) or not

BOOL bIsUnlock = CGPDFDocumentIsUnlocked(PDFDocument);

If pdf is lock then

BOOL success = CGPDFDocumentUnlockWithPassword ( PDFDocument, [password UTF8String]);

Here I succeed to unlock documents. Now I want to save the unlock document to app directory.

I have searched and found a way

CGPDFPageRef _PDFPage =CGPDFDocumentGetPage(PDFDocument, 1);

CGRect pageRect = CGPDFPageGetBoxRect(_PDFPage, kCGPDFMediaBox);

//create empty pdf file;
UIGraphicsBeginPDFContextToFile(newFilePath, pageRect, nil);
size_t count = CGPDFDocumentGetNumberOfPages(PDFDocument);

for (size_t pageNumber = 1; pageNumber <= count; pageNumber++)

{

    //get bounds of template page

    CGPDFPageRef templatePage = CGPDFDocumentGetPage(PDFDocument, pageNumber);

    CGRect templatePageBounds = CGPDFPageGetBoxRect(templatePage, kCGPDFCropBox);

    //create empty page with corresponding bounds in new document
    UIGraphicsBeginPDFPageWithInfo(templatePageBounds, nil);

    CGContextRef context = UIGraphicsGetCurrentContext();

    //flip context due to different origins
    CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    //copy content of template page on the corresponding page in new file
    CGContextDrawPDFPage(context, templatePage);

    //flip context back
    CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0); 
 }
CGPDFDocumentRelease(PDFDocument);

UIGraphicsEndPDFContext(); 

But I want any other simple way like convert the PDFDocument toNSdata and save to directory. Please help.

Altaf Rehman
  • 137
  • 9

2 Answers2

1

Your code is unfortunately the simplest solution to save decrypted PDF files to your app directory. The problem is this code will work only with simple PDF files because annotations, links, form fields, bookmarks, file attachments, etc, are not transferred to the new document. It is a limitation of CGPDF API and there is nothing much you can do.

iPDFdev
  • 5,229
  • 2
  • 17
  • 18
1

As iPDFdev already mentioned, you won't come very far with Apple's CoreGraphics rendering engine here - you'll likely need to re-implement this all yourself. Since you probably don't have a few years to do so, there are a few products that can help you to modify a document.

On the Open Source front there is PoDoFo or muPDF (GPL/commercial) which might be able to solve your problem. I work on the commercial PSPDFKit SDK which allows you do rewrite a document using PSPDFProcessor - we offer a similar API for Android as well.

steipete
  • 7,581
  • 5
  • 47
  • 81