I am trying to modify a pdf. This program Creates a simple PDF when ViewDoesLoad. That works. Then, when the button is pressed, I reload the PDF, and try and write additional text to it and then save it. However the the modified PDF is Identical to the original? What did I do wrong?
BTW I added the whole program so that it is easy to insert in a simple stupid sample app. I need to write more details here for StackOverflow to allow me to post. So you can skip this paragraph.
import UIKit
import PDFKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let pdf = createFlyer()
if let docDir = documentsDirectoryPath() {
print (docDir + "/newPDF.pdf")
saveDataToFile(data: pdf, filePath: docDir + "/newPDF.pdf")
}
}
@IBAction func button(_ sender: Any) {
print("pressed")
if let docDir = documentsDirectoryPath() {
print (docDir + "/newPDF.pdf")
let inputURL = docDir + "/newPDF.pdf"
let outputURL = docDir + "/modPDF.pdf"
if let input = URL(string: "file://\(inputURL)") {
// Use the URL object
if let output = URL(string: "file://\(outputURL)") {
// Use the URL object
modifyFlier(srcURL: input, dstURL: output, text: "new string")
}
}
}
}
//https://stackoverflow.com/questions/64376645/swift-ios-overlay-text-onto-pdf-with-pdfkit-and-ui
func modifyFlier(srcURL: URL, dstURL: URL, text: String) {
// Confirm there is a document there
if let doc: PDFDocument = PDFDocument(url: srcURL) {
// Create a document, get the first page, and set the size of the page
let page: PDFPage = doc.page(at: 0)!
var mediaBox: CGRect = page.bounds(for: .mediaBox)
// This is where the magic happens. Create the drawing context on the PDF
let context = CGContext(dstURL as CFURL, mediaBox: &mediaBox, nil)
UIGraphicsPushContext(context!)
context!.beginPDFPage(nil)
// Draws the PDF into the context
page.draw(with: .mediaBox, to: context!)
let flipVertical: CGAffineTransform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: mediaBox.size.height)
context!.concatenate(flipVertical)
let attributes = [
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
]
let text = "I'm a PDF!"
text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
context!.endPDFPage()
context?.closePDF()
UIGraphicsPopContext()
if doc.write(to: dstURL) {
print("Modified PDF saved successfully")
} else {
print("Failed to save the modified PDF")
}
print("The pdf should be different")
}
}
func createFlyer() -> Data {
// 1
let pdfMetaData = [
kCGPDFContextCreator: "Flyer Builder",
kCGPDFContextAuthor: "raywenderlich.com"
]
let format = UIGraphicsPDFRendererFormat()
format.documentInfo = pdfMetaData as [String: Any]
// 2
let pageWidth = 8.5 * 72.0
let pageHeight = 11 * 72.0
let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
// 3
let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
// 4
let data = renderer.pdfData { (context) in
// 5
context.beginPage()
// 6
let attributes = [
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
]
let text = "I'm a PDF!"
text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
}
return data
}
func saveDataToFile(data: Data, filePath: String) {
do {
// Create a URL for the file path
let fileURL = URL(fileURLWithPath: filePath)
// Write the data to the file
try data.write(to: fileURL)
print("Data saved successfully at: \(fileURL.path)")
} catch {
print("Failed to save data: \(error.localizedDescription)")
}
}
func documentsDirectoryPath() -> String? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
return paths.first
}
}