Set XMP Metadata

This guide will show how to set an XMP pdf metadata.

Before you begin

First of all you should get your API key from your UniCloud account.

If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.

Project setup

Clone the project repository

In your terminal, clone examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unipdf-examples.git

Navigate to the metadata folder in the unipdf-examples directory.

cd unipdf-examples/metadata

Configure environment variables

Replace the UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.

Linux/Mac

export UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

Windows

set UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

How it works

The import section in lines 3-13 imports some unipdf packages and other necessary libraries. The init function in lines 21-28 loads your metered license key and authenticates your request.

In lines 30-144 the main function is defined. In this function in lines 31-37 the input and output files are read from the command line arguments. The code line 40-44 measures the time taken to process the document. In lines 47-57 a new pdfReader is instantiated and converted to pdfWriter object.

In lines 60-72 an XMP document is extracted from the document. If it doesn’t exist in the document a new one is created in lines 72-74. In lines 77-80 the PdfInfo in the original file is read using reader.GetPdfInfo(). The code in lines 83-93 sets the creationDate info of the document. The modifiedAt info is set in lines 95-101.

In lines 104-112 the PdfInfoOptions is created by setting pdfInfo, pdfVersion, copyright information fields. The pdfInfo is set using xmpDoc.SetPdfInfo(xmpPdfMetadata) in lines 114-117. Then the XMP document is marshaled into byte stream using xmpDoc.MarshalIndent("", "\t"). In line 129-132 a core.PdfObjectStream object is created from the byte stream using core.MakeStream(metadataBytes, nil).

In line 135-137 the metadata is set to the document using pdfWriter.SetCatalogMetadata. Finally the document is written to file using pdfWriter.WriteToFile(outputPath) in lines 140-143.

Run the code

go run pdf_set_xmp_pdf_metadata.go <input.pdf> <output.pdf>

Got any Questions?

We're here to help you.