17

I am aware of taking the screenshot of UIWebView and converting it to PDF but I need to generate a proper pdf (text as text and not screenshot). Save2PDF is an application which creates proper PDF. Does anybody have an idea how do they do it?

Salil
  • 375
  • 1
  • 5
  • 14
  • maybe this could help: http://stackoverflow.com/questions/5443166/how-to-convert-uiview-to-pdf-within-ios – CarlJ Jun 04 '12 at 13:30
  • Thanks meccan but it seems to be just a screenshot approach. I am aware of libharu but its also a long process. – Salil Jun 04 '12 at 13:49
  • 9
    It is **psychotic** that this question was closed. *"this question will likely solicit debate, arguments, polling, or extended discussion"* ... how does that apply here? Questions such as "what's better, the Stones or the Beatles" or "Is Mac or PC better!!" ... solicit debate, argument etc. This is a straightforward technical engineering question. "How to convert html to pdf, on iOS" .. what could be clearer? Bizarre. – Fattie Jul 05 '14 at 12:13

2 Answers2

32

I created a class based on every good advice I found around. I've been digging a lot and I hope my class will offer some good start for anyone trying to create multi-page PDF directly out of some HTML source.

You'll find the whole code here with some basic sample code : https://github.com/iclems/iOS-htmltopdf

I had just the same issue as you and my requirements were: - full PDF (real text, no bitmap) - smart multi-pages (compared to cutting a full height webview every X pixels...)

Thus, the solution I use is pretty nice as it resorts to the same tools iOS uses to split pages for print.

Let me explain, I setup a UIPrintPageRenderer based on the web view print formatter (first tip) :

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

In the meantime, I have created a category on UIPrintPageRenderer to support:

- (NSData*) printToPDF
{
    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;
}
raidfive
  • 6,603
  • 1
  • 35
  • 32
cwehrung
  • 1,286
  • 13
  • 18
  • This code works well, but my understanding is that the `[render setValue:..]` statements use undocumented methods, and the App Store will reject this code. – brainjam Mar 08 '13 at 16:59
  • 1
    No. `-setValue:forKey:` is not a part of a private api. I have been using it myself on read-only properties and Apple approved my apps. – akashivskyy Apr 13 '13 at 09:56
  • hi I have got one requirement that i have to load one html file and that html file will have text fields, labels, check box buttons etc. I have to get the data whatever user will enter and then i have to convert it into pdf with user enter data. – amit soni Apr 18 '13 at 19:49
  • Amit, know this is a bit late, but you need to make sure that your fields are classes within divs in your html, and not values populated directly by javascript. – GuybrushThreepwood Oct 08 '13 at 18:44
  • @cwehrung will you be able to answer this http://stackoverflow.com/questions/27059369/text-cut-off-at-the-top-and-bottom-of-the-page-of-the-pdf-generated-programmatic question? – ViruMax Nov 24 '14 at 10:31
  • @cwehrung Great answer. Is there any way to use this method to convert HTML to an image instead? I tried doing it with UIGraphicsBeginImageContext but did not have any luck – hishamaus Feb 12 '15 at 05:56
  • Is there any way to make the generated PDF password protected ? – Renjithnath Ramachandran Aug 04 '20 at 14:05
-1

The entire point of this question was text as text and not screenshot

The following answer shows how to make a bitmap screenshot, in a pdf container...

#import <QuartzCore/CALayer.h>

- (NSString *)pdfPath {
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"tmp.pdf"];
  return writableDBPath;
}

- (NSDictionary *)pdfContextDictionary {
  NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:@"J. P. Author", kCGPDFContextAuthor,
                     @"My Cool App", kCGPDFContextCreator,
                     @"This is the Output", kCGPDFContextTitle,
                     nil];
  return d;
}

- (void)printToPDF {
  NSString *path = [self pdfPath];
  UIView *displayView = self.view;
  CGRect pageRect = displayView.bounds;
  if (UIGraphicsBeginPDFContextToFile(path, pageRect, [self pdfContextDictionary]) == NO) {
    return; // error
  }
  UIGraphicsBeginPDFPage();
  CGContextRef context = UIGraphicsGetCurrentContext();
  CALayer *layer = displayView.layer;
  [layer renderInContext:context];
  UIGraphicsEndPDFContext();  
  NSLog(@"[%@ %@] %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), path);
}
Fattie
  • 27,874
  • 70
  • 431
  • 719
self
  • 1,205
  • 1
  • 14
  • 17
  • 1
    Thanks but to me it seems like taking screenshot of the view. Will text be rendered as text rather than image using this method? – Salil Jun 04 '12 at 14:00
  • 3
    In my experience, `-renderInContext:` only outputs raster-based bitmaps for sublayers when rendering into a PDF context, converting vector elements like text into pixelated raster graphics. – Brad Larson Jun 04 '12 at 17:01
  • 1
    Thanks all for the help! I found the solution using this thread http://stackoverflow.com/questions/4356436/generating-a-pdf-using-the-new-printing-stuff-in-ios-4-2 which works perfect for me! I am sorry as my previous searches didn't show me that thread. – Salil Jun 04 '12 at 21:34