ios html字符串转pdf,objective c - HTML to PDF conversion on iOS? - Stack Overflow

I created a class based on every good advice I found around. I've been digging a lot and I hope my class will offer some good start for anyone trying to create multi-page PDF directly out of some HTML source.

You'll find the whole code here with some basic sample code : https://github.com/iclems/iOS-htmltopdf

I had just the same issue as you and my requirements were:

- full PDF (real text, no bitmap)

- smart multi-pages (compared to cutting a full height webview every X pixels...)

Thus, the solution I use is pretty nice as it resorts to the same tools iOS uses to split pages for print.

Let me explain, I setup a UIPrintPageRenderer based on the web view print formatter (first tip) :

UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];

[render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];

CGRect printableRect = CGRectMake(self.pageMargins.left,

self.pageMargins.top,

self.pageSize.width - self.pageMargins.left - self.pageMargins.right,

self.pageSize.height - self.pageMargins.top - self.pageMargins.bottom);

CGRect paperRect = CGRectMake(0, 0, self.pageSize.width, self.pageSize.height);

[render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];

[render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];

NSData *pdfData = [render printToPDF];

[pdfData writeToFile: self.PDFpath atomically: YES];

In the meantime, I have created a category on UIPrintPageRenderer to support:

- (NSData*) printToPDF

{

NSMutableData *pdfData = [NSMutableData data];

UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, 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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值