在iOS 6时代实现PDF功能需深入理解核心图形框架,以下是关键技术实现方案:

PDF文档生成(Core Graphics层)
// 创建PDF上下文
CGRect pageFrame = CGRectMake(0, 0, 612, 792); // 标准Letter尺寸
UIGraphicsBeginPDFContextToFile(@"/path/to/file.pdf", pageFrame, nil);
// 开启新页面
UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
// 绘制文本
CGContextRef context = UIGraphicsGetCurrentContext();
UIFont font = [UIFont systemFontOfSize:12];
NSDictionary attrs = @{NSFontAttributeName: font};
[@"iOS 6 PDF示例" drawAtPoint:CGPointMake(72, 72) withAttributes:attrs];
// 绘制图像
UIImage logo = [UIImage imageNamed:@"app_logo"];
[logo drawInRect:CGRectMake(200, 200, 100, 100)];
// 结束上下文
UIGraphicsEndPDFContext();
关键细节
- 路径需使用
NSDocumentDirectory保证沙盒可用性- 坐标系原点在左下角(与UIKit左上角相反)
PDF渲染与展示(UIWebView方案)
// 获取文档路径
NSString docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString pdfPath = [docPath stringByAppendingPathComponent:@"sample.pdf"];
// WebView加载
UIWebView pdfViewer = [[UIWebView alloc] initWithFrame:self.view.bounds];
NSURLRequest request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfPath]];
[pdfViewer loadRequest:request];
[self.view addSubview:pdfViewer];
适配要点
- iOS 6需手动处理内存警告释放WebView
- 大文件需添加
NSURLRequestReturnCacheDataElseLoad缓存策略
PDF交互功能实现(Quartz 2D解析)
1 获取文档元数据
CGPDFDocumentRef pdfDoc = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:pdfPath]);
size_t pageCount = CGPDFDocumentGetNumberOfPages(pdfDoc);
// 读取作者信息
CGPDFDictionaryRef infoDict = CGPDFDocumentGetInfo(pdfDoc);
CGPDFStringRef author;
if(CGPDFDictionaryGetString(infoDict, "Author", &author)) {
NSString authorStr = (__bridge NSString )CGPDFStringCopyTextString(author);
NSLog(@"文档作者: %@", authorStr);
}
2 精确文本选择
// 使用CGPDFContentStream解析文本
CGPDFPageRef page = CGPDFDocumentGetPage(pdfDoc, 1);
CGPDFContentStreamRef stream = CGPDFContentStreamCreateWithPage(page);
CGPDFScannerRef scanner = CGPDFScannerCreate(stream, table, NULL);
CGPDFScannerScan(scanner);
性能优化关键策略
-
分块加载技术

// 仅渲染当前可见区域 CGRect visibleRect = scrollView.bounds; CGPDFPageRef page = CGPDFDocumentGetPage(doc, currentPage); CGAffineTransform transform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, visibleRect, 0, true); CGContextConcatCTM(ctx, transform); CGContextDrawPDFPage(ctx, page); -
内存管理黄金法则
// 使用@autoreleasepool分段释放 for (int i=0; i<totalPages; i++) { @autoreleasepool { CGPDFPageRef page = CGPDFDocumentGetPage(doc, i+1); // 处理单页数据... } }
安全增强方案
// 添加密码保护
NSDictionary options = @{
(NSString )kCGPDFContextOwnerPassword: @"masterKey123",
(NSString )kCGPDFContextUserPassword: @"userAccess456"
};
UIGraphicsBeginPDFContextToFile(pdfPath, pageFrame, options);
兼容性处理要点
- 字体嵌入:使用
CTFontDescriptorRef嵌入非系统字体 - 旧设备适配:iPad 1需禁用透明图层加速
- 方向切换:重写
willAnimateRotationToInterfaceOrientation重置PDF视图
专家建议
优先采用CGPDFOperatorTable而非第三方解析库,避免iOS 6的符号冲突问题
实战思考:您在处理PDF签名或表单交互时是否遇到坐标转换难题?欢迎分享具体场景,我将提供针对性解决方案。

原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/14946.html