最近有一個將網(wǎng)頁轉(zhuǎn)成 pdf 需求,分享一下思路概荷!
參考資料
http://www.cuelogic.com/blog/convert-html-to-pdf-in-ios/
https://stackoverflow.com/questions/6316192/convert-html-file-to-pdf-document-in-ios-using-cocoa-touch
首先我們使用 UIWebView來顯示 html 頁面
UIWebView *webview = [[UIWebView alloc] initWithFrame:self.view.frame];
webview.delegate = self;
webview.scrollView.pagingEnabled = YES;
[self.view addSubview:webview];
// 如果有中文編碼
if (self.html == nil) {
// 傳入 url
if ([[self.url absoluteString] hasSuffix:@"txt"]) {
// txt中文自定義一個編碼方式
NSData *txtData = [NSData dataWithContentsOfURL:self.url];
[self.webview loadData:txtData
MIMEType:@"text/txt"
textEncodingName:@"GBK"
baseURL:nil];
} else {
[self.webview loadRequest:[NSURLRequest requestWithURL:self.url]];
}
} else {
// 直接傳入 html NSString 對象
[self.webview loadHTMLString:self.html baseURL:self.url];
}
顯示完 html 文件后我們?yōu)?UIPrintPageRenderer 添加以下方法,將 UIWebView 渲染成 pdf 文件
- (NSData*) printToPDF {
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, 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;
}
當(dāng)然我們需要設(shè)置 UIPrintPageRenderer 的一些屬性才能正確獲取數(shù)據(jù)。printableRect指定打印的大小猿妈,paperRect指定打印紙的大小,addPrintFormatter:startingAtPageAtIndex: 指定要渲染的對象故河,以及從第幾頁開始渲染
UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
[render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];
// 需要打印的frame
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);
// 打印紙的 frame
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"];
設(shè)置完UIPrintPageRenderer的屬性后吱韭, 我們就可以使用UIPrintPageRenderer對象 的 printToPDF 方法獲取到渲染出來的 NSData 數(shù)據(jù),寫入 pdf 文件
self.pdfData = [render printToPDF];
if (self.pdfPath) {
[self.pdfData writeToFile:self.pdfPath
atomically: YES];
}