7

Note : UIWebView to PDF working for me.

Now UIView to PDF is also option but wanted to work with below code as same as used to create PDF in UIWebView.

I have done below code so far for UIView's viewPrintFormatter to be able create PDF:

Added Category of UIPrintPageRenderer for getting PDF Data

@interface UIPrintPageRenderer (PDF)
- (NSData*) printToPDF;
@end

@implementation UIPrintPageRenderer (PDF)
- (NSData*) printToPDF
{
  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;
}
@end

Add these define for A4 size

#define kPaperSizeA4 CGSizeMake(595.2,841.8)

Create PDF

UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
[render addPrintFormatter:self.view.viewPrintFormatter startingAtPageAtIndex:0];
//increase these values according to your requirement
float topPadding = 10.0f;
float bottomPadding = 10.0f;
float leftPadding = 10.0f;
float rightPadding = 10.0f;
CGRect printableRect = CGRectMake(leftPadding,
                                  topPadding,
                                  kPaperSizeA4.width-leftPadding-rightPadding,
                                  kPaperSizeA4.height-topPadding-bottomPadding);
CGRect paperRect = CGRectMake(0, 0, kPaperSizeA4.width, kPaperSizeA4.height);
[render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];
[render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];
NSData *pdfData = [render printToPDF];
if (pdfData) {
  [pdfData writeToFile:[NSString stringWithFormat:@"%@/tmp.pdf",NSTemporaryDirectory()] atomically: YES];
}
else
{
  NSLog(@"PDF couldnot be created");
}
Community
  • 1
  • 1
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
  • http://concentricsky.com/blog/2014/jun/creating-multipage-pdf-document-uiviews-ios – Haroon Oct 17 '14 at 07:23
  • @Haroon : I know [view.layer renderInContext:pdfContext]; this can be used. My point is what about view.viewPrintFormatter can also be used for PDF. But issue is it creats blank PDF – Paresh Navadiya Oct 17 '14 at 07:55
  • @PareshNavadiya any success ? I am having exact issue. I am want to create PDF from UIView. UIWebView is working fine. – Maulik Feb 21 '18 at 07:44

0 Answers0