Creating and adding annotations

This is a code example of iText PDF, discover more.

31st May 2016
admin-marketing

Switch code for this example

AddLinkImages.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * Example written by Bruno Lowagie in answer to
 * http://stackoverflow.com/questions/29388313/itext-how-to-associate-actions-with-graphical-object
 */
package com.itextpdf.samples.sandbox.annotations;

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.wmf.WmfImageData;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.Property;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;

import org.junit.experimental.categories.Category;

import java.io.File;
import java.net.MalformedURLException;

@Category(SampleTest.class)
public class AddLinkImages extends GenericTest {
    public static final String sourceFolder = "./src/test/resources/img/";
    public static final String BUTTERFLY = sourceFolder + "butterfly.wmf";
    public static final String DEST = "./target/test/resources/sandbox/annotations/add_link_images.pdf";
    public static final String DOG = sourceFolder + "dog.bmp";
    public static final String FOX = sourceFolder + "fox.bmp";
    public static final String INFO = sourceFolder + "info.png";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new AddLinkImages().manipulatePdf(DEST);
    }

    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        Document doc = new Document(pdfDoc);
        Paragraph p = new Paragraph("Objects with links");
        p.add(createImage(INFO, "http://itextpdf.com/"));
        p.add(createImage(DOG, "http://pages.itextpdf.com/ebook-stackoverflow-questions.html"));
        p.add(createImage(FOX, "http://stackoverflow.com/q/29388313/1622493"));
        p.add(new Image(new PdfFormXObject(new WmfImageData(BUTTERFLY), pdfDoc)).
                setAction(PdfAction.createURI("http://stackoverflow.com/questions/tagged/itext*")));
        doc.add(p);
        doc.close();
    }

    public Image createImage(String src, String url) throws MalformedURLException {
        Image img = new Image(ImageDataFactory.create(src));
        img.setProperty(Property.ACTION, PdfAction.createURI(url));
        return img;
    }
}
AddPointerAnnotation.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * This example was written by Bruno Lowagie in answer to the following question:
 * http://stackoverflow.com/questions/26752663/adding-maps-at-itext-java
 */
package com.itextpdf.samples.sandbox.annotations;

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfLineAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;

import org.junit.experimental.categories.Category;

import java.io.File;

@Category(SampleTest.class)
public class AddPointerAnnotation extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/annotations/add_pointer_annotation.pdf";
    public static final String IMG = "./src/test/resources/img/map_cic.png";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new AddPointerAnnotation().manipulatePdf(DEST);
    }

    @Override
    protected void manipulatePdf(String dest) throws Exception {
        Image img = new Image(ImageDataFactory.create(IMG));
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc, new PageSize(img.getImageWidth(), img.getImageHeight()));
        img.setFixedPosition(0, 0);
        doc.add(img);
        Rectangle rect = new Rectangle(220, 350, 255, 245);
        PdfLineAnnotation lineAnnotation = new PdfLineAnnotation(rect, new float[]{225, 355, 470, 590});
        lineAnnotation.setTitle(new PdfString("You are here:"));
        lineAnnotation.setContents("Cambridge Innovation Center");
        lineAnnotation.setColor(Color.RED);
        lineAnnotation.setFlag(PdfAnnotation.PRINT);

        PdfDictionary borderStyle = new PdfDictionary();
        borderStyle.put(PdfName.S, PdfName.S);
        borderStyle.put(PdfName.W, new PdfNumber(5));
        lineAnnotation.setBorderStyle(borderStyle);

        PdfArray le = new PdfArray();
        le.add(new PdfName("OpenArrow"));
        le.add(new PdfName("None"));
        lineAnnotation.put(new PdfName("LE"), le);
        lineAnnotation.put(new PdfName("IT"), new PdfName("LineArrow"));

        pdfDoc.getFirstPage().addAnnotation(lineAnnotation);
        doc.close();
    }
}
AddRotatedAnnotation.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * This example was written by Bruno Lowagie in answer to the following question:
 * http://stackoverflow.com/questions/27083206/itextshape-clickable-polygon-or-path
 */
