2011-06-11 98 views
3

我想将iPhone上的本地HTML文件转换为PDF文档。我已经使用了我在网上找到的以下代码来从图片生成PDF文件,我试图用html文件替换图片,但是失败了。我非常感谢你的帮助。 由于提前,将html文件转换为PDF使用Cocoa-Touch的iOS文档

// Our method to create a PDF file natively on the iPhone 
// This method takes two parameters, a CGRect for size and 
// a const char, which will be the name of our pdf file 
void CreatePDFFile (CGRect pageRect, const char *filename) { 

    // This code block sets up our PDF Context so that we can draw to it 
    CGContextRef pdfContext; 
    CFStringRef path; 
    CFURLRef url; 
    CFMutableDictionaryRef myDictionary = NULL; 
    // Create a CFString from the filename we provide to this method when we call it 
    path = CFStringCreateWithCString (NULL, filename, 
             kCFStringEncodingUTF8); 
    // Create a CFURL using the CFString we just defined 
    url = CFURLCreateWithFileSystemPath (NULL, path, 
             kCFURLPOSIXPathStyle, 0); 
    CFRelease (path); 
    // This dictionary contains extra options mostly for 'signing' the PDF 
    myDictionary = CFDictionaryCreateMutable(NULL, 0, 
              &kCFTypeDictionaryKeyCallBacks, 
              &kCFTypeDictionaryValueCallBacks); 
    CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File")); 
    CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name")); 
    // Create our PDF Context with the CFURL, the CGRect we provide, and the above defined dictionary 
    pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary); 
    // Cleanup our mess 
    CFRelease(myDictionary); 
    CFRelease(url); 
    // Done creating our PDF Context, now it's time to draw to it 

    // Starts our first page 
    CGContextBeginPage (pdfContext, &pageRect); 

    // Draws a black rectangle around the page inset by 50 on all sides 
    CGContextStrokeRect(pdfContext, CGRectMake(50, 50, pageRect.size.width - 100, pageRect.size.height - 100)); 

    // This code block will create an image that we then draw to the page 
    const char *picture = "Picture"; 
    CGImageRef image; 
    CGDataProviderRef provider; 
    CFStringRef picturePath; 
    CFURLRef pictureURL; 

    picturePath = CFStringCreateWithCString (NULL, picture, 
             kCFStringEncodingUTF8); 
    pictureURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), picturePath, CFSTR("png"), NULL); 
    CFRelease(picturePath); 
    provider = CGDataProviderCreateWithURL (pictureURL); 
    CFRelease (pictureURL); 
    image = CGImageCreateWithPNGDataProvider (provider, NULL, true, kCGRenderingIntentDefault); 
    CGDataProviderRelease (provider); 
    CGContextDrawImage (pdfContext, CGRectMake(200, 200, 207, 385),image); 
    CGImageRelease (image); 


    // End image code 

    // Adding some text on top of the image we just added 
    CGContextSelectFont (pdfContext, "Helvetica", 16, kCGEncodingMacRoman); 
    CGContextSetTextDrawingMode (pdfContext, kCGTextFill); 
    CGContextSetRGBFillColor (pdfContext, 0, 0, 0, 1); 
    const char *text = "Hello World!"; 
    CGContextShowTextAtPoint (pdfContext, 260, 390, text, strlen(text)); 
    // End text 

    // We are done drawing to this page, let's end it 
    // We could add as many pages as we wanted using CGContextBeginPage/CGContextEndPage 
    CGContextEndPage (pdfContext); 

    // We are done with our context now, so we release it 
    CGContextRelease (pdfContext); 
} 

- (IBAction)createPDF:(id)sender { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *saveDirectory = [paths objectAtIndex:0]; 
    NSString *saveFileName = @"myPDF.pdf"; 
    NSString *newFilePath = [saveDirectory stringByAppendingPathComponent:saveFileName]; 
    const char *filename = [newFilePath UTF8String]; 
    CreatePDFFile(CGRectMake(0, 0, 612, 792),filename); 
} 
+0

查看https://discussions.apple.com/thread/2222497?threadID=2222497&tstart=0 – Jhaliya 2011-06-11 13:47:51

回答

6

将HTML转换为PDF格式,你需要:

  • 创建一个web视图并加载HTML。
  • 采取Webview捕获。
  • 将其转换成PDF文件。

第二步(的WebView捕获)都必须做一次您的WebView内容加载 对于这种捕获你可以找到样品中How Do I Take a Screen Shot of a UIView? 然后使用此背景下转换成PDF文件。

对于web视图,您不需要显示它,只需在屏幕上添加视图即可创建它。

编辑: 其他细节,为的WebView高度可以计算的WebView内容高度和改变你的WebView框架

- (void)webViewDidFinishLoad:(UIWebView *)theWebView { 
    NSUInteger contentHeight = [[theWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.body.scrollHeight;"]] intValue]; 
    NSUInteger contentWidth = [[theWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.body.scrollWidth;"]] intValue]; 
    [theWebView setFrame:CGRectMake(0, 0, contentWidth, contentHeight)]; 
} 
+3

如果** html **内容的高度很大,该怎么办? – Jhaliya 2011-06-11 13:45:59

+0

我编辑了帖子,并添加了将webview框架调整为html内容的方式 – AmineG 2011-06-11 13:53:57

+0

我以前尝试过这种技术,并且很难在不模糊文本的情况下获得足够高分辨率的WebView的大小精细的屏幕截图。 – Philosophistry 2012-09-04 21:03:52

7

我创建了一个基于每一个很好的建议,我发现周围的类。我一直在挖掘很多,我希望我的课程能够为尝试从某些HTML源代码直接创建多页PDF的人提供一些良好的开端。

你会一些基本的示例代码在这里找到整个代码:https://github.com/iclems/iOS-htmltopdf

我刚刚同一个问题,因为你和我的要求是: - 完整的PDF(真正的文本,没有位图) - 智能多页(与每X像素切割全高度webview相比...)

因此,我使用的解决方案非常好,因为它使用iOS用于分割页面以供打印的相同工具。

让我解释一下,我安装一个UIPrintPageRenderer基于Web视图的打印格式(第一尖):

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, CGRectZero, 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; 
} 
+0

这个自我推销的答案是不适合问问题(除了不适当的,因为它是一个副本)。 OP已经*有他们正在使用的代码*并需要帮助。将链接发布到您自己的项目中作为对这样的问题的答案看起来像垃圾邮件。 – 2012-11-19 21:33:17

+0

感谢您创造这个! – 3lvis 2013-01-22 04:34:06

+0

您好我有一个要求,我必须加载一个HTML文件,该HTML文件将具有文本字段,标签,复选框按钮等我必须得到的数据无论用户将进入,然后我必须将其转换为PDF用户输入数据。 – 2013-04-18 19:47:05