我有一个(待办事项)列表应用程序。数据布置在具有自定义单元格的 diffable dataSource tableview 中。我有一个功能正常的下拉菜单,我正在尝试添加一个print
按钮,以便用户可以根据需要打印出列表(在许多列表应用程序中似乎是标准的)。
到目前为止,我在按钮的操作中有以下内容:
let printController = UIPrintInteractionController.shared
printController.delegate = self
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.outputType = .general
printInfo.jobName = "Print TableView"
printController.printInfo = printInfo
let tableViewPDF = self?.tableView.exportAsPdfFromTable()
printController.printingItem = tableViewPDF
let formatter = UIPrintFormatter()
formatter.perPageContentInsets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)
printController.printFormatter = formatter
printController.present(animated: true, completionHandler: nil)
和代表:
extension ListTableViewController: UIPrintInteractionControllerDelegate {
func printInteractionControllerParentViewController(_ printInteractionController: UIPrintInteractionController) -> UIViewController? {
return self
}
}
如您所见,我正在尝试将 tableview 转换为 PDF 并打印(其他可能会更好?)。.exportAsPdfFromTable()
tableView 上的方法是一个UITableView
扩展,如下:
extension UITableView {
// Export pdf from UITableView and save pdf in drectory and return pdf file path
func exportAsPdfFromTable() -> String {
let originalBounds = self.bounds
self.bounds = CGRect(x:originalBounds.origin.x, y: originalBounds.origin.y, width: self.contentSize.width, height: self.contentSize.height)
let pdfPageFrame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.contentSize.height)
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
guard let pdfContext = UIGraphicsGetCurrentContext() else { return "" }
self.layer.render(in: pdfContext)
UIGraphicsEndPDFContext()
self.bounds = originalBounds
// Save pdf data
return self.saveTablePdf(data: pdfData)
}
// Save pdf file in document directory
func saveTablePdf(data: NSMutableData) -> String {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docDirectoryPath = paths[0]
let pdfPath = docDirectoryPath.appendingPathComponent("tablePdf.pdf")
if data.write(to: pdfPath, atomically: true) {
return pdfPath.path
} else {
return ""
}
}
}
结果是打印控制器显示一个空白页。关于我所缺少的任何想法?