简体   繁体   中英

Change color of PDF annotations with iText

I want to change the color of all my highlighting annotations of my PDF. There is the function com.itextpdf.text.pdf.PdfAnnotation.setColor(BaseColor color) , how can I call this function? Below is the code to iterate through all highlight annotations.

public static void main(String[] args) {

    try {

        // Reads and parses a PDF document
        PdfReader reader = new PdfReader("Test.pdf");

        // For each PDF page
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {

            // Get a page a PDF page
            PdfDictionary page = reader.getPageN(i);
            // Get all the annotations of page i
            PdfArray annotsArray = page.getAsArray(PdfName.ANNOTS);

            // If page does not have annotations
            if (page.getAsArray(PdfName.ANNOTS) == null) {
                continue;
            }

            // For each annotation
            for (int j = 0; j < annotsArray.size(); ++j) {

                // For current annotation
                PdfDictionary curAnnot = annotsArray.getAsDict(j);

                if (PdfName.HIGHLIGHT.equals(curAnnot.get(PdfName.SUBTYPE))) {

                    //how to access com.itextpdf.text.pdf.PdfAnnotation.setColor(BaseColor color)

                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

Unfortunately the iText PdfAnnotation class is only for creating new annotations from scratch, it is not a wrapper for pre-existing ones .

Thus, you essentially have to manipulate your PdfDictionary curAnnot with lowlevel methods like

curAnnot.put(PdfName.C, new PdfArray(new float[]{1, 0, 0}));

This entry for the name C is specified as

C array (Optional; PDF 1.1) An array of numbers in the range 0.0 to 1.0, representing a colour used for the following purposes:

The background of the annotation's icon when closed

The title bar of the annotation's pop-up window

The border of a link annotation

The number of array elements determines the colour space in which the colour shall be defined:

0 No colour; transparent

1 DeviceGray

3 DeviceRGB

4 DeviceCMYK

(Table 164 – Entries common to all annotation dictionaries – ISO 32000-1 )

PS: Don't forget to eventually store the changes using something like

new PdfStamper(reader, new FileOutputStream("changed.pdf")).close();
PdfAnnotation annotation = new PdfAnnotation(your_pdf_writer, new Rectangle(your_rectangle_information_here));
annotation.setColor(your_color_here);

You will also need a PdfWriter to write to your pdf and the information about the rectangle that you are drawing on the PDF.

Hope this helps!

Reference: creating anootations itext

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM