使用 iText 更改 PDF 注释的颜色

Change color of PDF annotations with iText

我想更改 PDF 中所有突出显示注释的颜色。有函数com.itextpdf.text.pdf.PdfAnnotation.setColor(BaseColor color),如何调用这个函数?下面是遍历所有高亮注释的代码。

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();
    }

}
PdfAnnotation annotation = new PdfAnnotation(your_pdf_writer, new Rectangle(your_rectangle_information_here));
annotation.setColor(your_color_here);

您还需要一个 PdfWriter 来写入您的 pdf 以及有关您在 PDF 上绘制的矩形的信息。

希望对您有所帮助!

参考:creating anootations itext

不幸的是,iText PdfAnnotation class 仅用于从头开始创建新注释,它不是pre-existing个.

因此,您基本上必须使用像

这样的低级方法来操纵您的PdfDictionary curAnnot
curAnnot.put(PdfName.C, new PdfArray(new float[]{1, 0, 0}));

名称 C 的条目指定为

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:不要忘记最终使用

之类的方式存储更改
new PdfStamper(reader, new FileOutputStream("changed.pdf")).close();