package com.itextpdf.samples.sandbox.annotations;

import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfLinkAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfStampAnnotation;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;

import org.junit.experimental.categories.Category;

import java.io.File;

@Category(SampleTest.class)
public class AddRotatedAnnotation extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/annotations/add_rotated_annotation.pdf";
    public static final String SRC = "./src/test/resources/pdfs/hello.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new AddRotatedAnnotation().manipulatePdf(DEST);
    }

    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));

        PdfAction action = PdfAction.createURI("http://pages.itextpdf.com/ebook-stackoverflow-questions.html");
        Rectangle linkLocation1 = new Rectangle(30, 770, 90, 30);
        PdfAnnotation link1 = new PdfLinkAnnotation(linkLocation1)
                .setHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT)
                .setAction(action)
                .setColor(Color.RED.getColorValue());
        pdfDoc.getFirstPage().addAnnotation(link1);

        Rectangle linkLocation2 = new Rectangle(30, 670, 30, 90);
        PdfAnnotation link2 = new PdfLinkAnnotation(linkLocation2)
                .setHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT)
                .setAction(action)
                .setColor(Color.GREEN.getColorValue());
        pdfDoc.getFirstPage().addAnnotation(link2);

        Rectangle linkLocation3 = new Rectangle(150, 770, 90, 30);
        PdfAnnotation stamp1 = new PdfStampAnnotation(linkLocation3)
                .setStampName(new PdfName("Confidential"))
                .setContents("Landscape");
        pdfDoc.getFirstPage().addAnnotation(stamp1);

        Rectangle linkLocation4 = new Rectangle(150, 670, 90, 90);
        PdfAnnotation stamp2 = new PdfStampAnnotation(linkLocation4)
                .setStampName(new PdfName("Confidential"))
                .setContents("Portrait")
                .put(PdfName.Rotate, new PdfNumber(90));
        pdfDoc.getFirstPage().addAnnotation(stamp2);

        Rectangle linkLocation5 = new Rectangle(250, 670, 90, 90);
        PdfAnnotation stamp3 = new PdfStampAnnotation(linkLocation5)
                .setStampName(new PdfName("Confidential"))
                .setContents("Portrait")
                .put(PdfName.Rotate, new PdfNumber(45));
        pdfDoc.getFirstPage().addAnnotation(stamp3);

        pdfDoc.close();
    }
}
AddStamp.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * Example written by Bruno Lowagie in answer to
 * http://stackoverflow.com/questions/29229629/how-to-add-a-printable-or-non-printable-bitmap-stamp-to-a-pdf
 */
package com.itextpdf.samples.sandbox.annotations;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfStampAnnotation;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;

import org.junit.experimental.categories.Category;

import java.io.File;

@Category(SampleTest.class)
public class AddStamp extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/annotations/add_stamp.pdf";
    public static final String IMG = "./src/test/resources/img/itext.png";
    public static final String SRC = "./src/test/resources/pdfs/hello.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new AddStamp().manipulatePdf(DEST);
    }

    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));

        ImageData img = ImageDataFactory.create(IMG);
        float w = img.getWidth();
        float h = img.getHeight();
        Rectangle location = new Rectangle(36, 770 - h, w, h);
        PdfStampAnnotation stamp = new PdfStampAnnotation(location)
                .setStampName(new PdfName("ITEXT"));
        PdfFormXObject xObj = new PdfFormXObject(new Rectangle(w, h));
        PdfCanvas canvas = new PdfCanvas(xObj, pdfDoc);
        canvas.addImage(img, 0, 0, false);
        stamp.setNormalAppearance(xObj.getPdfObject());
        stamp.setFlags(PdfAnnotation.PRINT);

        pdfDoc.getFirstPage().addAnnotation(stamp);
        pdfDoc.close();
    }
}
FileAttachmentAnnot.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * Example written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/31006683/itext-clickable-image-should-open-ms-word-attachment
 */
