我有一个html模板。我想将其转换为pdf并分享。
当我这样做的时候......
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: [self.appDelegate.HTMLContent], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
然后分享的只是html代码。我想将html代码转换为pdf然后分享它。我该怎么做...?
答案 0 :(得分:1)
使用以下方法将HTML字符串转换为A4大小的PDF数据格式:
myObjects
现在使用以下代码分享它:
func generatePDF(from html: String) -> NSData {
let fmt = UIMarkupTextPrintFormatter(markupText: html)
// 2. Assign print formatter to UIPrintPageRenderer
let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAt: 0)
// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printableRect = CGRect(x: 47.6, y: 70.9, width: 500, height: 700) // Adding margin to page
render.setValue(page, forKey: "paperRect")
render.setValue(printableRect, forKey: "printableRect")
// 4. Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)
for i in 0..<render.numberOfPages {
UIGraphicsBeginPDFPage()
render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
}
UIGraphicsEndPDFContext()
return pdfData
}