PDFlib Cookbook

cookbook

interchange/embed_xmp

Embed custom XMP metadata in a document.

Download Java Code  Switch to PHP Code  Show Output  Show Input (simple.xmp) 

/*
 * Embed XMP:
 * Embed custom XMP metadata in a document
 * 
 * Use the "metadata" option of begin_document() to read XMP metadata from an
 * XMP file and embed it in the output document.
 * 
 * Required software: PDFlib/PDFlib+PDI/PPS 10
 * Required data: XMP file
 */
package com.pdflib.cookbook.pdflib.interchange;

import com.pdflib.pdflib;
import com.pdflib.PDFlibException;

public class embed_xmp
{
    public static void main (String argv[])
    {
        /* This is where the data files are. Adjust as necessary. */
        String searchpath = "../input";
        String outfile = "embed_xmp.pdf";
        String title = "Embed XMP";

        pdflib p = null;
        String xmpfile = "simple.xmp";
        int exitcode = 0;

        try {
            p = new pdflib();

            p.set_option("searchpath={" + searchpath + "}");

            /* This means we must check return values of load_font() etc. */
            p.set_option("errorpolicy=return");
            
            /* Start the document with an XMP file supplied, containing a few
             * commonly used XMP properties. The XMP metadata will be read from the
             * file and embedded in the document. PDFlib will merge several
             * internally generated entries into the user-supplied XMP, e.g.
             * xmp:CreateDate. 
             */
            if (p.begin_document(outfile, 
                "metadata={filename={" + xmpfile + "}}") == -1)
                throw new Exception("Error: " + p.get_errmsg());
            
            p.set_info("Creator", "PDFlib Cookbook");
            p.set_info("Title", title);
            
            /* Start page */
            p.begin_page_ext(0, 0, "width=a4.width height=a4.height");
            
            p.fit_textline("XMP metadata is read from an XMP file and embedded " +
                "in the document.", 20, 600, 
                "fontname=NotoSerif-Regular fontsize=12");
            
            p.end_page_ext("");

            p.end_document("");

        } catch (PDFlibException e) {
            System.err.println("PDFlib exception occurred:");
            System.err.println("[" + e.get_errnum() + "] " + e.get_apiname()
                + ": " + e.get_errmsg());
            exitcode = 1;
        } catch (Exception e) {
            System.err.println(e);
            exitcode = 1;
        } finally {
            if (p != null) {
                p.delete();
            }
            System.exit(exitcode);
        }
    }
}