简体   繁体   中英

Generating multi-page PDF from single UIView w/ subviews

I'm having trouble breaking my PDF out into multiple pages from a single UIView. I'm trying to keep this as simple as possible. I have a UIScrollView that can vary in height. As of right now, I can get the first page to display correctly, but nothing after that. I'm pretty stumped at this point. Here's what I have:

NSMutableData *pdfData = [NSMutableData data];

UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);

CGContextRef pdfContext = UIGraphicsGetCurrentContext();
NSInteger    pageHeight = 867;

for (int originY = 0; originY < self.scrollView.contentSize.height; originY += pageHeight) {

    // Start a new page.
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0,originY,768,pageHeight), nil);

    [self.scrollView.layer renderInContext:pdfContext];

    for (UIView *subview in self.scrollView.subviews) {
        [subview.layer renderInContext:pdfContext];
    }

}

UIGraphicsEndPDFContext();

I'm trying to traverse this single UIScrollView and pick out the "pages" based on this frame, but that's not exactly working. Any help would be appreciated. I have read the apple docs on this topic and had problems translating that into my own application.

This worked pretty well for me. Make your life easier and just call on CGContextTranslateCTM.

NSInteger pageHeight = 792; // Standard page height - adjust as needed
NSInteger pageWidth = 612; // Standard page width - adjust as needed

/* CREATE PDF */
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0,0,pageWidth,pageHeight), nil);
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
for (int page=0; pageHeight * page < scrollView.frame.size.height; page++)
{
    UIGraphicsBeginPDFPage();
    CGContextTranslateCTM(pdfContext, 0, -pageHeight * page);
    [scrollView.layer renderInContext:pdfContext];
}

UIGraphicsEndPDFContext();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM