iPad App: Merge PDF files into 1 PDF document / Cr

2019-03-17 09:59发布

问题:

I am writing an iPad application which uses a scrollview with page control. I need to create a PDF of all the pages as 1 PDF file. So far, I figured that I should loop through all the sub-views (pages) and create PDF files for each (using CGPDFContext). BUT I do need to combine all the files into 1 PDF document. Can you help me to do so??

OR if you have a better way to create a PDF document with multiple pages from this scrollview, that would even be better!!

Please help. I've searched everywhere and saw that Mac OS has something using PDFDocument, insertPage function. I can't find a similar method for iOS??

回答1:

to create a multi-part PDF:

-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(NSString *) path
{
    CGContextRef myOutContext = NULL;
    NSURL * url;

    url = [NSURL fileURLWithPath:path];
    if (url != NULL) {
        myOutContext = CGPDFContextCreateWithURL (url,// 2
                                                  &inMediaBox,
                                                  NULL);
    }
    return myOutContext;// 4
}

-(void)createPdfFromScrollview:(UIScrollView *)scrollview
{

    CGContextRef pdfContext = [self createPDFContext:CGRectMake(0, 0, WIDTH, HEIGHT) path:outputFilePath];

    for(UIView * view in scrollview.subviews)
    {
        CGContextBeginPage (pdfContext,nil);
        CGAffineTransform transform = CGAffineTransformIdentity;
        transform = CGAffineTransformMakeTranslation(0, HEIGHT);
        transform = CGAffineTransformScale(transform, 1.0, -1.0);
        CGContextConcatCTM(pdfContext, transform);            
        //Draw view into PDF
        [view.layer renderInContext:pdfContext];

        CGContextEndPage (pdfContext);         
    }

    CGContextRelease (pdfContext);
}

Hope this helps.