I am successfully downloading a PDF from api end point. Once pdf is downloaded, the title of pdf is : PDF document.pdf . How to change the title of PDF?
I tried to update metadata
of PDF using PDFDocumentAttribute
(see below), but it is not working.
var metadata = pdfDocument.documentAttributes!
metadata[PDFDocumentAttribute.subjectAttribute] = "subject attribute"
metadata[PDFDocumentAttribute. titleAttribute] = "title attribute"
pdfDocument.documentAttributes = metadata
Note: I am not using FileManager
How I am fetching PDF:-
let task = session.dataTask(with: urlRequest) { (data, _, error) in
DispatchQueue.main.async {
guard let unwrappedData = data, error == nil else {
completion(.failure(error ?? Constants.dummyError))
return
}
guard let pdfDocument = PDFDocument(data: unwrappedData) else {
completion(.failure(error ?? Constants.dummyError))
return
}
completion(.success(pdfDocument))
}
}
try this:
pdfDocument.documentAttributes?["Title"] = "my title attribute"
or
pdfDocument.documentAttributes?[PDFDocumentAttribute.titleAttribute] = "my title attribute"
Similarly for PDFDocumentAttribute.subjectAttribute
.
The above will set the Title
of your document, and when you save it, the file
name will be whatever file name
you give it.
EDIT-1: saving the pdfDocument
to a file with a chosen file name
.
DispatchQueue.main.async {
guard let unwrappedData = data, error == nil else {
completion(.failure(error ?? Constants.dummyError))
return
}
guard let pdfDocument = PDFDocument(data: unwrappedData) else {
completion(.failure(error ?? Constants.dummyError))
return
}
// set the Title
pdfDocument.documentAttributes?[PDFDocumentAttribute.titleAttribute] = "my title attribute"
do {
// save the document to the given file name ("mydoc.pdf")
let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("mydoc.pdf") // <-- here file name
pdfDocument.write(to: docURL)
print("\n docUrl: \(docURL.absoluteString)\n")
}
catch {
print("Error \(error)")
}
completion(.success(pdfDocument))
}