如何在没有分页符的情况下生成PDF

时间:2014-04-09 06:01:17

标签: ios objective-c pdf

我使用以下代码将我的WebView转换为PDf。

 UIWebView *webView = self.webView;
        NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];

        int height = [heightStr intValue];
        //  CGRect screenRect = [[UIScreen mainScreen] bounds];
        //  CGFloat screenHeight = (self.contentWebView.hidden)?screenRect.size.width:screenRect.size.height;
        CGFloat screenHeight = webView.bounds.size.height;
            int pages = ceil(height / screenHeight);

        NSMutableData *pdfData = [NSMutableData data];
        UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);
        CGRect frame = [webView frame];
        for (int i = 0; i < pages; i++) {
            // Check to screenHeight if page draws more than the height of the UIWebView
            if ((i+1) * screenHeight  > height) {
                CGRect f = [webView frame];
                f.size.height -= (((i+1) * screenHeight) - height);
                f.size.width  = self.webView.bounds.size.width*1.6;
                [webView setFrame: f];
            }

            UIGraphicsBeginPDFPage();
            CGContextRef currentContext = UIGraphicsGetCurrentContext();
            //      CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins

            [[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO];
            [webView.layer renderInContext:currentContext];
        }

        UIGraphicsEndPDFContext();
        // Retrieves the document directories from the iOS device
        NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

        NSString* documentDirectory = [documentDirectories objectAtIndex:0];
        NSString* documentDirectoryFilename =[documentDirectory stringByAppendingString:@"/pdfFile.PDF"] ;

        // instructs the mutable data object to write its context to a file on disk
        [pdfData writeToFile:documentDirectoryFilename atomically:YES];
        [webView setFrame:frame];

但问题是如图所示,它会生成带分页符的PDF。 enter image description here

我不希望这个页面中断。任何人都建议我该怎么做。

2 个答案:

答案 0 :(得分:1)

您在此处设置页面尺寸

    UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);

目前设为webView.bounds

使用适当的值更改它。

答案 1 :(得分:0)

这个小css对我有用。

  @media print {
        .avoid_pagebreak { display: block; page-break-inside:avoid; page-break-before: auto; }
    }
  ...
  <div class="avoid_pagebreak">
  ...
  </div>