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

时间:2014-10-09 07:31:46

标签: ios iphone uiwebview pdf-generation

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

How to Convert UIView to PDF within iOS?

任何帮助

2 个答案:

答案 0 :(得分:2)

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

添加Category UIPrintPageRenderer以获取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的{​​{1}} property

UIWebView

答案 1 :(得分:0)

你是对的,你需要一个Webview。

如果捆绑包中有.pdf文件,只需执行以下操作:

@implementation{
     UIWebView *documentWebView;
}

- (void)viewDidLoad{     //Or any other method that you want to create the webview with.

    //Getting the full screen size
    UIWindow* currentWindow = [UIApplication sharedApplication].keyWindow;
    CGRect fullScreenRect = currentWindow.bounds;

    //Getting the pdf from the bundle ; change filepath with URL if its from the internet
    filePath = [[NSBundle mainBundle] pathForResource:@"YourPDFFileName" ofType:@"pdf"];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];

    //Creating the view programatically, because I'm like that.
    documentWebView = [[UIWebView alloc] initWithFrame:CGRectMake(fullScreenRect.origin.x, fullScreenRect.origin.y, fullScreenRect.size.width, fullScreenRect.size.height)];
    documentWebView.scalesPageToFit = YES;

    //Setting a back button to dismiss the view.
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(fullScreenRect.size.width-115, 10, 100, 30)];
    backButton.backgroundColor = [UIColor grayColor];
    backButton.alpha = 0.8;
    [backButton setTitle:@"Back" forState:UIControlStateNormal];

    //Linking the action & the button
    [backButton addTarget:self action:@selector(closeWebView:) forControlEvents:UIControlEventTouchUpInside];

    //Loading the pdf into the actual view
    [documentWebView loadRequest:request];

    //Adding the views to the main view
    [currentWindow addSubview:documentWebView];
    [documentWebView addSubview:backButton];
}

//Dismissing the view
- (IBAction)closeWebView:(id)sender{
    [documentWebView removeFromSuperview];
    [documentWebView release];

}