Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

iphone - Xcode save a PDF as Image?

I have a question, is it possible to save a PDF to Camera Roll? I mean, I know how to save a Picture, but can you save a PDF as well?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @jshin47 - the following fragment will get you going:

This converts a pdf called test.pdf sitting in the local documents directory to a png called test.png. I've used A4 dimensions for the PDF, but if you're not in UK / Europe you might need to US letter sizes.

NSString* localDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString* pdfPath = [localDocuments stringByAppendingPathComponent:@"test.pdf"];

// create a sample PDF (just for illustration)
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[@"Test string" drawInRect:CGRectMake(50, 50, 300, 200) withFont: [UIFont systemFontOfSize: 48.0]];
UIGraphicsEndPDFContext();

NSURL* url = [NSURL fileURLWithPath: pdfPath];

CGPDFDocumentRef document = CGPDFDocumentCreateWithURL ((CFURLRef) url);

UIGraphicsBeginImageContext(CGSizeMake(596,842));
CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(currentContext, 0, 842);
CGContextScaleCTM(currentContext, 1.0, -1.0); // make sure the page is the right way up

CGPDFPageRef page = CGPDFDocumentGetPage (document, 1); // first page of PDF is page 1 (not zero)
CGContextDrawPDFPage (currentContext, page);  // draws the page in the graphics context

UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSString* imagePath = [localDocuments stringByAppendingPathComponent: @"test.png"];
[UIImagePNGRepresentation(image) writeToFile: imagePath atomically:YES];

UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); // do error checking in production code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...