package com.itextpdf.samples.sandbox.annotations;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfFileAttachmentAnnotation;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.filespec.PdfFileSpec;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;

import org.junit.experimental.categories.Category;

import java.io.File;

@Category(SampleTest.class)
public class FileAttachmentAnnot extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/annotations/file_attachment_annot.pdf";
    public static final String IMG = "./src/test/resources/img/info.png";
    public static final String PATH = "./src/test/resources/txt/test.docx";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FileAttachmentAnnot().manipulatePdf(DEST);
    }

    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        Rectangle rect = new Rectangle(36, 700, 100, 100);
        PdfFileSpec fs = PdfFileSpec.createEmbeddedFileSpec(pdfDoc, PATH, null, "test.docx", null, null, false);
        PdfAnnotation attachment = new PdfFileAttachmentAnnotation(rect, fs)
                .setContents("Click me");

        PdfFormXObject xObject = new PdfFormXObject(rect);
        ImageData imageData = ImageDataFactory.create(IMG);
        PdfCanvas canvas = new PdfCanvas(xObject, pdfDoc);
        canvas.addImage(imageData, rect, true);
        attachment.setNormalAppearance(xObject.getPdfObject());

        pdfDoc.addNewPage().addAnnotation(attachment);
        pdfDoc.close();
    }
}
ImagesLinksTable.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * This example was written by Bruno Lowagie in answer to the following question:
 * http://stackoverflow.com/questions/32839816/export-hyperlink-to-pdf-file-from-itextsharp-library-in-c-sharp
 */
package com.itextpdf.samples.sandbox.annotations;

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfLinkAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.Property;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.layout.renderer.ImageRenderer;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;

import org.junit.experimental.categories.Category;

import java.io.File;

@Category(SampleTest.class)
public class ImagesLinksTable extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/annotations/images_links_table.pdf";
    public static final String IMG = "./src/test/resources/img/info.png";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new ImagesLinksTable().manipulatePdf(DEST);
    }

    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        Document doc = new Document(pdfDoc);

        Image img = new Image(ImageDataFactory.create(IMG));
        Paragraph anchor = new Paragraph().add(img);
        anchor.setProperty(Property.ACTION, PdfAction.createURI("http://lowagie.com/"));

        Table table = new Table(3);
        table.addCell(anchor);
        table.addCell("A");
        table.addCell("B");
        table.addCell("C");

        Image img2 = new Image(ImageDataFactory.create(IMG));
        img2.setNextRenderer(new LinkImageRenderer(img2));
        table.addCell(img2);

        doc.add(table);
        doc.close();
    }


    protected class LinkImageRenderer extends ImageRenderer {
        public LinkImageRenderer(Image image) {
            super(image);
        }

        @Override
        public void draw(DrawContext drawContext) {
            super.draw(drawContext);
            PdfAnnotation a = new PdfLinkAnnotation(getOccupiedAreaBBox())
                    .setAction(PdfAction.createURI("http://lowagie.com/bio"));
            drawContext.getDocument().getLastPage().addAnnotation(a);
        }
    }
}
RelativeLink.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * Example written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/27063677/use-of-relative-path-for-anchor-method-using-itext-for-pdf-generation
 */
package com.itextpdf.samples.sandbox.annotations;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Link;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;

import org.junit.experimental.categories.Category;

import java.io.File;

@Category(SampleTest.class)
public class RelativeLink extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/annotations/relative_link.pdf";
    public static final String XML = "./src/test/resources/xml/data.xml";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new RelativeLink().manipulatePdf(DEST);
    }

    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        Document doc = new Document(pdfDoc);

        Paragraph chunk = new Paragraph(new Link("Click me", PdfAction.createURI("../../../../." + XML)));
        doc.add(chunk);

        doc.close();
    }
}
RemoteGoToPage.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * Example written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/19999048/how-to-create-hyperlink-from-a-pdf-to-another-pdf-to-a-specified-page-using-itex
 * 

