Edit PDF metadata on iOS

Metadata may be stored in a PDF document in two ways: in a document information dictionary associated with the document, or in a metadata stream containing XMP data. To give you full access to all the PDF metadata, Nutrient comes with PDFMetadata and XMPMetadata, which allow you to retrieve or modify a document’s metadata.

PDF metadata

Use PDFMetadata to work with the dictionary-based metadata in a PDF.

All values specified in the PDF Info Dictionary are represented by the following types:

SwiftObjective-C
StringNSString
Int, Float, Double, BoolNSNumber
DateNSDate
Array<Any>NSArray<id>
Dictionary<String, Any>NSDictionary<NSString*, id>

The Any and id types above can include any of the types mentioned.

These types can be combined in any way you see fit and will be converted into the proper PDF types.

By default, the dictionary metadata may contain the following info keys:

  • Author
  • CreationDate
  • Creator
  • Keywords
  • ModDate
  • Producer
  • Title

You can, of course, add any supported key-value dictionary to the metadata.

Retrieving

To get an entry of the metadata dictionary (e.g. the Author), you can use the following code snippet:

let document = ...
let pdfMetadata = PDFMetadata(document: document)
let author = pdfMetadata?.object(forInfoDictionaryKey: .author)

Saving

You can customize the document metadata and then save the document, which also saves the modified metadata into the PDF:

let pdfMetadata = PDFMetadata(document: document)
pdfMetadata?.setObject("MyValue", forInfoDictionaryKey: PDFMetadata.Key("MyCustomKey"))
try? document.save()

XMP metadata

Use XMPMetadata to work with the metadata stream containing XMP data.

Each key in the XMP metadata stream has to have a namespace set. You can define your own namespace or use one of the already existing ones. Nutrient exposes two constants for common namespaces:

When setting a value, you also have to pass along a suggested namespace prefix, as this can’t be generated automatically.

Retrieving

Use the following code snippet to get an object from the XMP metadata:

let xmpMetadata = XMPMetadata(document: document)
let documentFormat = xmpMetadata?.string(forXMPKey: "format", namespace: PSPDFXMPDCNamespace)

Saving

You can also set new metadata and save it to the document:

let xmpMetadata = XMPMetadata(document: document)
let metadataKey = "MyKey"
let metadataValue = "MyValue"
xmpMetadata?.setString(metadataValue, forXMPKey: metadataKey, namespace: PSPDFXMPPDFNamespace, suggestedNamespacePrefix: PSPDFXMPPDFNamespacePrefix)