渲染PDF
首先UIPrintPageRender添加创建data的分类
关联需要渲染的对象
调用方法渲染,返回NSData
1.首先UIPrintPageRender添加创建data的分类
@implementation UIPrintPageRenderer (LBPDF)
- (NSData*) printToPDF {
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil );
[self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
CGRect bounds = UIGraphicsGetPDFContextBounds();
for ( int i = 0 ; i < self.numberOfPages ; i++ ) {
UIGraphicsBeginPDFPage();
[self drawPageAtIndex: i inRect: bounds];
}
UIGraphicsEndPDFContext();
return pdfData;
}
@end
2. 关联需要渲染的对象 ,3. 调用方法渲染,返回NSData
- (void)builderPDFView{
UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
[render addPrintFormatter:self.questionWebView.viewPrintFormatter startingAtPageAtIndex:0];//关联对象
NSUInteger contentHeight = self.questionWebView.scrollView.contentSize.height;
NSUInteger contentWidth = self.questionWebView.scrollView.contentSize.width;
CGSize contentSize = CGSizeMake(contentWidth, contentHeight);
// 需要打印的frame
CGRect printableRect = CGRectMake(0,
100,
contentSize.width,
contentSize.height/5);
// 纸张的规格(标准PDF格式)
CGRect paperRect = CGRectMake(0, 0, 595.2, 841.8);
[render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"]; //因为是readonly属性,所以我们只能用KVC 进行赋值
//设置pdf边距
[render setValue:[NSValue valueWithCGRect:CGRectInset(paperRect, 10, 10)] forKey:@"printableRect"];
NSData *pdfData = [render printToPDF];
NSString *fileUrl = [NSString stringWithFormat:@"%@temp.pdf",NSTemporaryDirectory()];
[pdfData writeToFile:fileUrl atomically: YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:fileUrl]) {
NSLog(@"本地存在");
}
NSURL *fileUrlPath = [NSURL fileURLWithPath:fileUrl];
NSString*textToShare =@"要分享的文本内容";
NSArray*activityItems =@[fileUrlPath];
UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
[self.weakVC presentViewController: activityVC animated:YES completion:nil];
}
网友评论