Set Custom XMP Metadata
In this guide setting a custom xmp metadata will be shown.
Before you begin
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-16
imports unipdf packages and other necessary libraries.
The init
function defined in lines 18-25
loads your metered License API key from the system environment.
In lines 27-118
the main
function is defined. In lines 28-34
the input path and the output path are read from the command line arguments. The code in lines 37-41
measures the time taken to finish the process. In lines 44-48
a new model.PdfReader
is instantiated from the input file. In lines 51-54
a new writer is instantiated from the reader using reader.ToWriter()
.
The code in lines 57-72
extracts the XMP metadata from the PDF Catalog Metadata if exists, other wise it creates a new xmp metadata. From the xmputil.Document
a new xmp.Document
is created using xmpDoc.GetGoXmpDocument()
. Then a new xmprights.XmpRights
is created from the xmp document to get a direct access to go-xmp/xmp.Document
which allows us to extract custom or undefined model from the XMP Metadata.
In lines 85-88
the various fields of the xmp document are set. The model is sync with xmp document in lines 91-93
.
The xmputil.Document
is marshalled into XML byte stream with predefined prefix and indent values in lines 97-100
using xmpDoc.MarshalIndent("", "\t")
.
In lines 103-106
a new core.PdfObjectStream
is created using core.MakeStream(data, nil)
. Here a nil
value is provided for the stream encoder parameter. Then the metadata stream is set to pdfWriter
using pdfWriter.SetCatalogMetadata(metadataStream)
in line 109
.
Finally the document is written to file using pdfWriter.WriteToFile(outputPath)
in lines 114-117
.
Run the code
go run pdf_set_custom_xmp_metadata.go <inputPath> <outPath>