Reputation:
I have an html file which contains static and dynamic data both, and I need to generate a PDF file from that html file. I am able to create PDF file but it only prints the first page. I need a three page PDF File. I have used following two functions to draw and save the PDF file. My code is :
func exportHTMLContentToPDF(HTMLContent: String) {
let printFormatter = UIMarkupTextPrintFormatter(markupText: HTMLContent)
let printPageRenderer = CustomPrintPageRenderer()
printPageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)
let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer: printPageRenderer)
pdfFilename = "\(AppDelegate.getAppDelegate().getDocDir())/FinalPdf.pdf"
pdfData?.write(toFile: pdfFilename, atomically: true)
print(pdfFilename)
}
func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
let data = NSMutableData()
UIGraphicsBeginPDFContextToData(data, CGRect.zero, nil)
UIGraphicsBeginPDFPage()
printPageRenderer.drawPage(at: 0, in: UIGraphicsGetPDFContextBounds())
UIGraphicsEndPDFContext()
return data
}
I have followed app coda tutorial for this. For multiple pages, it says to include the beginning of the PDF page creation and the print page renderer drawing into a loop. Please help me to create multiple page PDF.
Upvotes: 3
Views: 2959
Reputation: 358
Use the code below in place of your current drawPDFUsingPrintPageRenderer function:
func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
let data = NSMutableData()
UIGraphicsBeginPDFContextToData(data, CGRect.zero, nil)
printPageRenderer.prepare(forDrawingPages: NSMakeRange(0, printPageRenderer.numberOfPages))
let bounds = UIGraphicsGetPDFContextBounds()
for i in 0...(printPageRenderer.numberOfPages - 1) {
UIGraphicsBeginPDFPage()
printPageRenderer.drawPage(at: i, in: bounds)
}
UIGraphicsEndPDFContext();
return data
}
Viola, multiple page's.
Upvotes: 6