Objective-C PDF对象。尽我所能帮助我们摆脱Core Foundation的头痛。
在您的Podfile中,添加以下行:
pod "MTPDF"
pod? => https://github.com/CocoaPods/CocoaPods/
注意:如果 pods 库仅包含分类,您可能需要将 -all_load
添加到您的目标构建设置中的 "其它链接器标志"。
从文件中读取PDF
MTPDF *pdf = [MTPDF PDFWithContentsOfFile:path];
pdf.pages.count // => 3
pdf.isEncrypted // => NO
pdf.title // => @"Forever Young"
从URL中读取PDF
MTPDF *pdf = [MTPDF PDFWithContentsOfURL:url];
从数据创建PDF
MTPDF *pdf = [MTPDF PDFWithData:data];
修改PDF
MTPDF *pdf = [MTPDF PDFWithContentsOfURL:url];
pdf.title = @"New Title";
pdf.author = @"New Author";
pdf.creator = @"New Creator";
pdf.subject = @"New Subject";
将PDF写入文件
[pdf writeToFile:file];
遍历页面
for (MTPDFPage *page in pdf.pages) {
page.size // => (500, 600)
}
在UIView的drawRect中绘制页面(适应视图的高度)
MTPDFPage *page = pdf.pages[0];
// Calculate the size to draw based on the height of the view's rect
CGSize fullSize = page.size;
CGFloat ratio = fullSize.width / fullSize.height;
CGSize aspectFittingSize = CGSizeMake(rect.height * ratio, rect.height);
CGContextRef context = UIGraphicsGetCurrentContext();
[page drawInContext:context atSize:aspectFittingSize];
将页面绘制到CGPDFContext
MTPDFPage *page = pdf.pages[0];
CGRect rect = page.frame;
CGContextRef PDFContext = CGPDFContextCreateWithURL((__bridge CFURLRef)([NSURL fileURLWithPath:destinationFilePath]), &rect, NULL);
[page drawInPDFContext:PDFContext];
CFRelease(PDFContext);
将页面导出为UIImage
UIImage *img = [page imageWithPixelsPerPoint:4];
这允许您以所需的任何分辨率导出PDF。请记住,无论每点的像素数是多少,宽度和高都会从这个因素增长至原始大小。