这个问题在这里已经有了答案:
Best Answer-推荐答案 strong>
使用 UIWebView
中的 UIPrintPageRenderer
执行以下步骤:
添加UIPrintPageRenderer
的Category
获取PDF数据
@interface UIPrintPageRenderer (PDF)
- (NSData*) printToPDF;
@end
@implementation UIPrintPageRenderer (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;
}
@end
为 A4 尺寸添加这些定义
#define kPaperSizeA4 CGSizeMake(595.2,841.8)
现在在 UIWebView's
webViewDidFinishLoad
delegate
使用 UIPrintPageRenderer
property
的 UIWebView
.
- (void)webViewDidFinishLoadUIWebView *)awebView
{
if (awebView.isLoading)
return;
UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
[render addPrintFormatter:awebView.viewPrintFormatter startingAtPageAtIndex:0];
//increase these values according to your requirement
float topPadding = 10.0f;
float bottomPadding = 10.0f;
float leftPadding = 10.0f;
float rightPadding = 10.0f;
CGRect printableRect = CGRectMake(leftPadding,
topPadding,
kPaperSizeA4.width-leftPadding-rightPadding,
kPaperSizeA4.height-topPadding-bottomPadding);
CGRect paperRect = CGRectMake(0, 0, kPaperSizeA4.width, kPaperSizeA4.height);
[render setValue:[NSValue valueWithCGRect:paperRect] forKey"paperRect"];
[render setValue:[NSValue valueWithCGRect:printableRect] forKey"printableRect"];
NSData *pdfData = [render printToPDF];
if (pdfData) {
[pdfData writeToFile:[NSString stringWithFormat"%@/tmp.pdf",NSTemporaryDirectory()] atomically: YES];
}
else
{
NSLog(@"DF couldnot be created");
}
}
关于ios - 如何将webview内容创建为pdf文件ios sdk,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/26272717/