Answers Updated:
Since Apple introduced PDFKit to iOS 11.0, you can use the code below to convert uiimage to pdf, I only tried the osx below, but it should work the same way on iOS.
// Create an empty PDF document
let pdfDocument = PDFDocument()
// Load or create your UIImage
let image = UIImage(....)
// Create a PDF page instance from your image
let pdfPage = PDFPage(image: image!)
// Insert the PDF page into your document
pdfDocument.insert(pdfPage!, at: 0)
// Get the raw data of your PDF document
let data = pdfDocument.dataRepresentation()
// The url to save the data to
let url = URL(fileURLWithPath: "/Path/To/Your/PDF")
// Save the data to the url
try! data!.write(to: url)
================================================
Actually there're a lot similar questions and good enough answers. Let me try to answer this again.
Basically generating PDF is similar to the drawing in iOS.
- Create a PDF context and push it onto the graphics stack.
- Create a page .
- Use UIKit or Core Graphics routines to draw the content of the page.
- Add links if needed .
- Repeat steps 2, 3, and 4 as needed.
- End the PDF context to pop the context from the graphics stack and, depending on how the context was created, either write the resulting data to the specified PDF file or store it into the specified NSMutableData object.
So the most simple way would be something like this:
func createPDF(image: UIImage) -> NSData? {
let pdfData = NSMutableData()
let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!
var mediaBox = CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height)
let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
pdfContext.beginPage(mediaBox: &mediaBox)
pdfContext.draw(image.cgImage!, in: mediaBox)
pdfContext.endPage()
return pdfData
}
That created all the NSData for the PDF file, then we need to save the data to file:
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let docURL = documentDirectory.appendingPathComponent("myFileName.pdf")
try createPDF(image: someUIImageFile)?.write(to: docURL, atomically: true)
Read more here: Generating PDF Content
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…