ios - 如何将 webview 内容创建为 pdf 文件 ios sdk

标签 ios iphone uiwebview pdf-generation

<分区>

如何将 UIWebView 内容创建为 pdf 文件..? 我点击了这个链接,但是这个链接没有创建整个 webview 内容(当我滚动时 webview 上仍然有一些数据)它只是创建一个屏幕显示的 pdf..

How to Convert UIView to PDF within iOS?

任何帮助

最佳答案

使用 UIWebView 中的 UIPrintPageRenderer 按照以下步骤操作:

添加 UIPrintPageRendererCategory 获取 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 的 webViewDidFinishLoad delegate 中使用 UIPrintPageRenderer property UIWebView.

- (void)webViewDidFinishLoad:(UIWebView *)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(@"PDF couldnot be created");
  }
}

关于ios - 如何将 webview 内容创建为 pdf 文件 ios sdk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272717/

相关文章:

ios - 此类对于键 itemname 不符合键值编码

ios - 将 pdf 页面加载到 UIWebView 中

iphone - UIWebView加载本地内容延迟

ios - 不正确的 UITableViewCell 高度与动态 UILabels 和内容压缩/电阻

ios - 当我单击“更多”按钮而不是我离开的 VC 时,如何返回 iOS 中“更多...”按钮的 "Table"

ios - writeToFile :atomically: does not work on iOS 6. 1.3?

iphone - 在自定义 UITableViewCell 中管理 UITextFields 的委托(delegate)

iphone - (iphone) 可以为 C++ 类/结构定义 @property 吗?

javascript - 使用 Javascript 获取 webView 内容的总高度

ios - NSAttributedKey UIAccessibilitySpeechAttributeQueueAnnouncement