MBPDFGenerator
这是一个使用本地代码从 UIViewController 生成 PDF(iOS 10 及以上版本)的工具。它还可以帮助使用 UIView 和图片编辑 PDF(iOS 11 及以上版本)。它可以生成单页和多页 PDF(iOS 11 及以上版本)。
安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖管理器。您可以使用以下命令安装它
$ gem install cocoapods
要在 Xcode 项目中使用 CocoaPods 集成 MBPDFGenerator,在您的 Podfile
中指定它
target '<Your Target Name>' do
pod 'MBPDFGenerator'
end
如何使用
// Generate single page PDF
let url = try? MBSinglePagePDFGenerator.exportPDF(controller: self)
// you can use keepPDFPageSize as fasle to use actual UIViewController layout
let url = try? MBSinglePagePDFGenerator.exportPDF(controller: self, keepPDFPageSize: false)
// Generate mutli page PDF, it uses datasouece to generate PDF
let pdf = MBPDFGenerator(dataSource: self)
// set if you can actual UIViewController layout vs actula PDF page sie
pdf.keepPDFPageSize = false
// Generate PDF
let url = try? pdf.exportPDF()
// Data source for PDFGenerator
MBPDFGeneratorDataSource {
func numberOfPages() -> Int {
return //number of pages for PDF
}
func page(at index: Int) -> UIViewController {
return //UIViewConoller for give page index
}
编辑 PDF
// You can edit any existing PDF
let anyView = UIView()
// Create location to add on PDF
let viewBounds = CGRect(x: 10, y: 20, width: anyView.bounds.width, height: anyView.bounds.height)
// Create view annomation from view that need to add
let viewAnnotation = MBPDFAnnotationView(view: anyView, bounds: viewBounds, withProperties: nil)
// Create PDF object from existing PDF url
let pdf = MBPDFGenerator(url: <Existing PDF URL>)
// Somply add annonation at specified page index
if pdf?.addAnnotation(viewAnnotation, atPage: 0) {
// Generate New edited PDF
controller.url = try? pdf?.exportPDF()
}