我想从UIScrollView的内容创建一个PDF文件。
func createPdfFromView(aView: UIView, saveToDocumentsWithFileName fileName: String) {
let pdfData = NSMutableData()
let height = 1754.0
let width = 1240.0
UIGraphicsBeginPDFContextToData(pdfData, CGRect(x:-30, y:15,width:width,height:height) , nil)
UIGraphicsBeginPDFPage()
guard let pdfContext = UIGraphicsGetCurrentContext() else { return }
aView.layer.render(in: pdfContext)
UIGraphicsEndPDFContext()
if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let documentsFileName = documentDirectories + "/" + fileName
debugPrint(documentsFileName)
pdfData.write(toFile: documentsFileName, atomically: true)
}
}
我希望代码生成一个面向滚动视图中内容大小的PDF。
该代码目前仅生成静态PDF。如果滚动视图中的内容大于PDF页面,则内容将被截断。
答案 0 :(得分:2)
func createPdfFromView()
{
// Set frame as per content of view
self.spreadsheetView.frame = CGRect(x: 0, y: 0, width: self.spreadsheetView.contentSize.width, height: self.spreadsheetView.contentSize.height)
let pdfPageBounds: CGRect = self.spreadsheetView.frame
let pdfData: NSMutableData = NSMutableData()
// Rendering spreadsheetView
UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
self.spreadsheetView.layer.render(in: UIGraphicsGetCurrentContext()!)
UIGraphicsEndPDFContext()
let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let documentsFileName = documentDirectories! + "/" + "pdfName.pdf"
pdfData.write(toFile: documentsFileName, atomically: true)
print(documentsFileName)
// Reset spreadsheetView
self.spreadsheetView.frame = CGRect(x: 0, y: 64, width: self.view.frame.width, height: self.view.frame.height)
self.spreadsheetView.layoutSubviews()
self.spreadsheetView.layoutIfNeeded()
self.spreadsheetView.reloadData()}
希望它能帮助您从电子表格中创建PDF。
参考。 Github代码链接:SpreadsheetView
答案 1 :(得分:0)
我可以使用此Cocoapods框架实现这一目标。就我而言,我想从Spreadsheet制作一个PDF,以便该框架可以帮助我添加具有不同列大小的表以及需要从数据中获取的更多功能。