我有一个包含静态和动态数据的html文件,我需要从该html文件生成PDF文件。我能够创建PDF文件,但它只打印第一页。我需要一个三页的PDF文件。我使用了以下两个函数来绘制和保存PDF文件。 我的代码是:
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
}
我已经关注了app coda教程。对于多个页面,它表示包括PDF页面创建的开始和打印页面渲染器绘制到循环中。请帮我创建多页PDF。
答案 0 :(得分:5)
使用下面的代码代替您当前的drawPDFUsingPrintPageRenderer函数:
// let causes the variable to have block level scope and with a loop
// that means that a separately scoped variable is created for each
// loop iteration. This allows each iteration to have its own unique
// value for the variable that doesn't share a higher level scope.
for (let i = 0; i < 5; i++) {
var btn = document.createElement("button");
btn.onclick = function(){alert(i);}
btn.innerHTML = "Button " + i;
document.body.appendChild(btn);
}
Viola,多页。