Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw content on existing PDF Document in specific Page

So I am implementing a specific type of PDF editor for the iPad, for personal use. I have already implemented the PDF viewer, and now i am stuck in the editing part. Here is the deal: I display each page of the document in a UIView, and then create another view, with the exact same size of the page inside it. I then let the user draw on the view

Now, say i want to print that UIVIiew in the exact page of the PDF file it was drawn. I am aware of a way to do this, but it is taking too long for bigger documents. I was doing it like this (simplified the code for better understanding):

UIGraphicsBeginPDFContextToFile(file, pageSize, nil);

for (size_t currentPage = 1; currentPage <= pageCount; currentPage++) {

    UIGraphicsBeginPDFPageWithInfo(pageSize, nil);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //translates context, copies doc page to the new pdf, translates back
    CGContextTranslateCTM(ctx, 0, pageSize.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0); 
    CGPDFPageRef page = CGPDFDocumentGetPage (document, currentPage);
    CGContextDrawPDFPage (ctx, page);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    CGContextTranslateCTM(ctx, 0, -pageSize.size.height);
    //custom drawing goes here
    if(currentPage == desiredPage) [imageFromView drawInRect:pageSize];
}
UIGraphicsEndPDFContext();

The problem here is that this procedure recreates the entire PDF, and for larger documents, this can take minutes to finish.

I needed a solution that prints the UIView (that the user drew on) in a page of the PDF document, without having to recreate the whole document.

Any links, tips and other useful information are very appreciated. Thanks in advance

like image 506
luksfarris Avatar asked Nov 14 '22 06:11

luksfarris


1 Answers

On iOS there is only CGPDF and this does not support mutability as the Mac's PDFDocument partially does.

You would have to write your own solution to take the PDF streams of unmodified pages and combine these with one for the new page that you are creating. I began an open-source project for a DTPDFDocument wrapper modeled after the one on Mac, but I didn't do any work so far in moving or modifying pages: https://github.com/Cocoanetics/DTPDF

Or you could use one of the many available PDF frameworks. PSPDFKit is the first that comes to mind.

like image 79
Cocoanetics Avatar answered Jan 29 '23 08:01

Cocoanetics