将UIWebView存储为多页的PDF

才开始正iOS开发,项目中要求预览doc,docx,ppt,excel等等文档时,将这些文档转换成PDF存储起来。

刚一开始想的方法自然就是Screen Capture,然后图片做PDF,那效果可想而知了,iPhone上截图就是固定的320*480,做出来的都是模糊的。

后来参考了网上的一个将HTML页面转存为多页的PDF的帖子,整了一段时间终于整出来了,效果还行,至少不是单纯图片,而且文字部分都能出来。

1. 子类化 UIPrintPageRenderer用于分页

@interface MyPrintPageRender : UIPrintPageRenderer

- (NSData*) convertUIWebViewToPDFsaveWidth: (float)pdfWidth saveHeight:(float) pdfHeight;

@end




@implementation MyPrintPageRender
{
BOOL _generatingPdf;
}

- (CGRect) paperRect
{
if (!_generatingPdf)
return [super paperRect];

return UIGraphicsGetPDFContextBounds();
}

- (CGRect) printableRect
{
if (!_generatingPdf)
return [super printableRect];

return CGRectInset( self.paperRect, 20, 20 );
}

- (NSData*) convertUIWebViewToPDFsaveWidth: (float)pdfWidth saveHeight:(float) pdfHeight
{
_generatingPdf = YES;

NSMutableData *pdfData = [NSMutableData data];

UIGraphicsBeginPDFContextToData( pdfData, CGRectMake(0, 0, pdfWidth, pdfHeight), nil );

[self prepareForDrawingPages: NSMakeRange(0, 1)];

CGRect bounds = UIGraphicsGetPDFContextBounds();

for ( int i = 0 ; i < self.numberOfPages ; i++ )
{
UIGraphicsBeginPDFPage();

[self drawPageAtIndex: i inRect: bounds];
}

UIGraphicsEndPDFContext();

_generatingPdf = NO;

return pdfData;
}

@end



2. 调用PageRenderer的部分

// width 和height 按自己定义即可,比如说A4大小
float pdfWidth = 595.0f;
float pdfHeight = 842.0f;

MyPrintPageRender *myRenderer = [[MyPrintPageRender alloc] init];
UIViewPrintFormatter *viewFormatter = [self.imgView viewPrintFormatter];
[myRenderer addPrintFormatter:viewFormatter startingAtPageAtIndex:0];

NSData *pdfData = [myRenderer convertUIWebViewToPDFsaveWidth: pdfWidth saveHeight:pdfHeight];

[pdfData writeToFile:fileFullPath atomically:YES];
[myRenderer release];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值