* Creating a link from one PDF to another */ package com.itextpdf.samples.sandbox.annotations; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.action.PdfAction; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.AreaBreak; import com.itextpdf.layout.element.Link; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.samples.GenericTest; import com.itextpdf.test.annotations.type.SampleTest; import org.junit.experimental.categories.Category; import java.io.File; @Category(SampleTest.class) public class RemoteGoToPage extends GenericTest { // !IMPORTANT We change the order of SRC and DEST because we want to check via CompareTool // comprehensive file rather then simple // So DEST file DOES NOT mean destination but DEST-file-which-we-will-check-from-GenericTest public static final String SRC = "./target/test/resources/sandbox/annotations/subdir/xyz2.pdf"; public static final String DEST = "./target/test/resources/sandbox/annotations/remote_go_to_page.pdf"; public static void main(String[] args) throws Exception { new RemoteGoToPage().manipulatePdf(DEST); } @Override protected void manipulatePdf(String dest) throws Exception { File file = new File(SRC); file.getParentFile().mkdirs(); RemoteGoToPage app = new RemoteGoToPage(); app.createPdf(SRC); app.createPdf2(DEST); } private void createPdf(String src) throws Exception { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(src)); Document doc = new Document(pdfDoc); doc.add(new Paragraph("page 1")); doc.add(new AreaBreak()); doc.add(new Paragraph("page 2")); doc.add(new AreaBreak()); doc.add(new Paragraph("page 3")); doc.add(new AreaBreak()); doc.add(new Paragraph("page 4")); doc.add(new AreaBreak()); doc.add(new Paragraph("page 5")); doc.add(new AreaBreak()); doc.add(new Paragraph("page 6")); doc.add(new AreaBreak()); doc.add(new Paragraph("page 7")); doc.close(); } private void createPdf2(String dest) throws Exception { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest)); Document doc = new Document(pdfDoc); Paragraph chunk = new Paragraph(new Link("Link", PdfAction.createGoToR("subdir/xyz2.pdf", 6))); doc.add(chunk); doc.close(); } }

RemoteGoto.java
/*

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV

*/

/**
 * Example written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/19999048/how-to-create-hyperlink-from-a-pdf-to-another-pdf-to-a-specified-page-using-itex
 * 

* Creating a link from one PDF to another */ package com.itextpdf.samples.sandbox.annotations; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.action.PdfAction; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Link; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.property.Property; import com.itextpdf.samples.GenericTest; import com.itextpdf.test.annotations.type.SampleTest; import org.junit.experimental.categories.Category; import java.io.File; @Category(SampleTest.class) public class RemoteGoto extends GenericTest { // !IMPORTANT We change the order of SRC and DEST because we want to check via CompareTool // comprehensive file rather then simple // So DEST file DOES NOT mean destination but DEST-file-which-we-will-check-from-GenericTest public static final String SRC = "./target/test/resources/sandbox/annotations/subdir/xyz.pdf"; public static final String DEST = "./target/test/resources/sandbox/annotations/remote_goto.pdf"; public static void main(String[] args) throws Exception { new RemoteGoto().manipulatePdf(DEST); } @Override protected void manipulatePdf(String dest) throws Exception { File file = new File(SRC); file.getParentFile().mkdirs(); RemoteGoto app = new RemoteGoto(); app.createPdf(SRC); app.createPdf2(DEST); } private void createPdf(String src) throws Exception { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(src)); Document doc = new Document(pdfDoc); Paragraph anchor = new Paragraph("This is a destination"); anchor.setProperty(Property.DESTINATION, "dest"); doc.add(anchor); doc.close(); } private void createPdf2(String dest) throws Exception { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest)); Document doc = new Document(pdfDoc); Paragraph chunk = new Paragraph(new Link("Link", PdfAction.createGoToR("subdir/xyz.pdf", "dest"))); doc.add(chunk); doc.close(); } }

Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now