PDFlib Cookbook

cookbook

text_output/watermark

Download Java Code     Switch to PHP Code     Show Output PDF

package com.pdflib.cookbook.pdflib.text_output;

/*
 * $Id: watermark.java,v 1.1 2016/01/12 14:06:55 stm Exp $
 *
 * Create an editable watermark
 * 
 * Required software: PDFlib 9.0.6
 * Required data: image file
 */

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

public class watermark {
    public static void main(String argv[]) {
        int image;
        pdflib p = null;
        String imagefile = "nesrin.jpg";
        /*
         * This is where font/image/PDF input files live. Adjust as necessary.
         */
        String searchpath = "../input";

        String title = "Create Editable Watermark";
        
        int exitcode = 0;
        
        try {

            p = new pdflib();

            /*
             * Set errorpolicy to return, this means we must check return values
             * of load_font() etc. Set the search path for the image file.
             */
            p.set_option(
                    "errorpolicy=return SearchPath={{" + searchpath + "}}");

            if (p.begin_document("watermark.pdf", "") == -1)
                throw new Exception("Error: " + p.get_errmsg());

            p.set_info("Creator", "PDFlib Cookbook");
            p.set_info("Title", title + " $Revision: 1.1 $");

            /*
             * Create watermark. The watermark by default applies to all
             * pages in the document
             */
            p.begin_template_ext(0, 0,
                    "watermark={location=ontop opacity=60%}");

            p.fit_textline("Preliminary", 0, 0,
                    "fontsize=12 fontname=Helvetica-Bold encoding=unicode "
                            + "fillcolor=red boxsize={595 842} stamp=ll2ur");

            p.end_template_ext(0, 0);

            /*
             * Create page content.
             */
            image = p.load_image("auto", imagefile, "");

            if (image == -1)
                throw new Exception("Error: " + p.get_errmsg());

            p.begin_page_ext(0, 0, "width=a4.width height=a4.height");
            p.fit_textline("The watermark can be edited in Acrobat", 20, 600,
                    "fontname=Helvetica encoding=unicode fontsize=14");

            p.fit_image(image, 0.0, 0.0, "boxsize={595 600} fitmethod=meet");
            p.close_image(image);
            p.end_page_ext("");

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