I'm creating PDF files from UIViews using full screen iPad with Retina Display 2048x1536 resolution (2x scale). The resulting files are very large, I'm getting 6-10 mb files for 2 pages of fairly simple views. Ideally I would get to 4-5 pages per document, but the current approach would make the PDF size prohibitively large.
Is there a way to make the PDFs created this way smaller? Like creating a screenshot of view, converting it to JPG, then writing that to PDF context? Or is there some quality option that I'm missing?
Here's the code to create a PDF from a single view:
+(NSMutableData *)createPDFDatafromUIView:(UIView*)aView
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView.layer renderInContext:pdfContext];
// remove PDF rendering context
UIGraphicsEndPDFContext();
return pdfData;
}
+(NSString*)createPDFfromUIView:(UIView*)aView saveToFilepath:(NSString*)filepath
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [AppGraphics createPDFDatafromUIView:aView];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:filepath atomically:YES];
DLog(@"saving PDF to: %@",filepath);
DLog(@"file exists: %@",[[NSFileManager defaultManager] fileExistsAtPath:filepath]?@"YES":@"NO");
return filepath;
}
Here's what I'm using to join multiple PDFs together
+ (NSString *)joinPDF:(NSArray *)listOfPaths saveToPath:(NSString*)path
{
CFURLRef pdfURLOutput = ( CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:path]);
NSInteger numberOfPages = 0;
// Create the output context
CGContextRef writeContext = CGPDFContextCreateWithURL(pdfURLOutput, NULL, NULL);
for (NSString *source in listOfPaths) {
CFURLRef pdfURL = ( CFURLRef)CFBridgingRetain([[NSURL alloc] initFileURLWithPath:source]);
//file ref
CGPDFDocumentRef pdfRef = CGPDFDocumentCreateWithURL((CFURLRef) pdfURL);
numberOfPages = CGPDFDocumentGetNumberOfPages(pdfRef);
// Loop variables
CGPDFPageRef page;
CGRect mediaBox;
// Read the first PDF and generate the output pages
DLog(@"GENERATING PAGES FROM PDF 1 (%@)...", source);
for (int i=1; i<=numberOfPages; i++) {
page = CGPDFDocumentGetPage(pdfRef, i);
mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGContextBeginPage(writeContext, &mediaBox);
CGContextDrawPDFPage(writeContext, page);
CGContextEndPage(writeContext);
}
CGPDFDocumentRelease(pdfRef);
CFRelease(pdfURL);
}
CFRelease(pdfURLOutput);
// Finalize the output file
CGPDFContextClose(writeContext);
CGContextRelease(writeContext);
return path;
}