问题描述
我想将一些html页面转换为PDF格式。是否可以使用iPhone SDK?
I want to convert some html page into PDF format.Is it possible using iPhone SDK?
是否有可用的API或第三方库?我已经搜索了解决方案,但无法找到任何实质性的材料。
Are there any APIs or 3rd party libraries available to so? I have googled around for the solution but was not able to find any substantial material.
干杯
推荐答案
我根据我发现的每一个好建议创建了一个课程。我一直在挖掘很多东西,我希望我的课程能为那些试图直接从某些HTML源代码创建多页PDF的人提供一个良好的开端。
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
我遇到了与您相同的问题,我的要求是:
- 完整PDF(真实文本,无位图)
- 智能多页(与每X像素切割一个全高webview相比......)
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...)
因此,我使用的解决方案非常好,因为它采用相同的方法iOS用于分割打印页面的工具。
Thus, the solution I use is pretty nice as it resorts to the same tools iOS uses to split pages for print.
让我解释一下,我根据网页视图打印格式化程序设置了一个UIPrintPageRenderer(第一个提示):
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];
与此同时,我在UIPrintPageRenderer上创建了一个类别来支持:
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;
}
这篇关于iPhoneSDK中的HTML到PDF转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!