我想创建self.view
的多页PDF。我现在要在viewController
之后跟随tableView
,并创建视图的pdf。
这是我所做的,但仅创建单页pdf
func pdfDataWithTableView(tableView: UITableView) {
let priorBounds = tableView.bounds
let fittedSize = tableView.sizeThatFits(CGSize(width:priorBounds.size.width, height:tableView.contentSize.height))
tableView.bounds = CGRect(x:0, y:0, width:fittedSize.width, height:fittedSize.height)
let pdfPageBounds = CGRect(x:0, y:0, width:tableView.frame.width, height:self.view.frame.height)
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds,nil)
var pageOriginY: CGFloat = 0
while pageOriginY < fittedSize.height {
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
UIGraphicsGetCurrentContext()!.saveGState()
UIGraphicsGetCurrentContext()!.translateBy(x: 0, y: -pageOriginY)
tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
UIGraphicsGetCurrentContext()!.restoreGState()
pageOriginY += pdfPageBounds.size.height
}
UIGraphicsEndPDFContext()
tableView.bounds = priorBounds
var docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
docURL = docURL.appendingPathComponent("myPassBook.pdf")
pdfData.write(to: docURL as URL, atomically: true)
share()
}
答案 0 :(得分:0)
保存按钮调用以下功能
func createImg() -> UIImage {
guard tblView.numberOfSections > 0, tblView.numberOfRows(inSection: 0) > 0 else {
let errorImage = UIImage(named: "Error Image")
return errorImage!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: tblView.contentSize.width, height: tblView.contentSize.height), false, 0.0)
let context = UIGraphicsGetCurrentContext()
let previousFrame = tblView.frame
tblView.frame = CGRect(x: tblView.frame.origin.x, y: tblView.frame.origin.y, width: tblView.contentSize.width, height: tblView.contentSize.height)
// Draw view in that context
tblView.layer.render(in: context!)
tblView.frame = previousFrame
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
createPDFDataFromImage(image: image)
return image;
}
从图像创建PDF并共享
func createPDFDataFromImage(image: UIImage){
let pdfData = NSMutableData()
let imgView = UIImageView.init(image: image)
let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
UIGraphicsBeginPDFContextToData(pdfData, imageRect, nil)
UIGraphicsBeginPDFPage()
let context = UIGraphicsGetCurrentContext()
imgView.layer.render(in: context!)
UIGraphicsEndPDFContext()
//try saving in doc dir to confirm:
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let path = dir?.appendingPathComponent("file.pdf")
do {
try pdfData.write(to: path!, options: NSData.WritingOptions.atomic)
} catch {
print("error catched")
}
let activityViewController = UIActivityViewController(activityItems: [pdfData] , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}