将UIWebView内容保存为A4大小的PDF

时间:2013-12-04 10:04:55

标签: ios uiwebview pdf-generation

我已经讨论了之前关于这个主题的问题,但 A4大小的PDF 是一个麻烦的部分。

我在下面编写的代码保存了一个正确的(比例)PDF文件,但其大小(面积)是A4大小的4倍。如果我将高度和宽度减半,我会得到A4大小的PDF,但内容会溢出两页。

我该如何解决这个问题? (基本上与缩放有关)

-(void)savePDFFromWebView:(UIWebView*)webView fileName:(NSString*)_fileName
{
    int height, width, header, sidespace;

    height = 1754;
    width = 1240;
    header = 15;
    sidespace = 30;

    // set header and footer spaces

    UIEdgeInsets pageMargins = UIEdgeInsetsMake(header, sidespace, header, sidespace);  

    webView.viewPrintFormatter.contentInsets = pageMargins;

    UIPrintPageRenderer *renderer = [[UIPrintPageRenderer alloc] init];

    [renderer addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];

    CGSize pageSize = CGSizeMake(width, height);
    CGRect printableRect = CGRectMake(pageMargins.left,
                                      pageMargins.top,
                                      pageSize.width - pageMargins.left - pageMargins.right,
                                      pageSize.height - pageMargins.top - pageMargins.bottom);

    CGRect paperRect = CGRectMake(0, 0, pageSize.width, pageSize.height);

    [renderer setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];
    [renderer setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];


    NSData *pdfData = [self printToPDFWithRender:renderer paperRect:paperRect];


    // save PDF file
    NSString *saveFileName = [NSString stringWithFormat:@"%@%dx%d.pdf", _fileName, (int)pageSize.width, (int)pageSize.height];

    NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:saveFileName];
    [pdfData writeToFile: savePath  atomically: YES];
}

- (NSData*) printToPDFWithRenderer:(UIPrintPageRenderer*)renderer  paperRect:(CGRect)paperRect
{
    NSMutableData *pdfData = [NSMutableData data];

    UIGraphicsBeginPDFContextToData( pdfData, paperRect, nil );

    [renderer prepareForDrawingPages: NSMakeRange(0, renderer.numberOfPages)];

    CGRect bounds = UIGraphicsGetPDFContextBounds();

    for ( int i = 0 ; i < renderer.numberOfPages ; i++ )
    {
        UIGraphicsBeginPDFPage();

        [renderer drawPageAtIndex: i inRect: bounds];
    }

    UIGraphicsEndPDFContext();

    return pdfData;
}

1 个答案:

答案 0 :(得分:1)

您提供的paperRect不是A4 size

CGRect paperRect = CGRectMake(0, 0,595.2,841.8);

根据printableRect会改变

CGRect printableRect = CGRectMake(sidespace,
                                  header,
                                  pageSize.width - (sidespace*2),
                                  pageSize.height - (header*2));

此外,我认为无需指定contentInsets,因为printableRect也会这样做。所以remove下面的行

UIEdgeInsets pageMargins = UIEdgeInsetsMake(header, sidespace, header, sidespace);  
webView.viewPrintFormatter.contentInsets = = pageMargins;