Is there a way in iOS to merge PDF files, that is, append the pages of one at the end of another and save it to disk?
Swift 5:
Merge pdfs like this to keep links, etc...
func mergePdf(data: Data, otherPdfDocumentData: Data) -> PDFDocument {
// get the pdfData
let pdfDocument = PDFDocument(data: data)!
let otherPdfDocument = PDFDocument(data: otherPdfDocumentData)!
// create new PDFDocument
let newPdfDocument = PDFDocument()
// insert all pages of first document
for p in 0..<pdfDocument.pageCount {
let page = pdfDocument.page(at: p)!
newPdfDocument.insert(page, at: newPdfDocument.pageCount)
}
// insert all pages of other document
for q in 0..<otherPdfDocument.pageCount {
let page = otherPdfDocument.page(at: q)!
newPdfDocument.insert(page, at: newPdfDocument.pageCount)
}
return newPdfDocument
}
Show your mergedPdf in a PDFView:
// show merged pdf in pdfView
PDFView.document = newPdfDocument
Save your pdf.
First convert the newPdfDocument
like this:
let documentDataForSaving = newPdfDocument.dataRepresentation()
Put the documentDataForSaving
in this following function:
Use the save function:
let urlWhereTheFileIsSaved = writeDataToTemporaryDirectory(withFilename: "My File Name", inFolder: nil, data: documentDataForSaving)
Probably you want to avoid /
in file name and don't make it longer than 256 characters
Save-Function:
// Export PDF to directory, e.g. here for sharing
func writeDataToTemporaryDirectory(withFilename: String, inFolder: String?, data: Data) -> URL? {
do {
// get a directory
var temporaryDirectory = FileManager.default.temporaryDirectory // for e.g. sharing
// FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! // to make it public in user's directory (update plist for user access)
// FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last! // to hide it from any user interactions)
// do you want to create subfolder?
if let inFolder = inFolder {
temporaryDirectory = temporaryDirectory.appendingPathComponent(inFolder)
if !FileManager.default.fileExists(atPath: temporaryDirectory.absoluteString) {
do {
try FileManager.default.createDirectory(at: temporaryDirectory, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription);
}
}
}
// name the file
let temporaryFileURL = temporaryDirectory.appendingPathComponent(withFilename)
print("writeDataToTemporaryDirectory at url:\t\(temporaryFileURL)")
try data.write(to: temporaryFileURL)
return temporaryFileURL
} catch {
print(error)
}
return nil
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With