才开始正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];
分享到:
相关推荐
iOS UIWebView URL拦截.pdf
UIWebView使用[归纳].pdf
IOS开发中因为引入cocos2dx,导致代码审核不通过无法提交( Apple will stop accepting...不想更新的话,可以修改UIWebView为WKWebView。具体的修改方式使用以下的文件替换cocoas引擎中的UIWebViewImpl-ios.mm文件即可。
UIWebView包含一个scrollView组件,用来将关联web内容实现滚动效果,页面滚动后的UIWebView的面板周围会出现阴影效果,该效果是在四周添加UIImageView实现的,因此移除这种阴影效果的代码如下: ? 1 2 3 4 5 ...
无缝切换 UIWebView 为 WKWebView QQ群号 113767274 有什么问题或者改进的地方大家一起讨论 要求 ARC only ##如何添加到项目中 pod 'IMYWebView' ##使用方法 直接把你项目中的 'UIWebView' 名称替换为 'IMYWebView' ...
IOS之UIWebView的使用(基本知识)共7页.pdf.zip
UIWebView原生与H5交互,pre;confirm;等包含三个H5页面跳转的交互demo
UIWebView+html+css,实现UIWebView中可点击链接,并且可显示gif动画效果
UIWebView和js交互 里边自己写了个H5方便大家理解
UIWebView Web 网页 Demo 代码
使用UIWebView和JS进行交互,可以OC操作js,也可以JS对OC进行交互
这是我在学习ios的过程中写的一个demo,使用UIWebView实现一个简单的浏览器
网页视图的基本使用,网络资源地址字符串的处理,UIWebView属性与协议的综合使用;
UIWebView实现图文混排
这是iPhone开发之UIWebView示例程序,具体参考: http://blog.csdn.net/htttw/article/details/7888557
UIWebVeiw的使用,功能包括“返回上页”“在safari打开”“网页刷新”
UIWebView与JS交互小例子,其中涉及APP向JS提交信息,和JS提交信息给App
ITMS-90809: Deprecated API Usage - New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security and reliability. Unity IOS审核被拒,解决办法,去网上看了好多帖子,...
完美的webView,不懂UIwebView的可以看看