Contex Drawing + Pagination
I don't think you need the code which flips the PDF upside down. I've done this before (manual pagination, but without a scroll view) and never had to flip the context vertically. My main concern is that you are doing it on every iteration - if you have a valid reason for flipping it, you probably don't need it in the loop, but just once before the loop begins. Also the code CGContextTranslateCTM(pdfContext,0,-ty);
might need to be replaced with CGContextTranslateCTM(pdfContext,0,heightOfPdf);
If that doesn't work, try UIGraphicsBeginPDFPage();
instead of CGContextBeginPage()
, that's the only major difference between your code and mine.
This github project can definitely help you.
- (void) renderPageAtIndex:(NSUInteger)index inContext:(CGContextRef)ctx {
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, index + 1);
CGAffineTransform transform = aspectFit(CGPDFPageGetBoxRect(page, kCGPDFMediaBox),
CGContextGetClipBoundingBox(ctx));
CGContextConcatCTM(ctx, transform);
CGContextDrawPDFPage(ctx, page);
}
Found this link to render a PDF, it says about multiple pages but haven't shown an implementation. It doesnt straight away answer to your question but it tells a simpler method to render a pdf with much less translation and transforms.
Render PDF
Generate Multipage PDF -anoop
You could consider using a UIScrollView
to layout your separate PDF pages. The following method loads each PDF page in a view (PDFView
) and adds it to the scroll view content in a centered fashion:
- (void) loadPDFAtPath:(NSString *)path
{
NSURL *pdfUrl = [NSURL fileURLWithPath:path];
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfUrl);
float height = 0.0;
for(int i = 0; i < CGPDFDocumentGetNumberOfPages(document); i++) {
CGPDFPageRef page = CGPDFDocumentGetPage(document, i + 1);
PDFView *pdfView = [[PDFView alloc] initPdfViewWithPageRef:page];
CGRect pageSize = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
pv.frame = CGRectMake((self.frame.size.width / 2.0) - pageSize.size.width / 2.0, height, pageSize.size.width, pageSize.size.height);
height += pageSize.size.height + SOME_SPACE_IN_BETWEEN_PAGES;
// self is a subclass of UIScrollView
[self addSubview:pdfView];
[pdfView setNeedsDisplay];
}
CGPDFDocumentRelease(document);
[self setContentSize:CGSizeMake(self.frame.size.width, height)];
}
In this case, PDFView
is responsible for rendering a single CGPDFPageRef
in its drawRect or drawLayer implementation.