Tuesday, 31 May 2016

Create multi page pdf in IOS SDK - Tutorial




Create multipage PDF in IOS programmatically

In this we are going to learn, how can we create a multi page PDF file of UIScrollView or UIWebView programmatically in IOS. Below is the code that will help you in creating multi page PDF from UIScrollView.

        NSInteger pageHeight = 700; // Standard page height - adjust as needed
        NSInteger pageWidth = 768; // Standard page width - adjust as needed

  // CREATE PDF 
        NSMutableData *pdfData = [NSMutableData data];
        UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0,0,pageWidth,pageHeight), nil);
        CGContextRef pdfContext = UIGraphicsGetCurrentContext();
        for (int page=0; pageHeight * page < scroll.contentSize.height; page++)
        {
              [scroscrollRectToVisill ble:CGRectMake(0, pageHeight * page, pageWidth, pageHeight) animated:NO];
            UIGraphicsBeginPDFPage();
         CGContextTranslate   CTM(pdfContext, 0, -pageHeight * page);
            [scroll.layerrenderInCont ext:pdfContext];
        }
        
        UIGraphicsEndPDFContext();

//Save to Document Directory

        NSString *fileName = certificateName;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
      writeTo  [pdfDaFta ile:pdfFileName atomically:NO];


In above code, first we will set our pagewidth and pageheight as this will be required to snapshot view as pdf of length specified by pageheight and pagewidth. NOw we can start generating pdf. First, create an instance of NSMutableData. Then we will call UIGraphicsBeginPDFContextToData to start generating PDF.

Then we create a reference to CGContextRef. Now we will start our page loop so that we can get multipage pdf of whole content. Inside our for loop we will move our scroll according to page rect of whom we want to make a PDF page. We will end our context by UIGraphicsEndPDFContext.

To view it will save this to our documents directory.

No comments:
Write comments