此方法可以快速的將表格頁面繪制成一個(gè)PDF文件惹盼,僅傳入一個(gè)tableView即可
其中 判斷文件路徑 的方法是自己擴(kuò)展FileManager寫的澡刹,可根據(jù)自己的需求進(jìn)行調(diào)整或刪除
分享是使用 UIActivityViewController 調(diào)用自身的分享方法
使用此方法時(shí)字旭,需要將tableView的style設(shè)置為grouped
//將tableView頁面繪制成PDF
func pdfDataWithTableView(tableView: UITableView) {
//記錄tableView的bounds
let originalBounds = tableView.bounds
//計(jì)算tableView的內(nèi)容的高度锉矢,方便后面的PDF分頁
let fitSize = tableView.sizeThatFits(CGSize(width: originalBounds.size.width, height: tableView.contentSize.height))
//將tableView的大小調(diào)整為適合大小藕溅,以便在后續(xù)操作中用于生成PDF頁面
tableView.bounds = CGRect(origin: .zero, size: fitSize)
//定義了PDF頁面的邊界框大小棚壁,其中寬度與tableView的寬度相同杯矩,高度與視圖控制器的視圖高度相關(guān)
let pdfPageBounds = CGRect(x: 0, y: 0, width: tableView.frame.width, height: self.view.frame.height)
//創(chuàng)建一個(gè)NSMutableData對(duì)象,用于存儲(chǔ)生成的PDF數(shù)據(jù)
let pdfData = NSMutableData()
//開始一個(gè)PDF上下文袖外,將繪制的內(nèi)容保存到pdfData中史隆,并使用定義的頁面邊界框大小
UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil)
var pageOriginY: CGFloat = 0
while pageOriginY < fitSize.height {
//創(chuàng)建一個(gè)新的PDF頁面
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
//保存當(dāng)前圖形上下文的狀態(tài)
UIGraphicsGetCurrentContext()!.saveGState()
//通過向上移動(dòng)坐標(biāo)原點(diǎn),將內(nèi)容繪制到正確的位置曼验。
UIGraphicsGetCurrentContext()!.translateBy(x: 0, y: -pageOriginY)
//將tableView的內(nèi)容渲染到PDF上下文中泌射。
tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
//恢復(fù)之前保存的圖形上下文狀態(tài)。
UIGraphicsGetCurrentContext()!.restoreGState()
//更新pageOriginY鬓照,以便渲染下一頁的內(nèi)容熔酷。
pageOriginY += pdfPageBounds.size.height
//更改tableView視圖的內(nèi)容偏移量
tableView.contentOffset = CGPoint(x: 0, y: pageOriginY)
}
//結(jié)束PDF上下文,完成PDF文檔的生成
UIGraphicsEndPDFContext()
//將tableView的邊界框大小恢復(fù)到原始大小
tableView.bounds = originalBounds
//判斷文件路徑是否存在豺裆,不存在則創(chuàng)建
if !FileManager.judgeFileOrFolderExists(filePath: Utils.vinPDFPath) {
FileManager.createFolder(folderPath: Utils.vinPDFPath)
}
let docURL = URL(fileURLWithPath: Utils.vinPDFPath + "\(model.base.companyName).pdf")
//保存文件到指定的路徑拒秘,并進(jìn)行分享操作
do {
try pdfData.write(to: docURL, options: .atomic)
sharePDF(docURL: docURL)
} catch {
PrintLog(message: error.localizedDescription)
}
}
//分享
private func sharePDF(docURL: URL){
let activityItems = [docURL as Any]
let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityController.modalPresentationStyle = .fullScreen
activityController.completionWithItemsHandler = {
(type, flag, array, error) -> Void in
if flag == true {
PrintLog(message: "成功")
} else {
PrintLog(message: "失敗")
}
}
self.present(activityController, animated: true, completion: nil)
}
注:此方法可能會(huì)造成頁面數(shù)據(jù)內(nèi)容的分割