I need to turn pages of PDF documents into separate PNG files, but I'm having problems getting a large enough version of the PDF document into my graphics context. The pages are always around 500 pixels tall, no matter which PDF I try. How can I get larger versions (/higher quality) of each page?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[[_issue objectForKey:#"Issue"] lastPathComponent]];
NSURL *pdfFileUrl = [NSURL fileURLWithPath:pdfPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfFileUrl);
CGPDFPageRef myPageRef = CGPDFDocumentGetPage(pdf, pageNumber);
CGRect aRect = CGPDFPageGetBoxRect(myPageRef, kCGPDFCropBox);
UIGraphicsBeginImageContext(CGSizeMake(2008 / (aRect.size.height / aRect.size.width), 2008));
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, aRect.size.height);
CGContextScaleCTM(context, 2.0, -1.0);
CGContextSetGrayFillColor(context, 1.0, 1.0);
CGContextFillRect(context, aRect);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, pageNumber);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, aRect, 0, true);
CGContextConcatCTM(context, pdfTransform);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
CGContextDrawPDFPage(context, page);
As iPDFdev answered in the comment, the solution can be found here: Best way to convert PDF to high-resolution image in Cocoa
Related
This question already has answers here:
Cannot create PDF document with 400+ pages on iOS
(4 answers)
Closed 6 years ago.
I need to generate PDF more than 60 pages and need to Print it, but in iPhone & iPad memory Ram raises to 350.50MB-500.00MB and Crashes .
For Reducing memory->Running in dispatch queues also that doesn't help
Can't find the solution for this . Plz help me in this ...
and referred below link but doesn't help
Cannot create PDF document with 400+ pages on iOS
-(NSData*)getPdfFullLineSheetiPhone:(UIScrollView *)tableView GridCount:(NSInteger)count{
// -- first page height, rest pages height: adjust to get it right
#define FIRST_PAGE_HEIGHT_FULLSON 1040
#define REST_PAGES_HEIGHT_FULLSON 1090//1420
#define WIDTH_FULLSO_PORTRAITN 400
CGSize fittedSize;
CGRect priorBounds = tableView.frame;
// - the '200' is the cell height for estimating how many pages, and 200/3 is ROw calculation(How many rows in GMGridView)
fittedSize =CGSizeMake(WIDTH_FULLSO_PORTRAITN, count * 200/3);
tableView.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height);
Generating Pages Code Starts
CGRect pdfPageBounds;
// Standard US Letter dimensions 8.5" x 11"
pdfPageBounds = CGRectMake(0, 0, 768/1.8, REST_PAGES_HEIGHT_FULLSON/1.79);
NSMutableData *pdfData = [[NSMutableData alloc] init];
UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil);
int pageno=0;
{
// do page1
CGRect pdfPageBoundsPage1;
pdfPageBoundsPage1 = CGRectMake(0,0,768/1.8, FIRST_PAGE_HEIGHT_FULLSON/1.7);
UIGraphicsBeginPDFPageWithInfo(pdfPageBoundsPage1, nil);
{
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 10, 0);
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
pageno ++;
}
//Rest of Pages
for (CGFloat pageOriginY = FIRST_PAGE_HEIGHT_FULLSON/1.7; pageOriginY < fittedSize.height; pageOriginY += REST_PAGES_HEIGHT_FULLSON/1.79)
{
#autoreleasepool {
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil);
{
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 10, -pageOriginY);
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
pageno ++;
}
}
}
}
UIGraphicsEndPDFContext();
tableView.bounds = priorBounds;
return pdfData;
}
Memory Raises in iPad4 whereas in iPad Mini 180-240MB nd crashes
you have to construct your code some thing like this:
UIGraphicsBeginPDFContextToFile( pdfPath, CGRectZero, nil );// as per rMaddy
UIGraphicsBeginPDFPageWithInfo();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[tableView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
here:
file namecan be like this:
NSString *newPDFName = [NSString stringWithFormat:#”%#.pdf”, #"whatEverNameYouWant"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
NSLog(#”%#”,pdfPath);
basically the main benefit of this approach will be reduce NSData which is creating memory pressure.
over all code will look some thing this:
// Set up we the pdf we're going to be generating is
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
int i = 0;
for ( ; i < pages; i++)
{
#autoreleasepool{
// Specify the size of the pdf page
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Move the context for the margins
CGContextTranslateCTM(currentContext, kMargin, kMargin);
// draw the layer to the pdf, ignore the "renderInContext not found" warning.
[tableView.layer.layer renderInContext:currentContext];
}
}
// all done with making the pdf
UIGraphicsEndPDFContext();
Thats it !! you can take care of your calculation
It is not the answer for above question , it is another Code which was tried for to generate PDf using
UIGraphicsBeginPDFPageWithInfo. This approach also crashes for more than 500 rows nothing but it comes around 56 Pages
After this approach after returning PDF Data when i assign that PDF Data to UIPrinterInteractionController Action -
It shows , SO i am unable to calculate Pages
Print-Job failed: Printer exists.
2016-05-27 00:37:26.131 APPName[9078:2952235] \032Send\032to\032Mac\032#\032macminiB._ipp._tcp.local.: startJob not called.
Note :
whereas this Printer error doesn't shows in Above code which i posted above with UIGraphicsBeginPDFContextToData
-(NSData *)getPdfSimpleSOTr:(UITableView *)tableView{
#define FIRST_PAGE_HEIGHT 1188
#define REST_PAGES_HEIGHT 1176.5
CGSize fittedSize;
CGRect priorBounds;
// 140208 dan - Comment: save the WIDTH
CGRect savedFrame = tableView.frame;
// 140207 dan - force portrait width
priorBounds = tableView.frame;
priorBounds.size.width=768; // put into Portrait
tableView.frame = priorBounds;
fittedSize = [tableView sizeThatFits:CGSizeMake(priorBounds.size.width, ([tableView numberOfRowsInSection:0] * 49) + 529)];
tableView.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height);
CGRect pdfPageBounds;
pdfPageBounds = CGRectMake(0, -12, 768, REST_PAGES_HEIGHT);
File Name & Path
NSString *newPDFName = [NSString stringWithFormat:#"%#.pdf", #"AppName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
NSLog(#"%#",pdfPath);
Generating Pages
// Set up we the pdf we're going to be generating is
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
int pageno=0;
{
CGRect pdfPageBoundsPage1 = CGRectMake(0,0,768, FIRST_PAGE_HEIGHT+15);//15
UIGraphicsBeginPDFPageWithInfo(pdfPageBoundsPage1, nil);
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 10, 0);
[tableView.layer renderInContext:context];
pageno ++;
}
for (CGFloat pageOriginY = FIRST_PAGE_HEIGHT; pageOriginY < fittedSize.height; pageOriginY += REST_PAGES_HEIGHT)
{
#autoreleasepool{
// Specify the size of the pdf page
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil);
CGContextRef context = UIGraphicsGetCurrentContext();
// Move the context for the margins
CGContextTranslateCTM(context, 10, -pageOriginY);
// draw the layer to the pdf, ignore the "renderInContext not found" warning.
[tableView.layer renderInContext:context];
}
}
}
// all done with making the pdf
UIGraphicsEndPDFContext();
After GraphicsEnd retrieving NSData from FilePath
NSData *pdfData;
if([[NSFileManager defaultManager] fileExistsAtPath:pdfPath])
{
pdfData = [[NSFileManager defaultManager] contentsAtPath:pdfPath];
}
else
{
NSLog(#"File not exits");
}
tableView.bounds = priorBounds;
// 140208 dan - Comment: restored the saved WIDTH
tableView.frame=savedFrame ;
return pdfData;
}
I am working on document based application. I will load the PDF in UIWebView. For my requirement, i have to add an image in my touch/tap point. I have found the touch point(CGPoint) in UIWebview. But i want to get the same touch point of PDF that was loaded in PDF.
In detail, UIWebView show the contents of PDF document in varied size(Small size). So the touchpoint(CGPoint) of UIWebView will differ with the PDF.
I am not rendering the content of UIWebView to PDF due to decrease in page clarity. I will render the content of PDF directly.
Below code will explain the how i am rendering the PDF.
Code for PDF render:
NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:#"input" ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:tessdataPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)url);
const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);
NSMutableData* data = [NSMutableData data];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);
for(size_t page = 1; page <= numberOfPages; page++)
{
// Get the current page and page frame
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, page);
const CGRect pageFrame = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
// Draw the page (flipped)
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
CGContextDrawPDFPage(ctx, pdfPage);
CGContextRestoreGState(ctx);
if(page == 1)
{
for (UIView *subview in [self.pdfView.scrollView subviews]) {
if([subview isKindOfClass:[UIImageView class]])
{
UIImageView *img = (UIImageView*)subview;
[subview removeFromSuperview];
CGPoint point1 = CGPointMake(img.frame.origin.x, img.frame.origin.y);
[self drawCustomPDFContent:img.image point1:point1];
}
}
}
}
UIGraphicsEndPDFContext();
CGPDFDocumentRelease(pdf);
pdf = nil;
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:#"output.pdf"];
//bool fileCopied = [[NSFileManager defaultManager]copyItemAtURL:url toURL:toUrl error:nil];
[data writeToFile:filePath atomically:YES];
In this, i am rendering the input pdf with an image in page 1. Image was successfully rendered with input.pdf. But i need to add the image at exact point in pdf. See the above image for touch point difference. Can anyone provide the solution to find the exact touch point in PDF?
I want to add the signature on existing pdf. I have done this in following way:
1) Load existing pdf on UIView say mainView.
2) Add a signature image on mainView.
3) Call a following function
-(NSMutableData *)getPDFDatafromUIView
{
DebugLog(#"");
// 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, mainView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
mainView.layer renderInContext:pdfContext];
// remove PDF rendering context
UIGraphicsEndPDFContext();
return pdfData;
}
4) This function block your UI for a while, so call it on new thread
[NSThread detachNewThreadSelector:#selector(launchExportViewForExportDrawing) toTarget:self withObject:nil];
Using above method I get a pdf data with signature which contain the old pdf data too.
But for above method I must need to show the pdf in UIView. If I want do the above thing without loading on UIView, without showing pdf to user, How do I do that?
I am able to add a Image on pdf with creating the new pdf page. How do I add a image on existing pdf?
I have solved by creating the new PDF and drawing the pdf data and signature on it. Please refer following code:
// For adding the Siganture we need to wite the content on new PDF
-(void) addSignature:(UIImage *) imgSignature onPDFData:(NSData *)pdfData {
NSMutableData* outputPDFData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)outputPDFData);
CFMutableDictionaryRef attrDictionary = NULL;
attrDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrDictionary, kCGPDFContextTitle, CFSTR("My Doc"));
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, NULL, attrDictionary);
CFRelease(dataConsumer);
CFRelease(attrDictionary);
CGRect pageRect;
// Draw the old "pdfData" on pdfContext
CFDataRef myPDFData = (__bridge CFDataRef) pdfData;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGDataProviderRelease(provider);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);
pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGContextBeginPage(pdfContext, &pageRect);
CGContextDrawPDFPage(pdfContext, page);
// Draw the signature on pdfContext
pageRect = CGRectMake(0, 0,imgSignature.size.width , imgSignature.size.height);
CGImageRef pageImage = [imgSignature CGImage];
CGContextDrawImage(pdfContext, pageRect, pageImage);
// release the allocated memory
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);
// write new PDFData in "outPutPDF.pdf" file in document directory
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pdfFilePath =[NSString stringWithFormat:#"%#/outPutPDF.pdf",docsDirectory];
[outputPDFData writeToFile:pdfFilePath atomically:YES];
}
Rohit Answer is working perfectly,But it works only single page so i just Added some code for all pages displaying with image(image shown in single page reaming pages are looks same).Thanks #Rohit
NSString *path = [[NSBundle mainBundle] pathForResource:#"PartB" ofType:#"pdf"];
NSURL *docURL = [NSURL fileURLWithPath:path];
NSString *pdfName = [NSString stringWithFormat:#"%#",docURL];
NSLog(#"pdfName: %#", pdfName);
NSData *pdfData = [NSData dataWithContentsOfFile:path];
NSURL *pdfURL = [[NSBundle mainBundle] URLForResource:#"PartB.pdf" withExtension:nil];
CGPDFDocumentRef pdf1 = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
long pageCount = CGPDFDocumentGetNumberOfPages(pdf1);
NSLog(#"the page count %ld",pageCount);
NSMutableData* outputPDFData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)outputPDFData);
CFMutableDictionaryRef attrDictionary = NULL;
attrDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrDictionary, kCGPDFContextTitle, CFSTR("My Doc"));
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, NULL, attrDictionary);
CFRelease(dataConsumer);
CFRelease(attrDictionary);
CGRect pageRect;
// Draw the old "pdfData" on pdfContext
CFDataRef myPDFData = (__bridge CFDataRef) pdfData;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGDataProviderRelease(provider);
for (int k=1; k<=pageCount; k++) {
CGPDFPageRef page3 = CGPDFDocumentGetPage(pdf, k);
pageRect = CGPDFPageGetBoxRect(page3, kCGPDFMediaBox);
CGContextBeginPage(pdfContext, &pageRect);
CGContextDrawPDFPage(pdfContext, page3);
if (k==pageSelect) {
pageRect = CGRectMake(0, 0,100 , 100);
CGImageRef pageImage = [mainImage.image CGImage];
CGContextDrawImage(pdfContext, pageRect, pageImage);
}
CGPDFContextEndPage(pdfContext);
}
CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);
// write new PDFData in "outPutPDF.pdf" file in document directory
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pdfFilePath =[NSString stringWithFormat:#"%#/outPutPDF.pdf",docsDirectory];
[outputPDFData writeToFile:pdfFilePath atomically:YES];
NSLog(#"save the pdf %#",pdfFilePath);
I'm not sure I understand your problem completely. From what I can tell you have a UIView that you're rendering onto a PDF document, and you want to add a signature image and not show it to the user.
If you're trying to add a "signature image" to your pdf, you can add a UIImageView to the UIView that you're rendering to the pdf.
If you don't want the user to see the UIView in the mean time, you could change it's origin to somewhere off bounds, for example:
CGRect originalFrame = mainView.frame;
CGRect newFrame = mainView.frame;
newFrame.origin.x = -newFrame.size.width;
newFrame.origin.y = -newFrame.size.height;
mainView.frame = newFrame;
//do all your PDF stuff here
mainView.frame = originalFrame;
I hope that helps. If it doesn't, please clarify the problem :)
i'm trying to figure out this problem but failed after doing every thing i found on OS or google. Problem is that when i convert UIImage to NSData using UIImageJPEGRepresentation or UIImagePNGRepresentation it increases the memory size to 30Mb (believe me or not).
Here is my code
myImage= image;
LoginSinglton*loginObj = [LoginSinglton sharedInstance];
NSError *error;
NSData *pngData = UIImageJPEGRepresentation(image, scaleValue); //scaleVale is 1.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
self.imageCurrentDateAndTime =[self getTimeAndDate];
self.filePathAndDirectory = [documentsPath stringByAppendingPathComponent:#"Photos Dir"];
NSLog(#"Documents path %#",self.filePathAndDirectory);
if (![[NSFileManager defaultManager] createDirectoryAtPath:self.filePathAndDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
self.imageName= [NSString stringWithFormat:#"photo-%#-%#.jpg",loginObj.userWebID,self.imageCurrentDateAndTime];
NSString *filePath = [self.filePathAndDirectory stringByAppendingPathComponent:self.imageName];
[pngData writeToFile:filePath atomically:YES]; //Write the file
[self writeImageThumbnailToFolder:image];
[self writeImageHomeViewThumbnailToFolder:image];
I have tried following solution as well
UIImageJPEGRepresentation - memory release issue
1- Used #autoreleasepool
2- done pngData = nil;
but still facing that memory issue.
EDIT I think i'm not able to convey my problem. It's ok if UIImageJPEGRepresentation taking huge memory,but memory should back to it's earlier position after saving that image. Hope this will help you in detail.
Use a scaleValue of less than 1. Even 0.9 will massively reduce the memory footprint with minimal quality loss.
Try this:
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
If not got solution for your expectation, no need to worry try this too:
UIImage *small = [UIImage imageWithCGImage:original.CGImage scale:0.25 orientation:original.imageOrientation];
Get sample app form here for editing image or scale:
http://mattgemmell.com/2010/07/05/mgimageutilities/
To resize using minimum memory try Using CoreGraphics
SO answer by #Mina Nabil, see full answer for more details
#import <ImageIO/ImageIO.h>
-(UIImage*) resizedImageToRect:(CGRect) thumbRect {
CGImageRef imageRef = [inImage CGImage];
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
if (alphaInfo == kCGImageAlphaNone)
alphaInfo = kCGImageAlphaNoneSkipLast;
// Build a bitmap context that's the size of the thumbRect
CGContextRef bitmap = CGBitmapContextCreate(
NULL,
thumbRect.size.width, // width
thumbRect.size.height, // height
CGImageGetBitsPerComponent(imageRef), // really needs to always be 8
4 * thumbRect.size.width, // rowbytes
CGImageGetColorSpace(imageRef),
alphaInfo
);
// Draw into the context, this scales the image
CGContextDrawImage(bitmap, thumbRect, imageRef);
// Get an image from the context and a UIImage
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage* result = [UIImage imageWithCGImage:ref];
CGContextRelease(bitmap); // ok if NULL
CGImageRelease(ref);
return result;
}
i render Thumbnails of newly recieved PDF Document to the Documents-Directory.
I'm using the following code:
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("thedoc.pdf"), NULL, NULL);
CGPDFDocumentRef bookPDF = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
UIGraphicsBeginImageContext(CGSizeMake(100, 130));
NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(bookPDF);
CGContextRef context = UIGraphicsGetCurrentContext();
for(int i = 0; i < totalNum; i++ ) {
CGRect arect = CGRectMake(0,0,200,282);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, 141);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetGrayFillColor(context, 1.0, 1.0);
CGContextFillRect(context, arect);
// Grab the first PDF page
CGPDFPageRef page = CGPDFDocumentGetPage(bookPDF, i + 1);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, arect, 0, true);
// And apply the transform.
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, page);
// Create the new UIImage from the context
UIImage* thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
if (thumbnailImage == nil) {
NSLog(#"ERROR during creation of PNG");
}
// SAVE THE IMAGE TO DOCUMENTS-DIRECTORY
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/thumbPage%i.png",theLocalFolder ,i]];
// Write image to PNG
BOOL writtenBool = [UIImagePNGRepresentation(thumbnailImage) writeToFile:pngPath atomically:YES];
// END SAVE THE IMAGE TO DOCUMENT-DIRECTORY
CGContextRestoreGState(context);
NSLog(#"Rendering PDF-Thumbnail %i (%i): %#", i, writtenBool, [NSString stringWithFormat:#"%#/thumbPage%i.png",theLocalFolder ,i]);
}
There is no error in Console, but the PNGs are not stored to the documents-Directory. The BOOL
writtenBool
is "0", what means that the write-action was not succuessful. I don't know why. I write the path in
pngPath
also to the console and the path is correct. If i open a terminal and write
open <<copyed path from console>>
it opens the correct path in finder.
What could cause this not to work? I had a look at the api but there seems to be no
error:
for UIImagePNGRepresentation: writeToFile:
Thanks for your help!
UIImagePNGRepresentation(thumbnailImage) return a NSData object
for NSData object, you can use these methods:
writeToFile:atomically:,
writeToFile:options:error:,
writeToURL:atomically:,
writeToURL:options:error:,
so, you can try use code like BOOL writtenBool = [UIImagePNGRepresentation(thumbnailImage) writeToFile:pngPath options:NSDataWritingAtomic error:&error]; to see what happened.