在iOS上将HTML转换为PDF的问题

时间:2013-08-01 06:50:16

标签: html iphone ios pdf

我使用以下代码将HTML转换为PDF(由cwehrung在各个地方发布)

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

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

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

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

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

NSData *pdfData = [render printToPDF];

[pdfData writeToFile: self.PDFpath  atomically: YES];

在UIPrintPageRenderer上创建了一个类别以支持:

-(NSData*) printToPDF
{
    [self doNotRasterizeSubviews:self.view];

    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;
}

我遇到的问题是图像和文字之间的对齐。

我将HTML文件上传到here,很容易在转换后的PDF文件中看到问题,我上传到here。 (见第3册和第6册)

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

我们可以用另一种方式将HTML转换为pdf -

在UIWebview中打开html,代码是 -

-(void)display
{
webViewHeight = [[self.printWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] integerValue];

CGRect screenRect = self.printWebView.frame;

double currentWebViewHeight = webViewHeight;


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageCacheDirPath = [documentsDirectory stringByAppendingPathComponent:@"pdfImages"];
if (![[NSFileManager defaultManager] fileExistsAtPath: imageCacheDirPath])
{
    [[NSFileManager defaultManager] createDirectoryAtPath:imageCacheDirPath withIntermediateDirectories:NO attributes:nil error:NULL];
}
else
{
    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath: imageCacheDirPath error: &error];
    [[NSFileManager defaultManager] createDirectoryAtPath:imageCacheDirPath withIntermediateDirectories:NO attributes:nil error:NULL];
 }

while (currentWebViewHeight > 0)
{
    imageName ++;
     UIGraphicsBeginImageContext(screenRect.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);
    [self.printWebView.layer renderInContext:ctx];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSString *pngPath = [imageCacheDirPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",imageName]];
    if(currentWebViewHeight < 440)
    {
        CGRect lastImageRect = CGRectMake(0,440-currentWebViewHeight, self.printWebView.frame.size.width, currentWebViewHeight);
        CGImageRef lastImageRef = CGImageCreateWithImageInRect([newImage CGImage], lastImageRect);
        newImage = [UIImage imageWithCGImage:lastImageRef];
        CGImageRelease(lastImageRef);
    }
    [UIImagePNGRepresentation(newImage) writeToFile:pngPath atomically:YES];
    [self.printWebView stringByEvaluatingJavaScriptFromString:@"window.scrollBy(0,440);"];
    currentWebViewHeight -= 440;
}
[self drawPdf];
}

- (void) drawPdf
{
CGSize pageSize = CGSizeMake(612, webViewHeight);
NSString *fileName = @"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageCacheDirPath = [documentsDirectory stringByAppendingPathComponent:@"pdfImages"];

NSString *pdfFileName = [imageCacheDirPath stringByAppendingPathComponent:fileName];
NSLog(@"file path:%@",pdfFileName);

UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);

// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);

double currentHeight = 0.0;
for (int index = 1; index <= imageName ; index++)
{
    NSString *pngPath = [imageCacheDirPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", index]];
    UIImage *pngImage = [UIImage imageWithContentsOfFile:pngPath];

    [pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
    currentHeight += pngImage.size.height;
}
UIGraphicsEndPDFContext();
}