您的位置:首页 > 其它

将多页PDF文件转换为多张JPG图片

2014-11-07 16:31 627 查看
一开始以为做不到,不过iOS原生的库还是挺强大的。

直接上Code吧

Obj-c代码



-(void) createJPGsFromPDF:(NSString *)fromPDFName

{

if (fromPDFName == nil || [fromPDFName isEqualToString:@""]) {

return;

}

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDir = [paths objectAtIndex:0];

NSString *docPath = [documentsDir stringByAppendingPathComponent:fromPDFName];

NSURL *fromPDFURL = [NSURL fileURLWithPath:docPath];

CGPDFDocumentRef fromPDFDoc = CGPDFDocumentCreateWithURL((CFURLRef) fromPDFURL);

// Get Total Pages

int pages = CGPDFDocumentGetNumberOfPages(fromPDFDoc);

// Create Folder for store under "Documents/"

NSError *error = nil;

NSFileManager *fileManager = [[NSFileManager alloc] init];

NSString *folderPath = [documentsDir stringByAppendingPathComponent:[fromPDFName stringByDeletingPathExtension]];

[fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:&error];

[fileManager release];

int i = 1;

for (i = 1; i <= pages; i++) {

CGPDFPageRef pageRef = CGPDFDocumentGetPage(fromPDFDoc, i);

CGPDFPageRetain(pageRef);

// determine the size of the PDF page

CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFMediaBox);

// renders its content.

UIGraphicsBeginImageContext(pageRect.size);

CGContextRef imgContext = UIGraphicsGetCurrentContext();

CGContextSaveGState(imgContext);

CGContextTranslateCTM(imgContext, 0.0, pageRect.size.height);

CGContextScaleCTM(imgContext, 1.0, -1.0);

CGContextSetInterpolationQuality(imgContext, kCGInterpolationDefault);

CGContextSetRenderingIntent(imgContext, kCGRenderingIntentDefault);

CGContextDrawPDFPage(imgContext, pageRef);

CGContextRestoreGState(imgContext);

//PDF Page to image

UIImage *tempImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

//Release current source page

CGPDFPageRelease(pageRef);

// Store IMG

NSString *imgname = [NSString stringWithFormat:@"fromPDFName_%d.jpg", i];

NSString *imgPath = [folderPath stringByAppendingPathComponent:imgname];

[UIImageJPEGRepresentation(tempImage, 1.0) writeToFile:imgPath atomically:YES];

}

CGPDFDocumentRelease(fromPDFDoc);

}

转载自/article/4458468.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: