开发者

HTML to PDF conversion in iPhoneSDK

开发者 https://www.devze.com 2023-02-09 08:34 出处:网络
I want to convert some html page into PDF format.Is it possible using iPhone SDK? Are there any APIs or 3rd party libraries available to so? I have googled around for the solution but was not a开发者

I want to convert some html page into PDF format.Is it possible using iPhone SDK?

Are there any APIs or 3rd party libraries available to so? I have googled around for the solution but was not a开发者_JAVA百科ble to find any substantial material.

Cheers


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;
}


Of course it is possible, but either by manually parsing the html and creating a pdf file dynamically using the parsed content, or by using a webview to display the html and render its content to a pdf (as an image) as shown in this topic.

I don't think that there is a 3rd party library that does this.

0

精彩评论

暂无评论...
验证码 换一张
取 消