使用 iText 更改 PDF 批注的颜色



我想更改 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();
    }
}

不幸的是,iText PdfAnnotation 类仅用于从头开始创建新注释,它不是预先存在的注释的包装器

因此,您基本上必须使用低级方法PdfDictionary curAnnot(例如)

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

名称 C 的此项指定为

C 数组(可选;PDF 1.1) 0.0 到 1.0 范围内的数字数组, 表示用于以下目的的颜色:

关闭时批注图标的背景

批注弹出窗口的标题栏

链接批注的边框

数组元素的数量决定了 颜色应定义:

0 无颜色;透明

1 设备灰色

3 设备RGB

4 设备CMYK

(表 164 – 所有注释词典通用的条目 – ISO 32000-1)

PS:不要忘记最终使用类似的东西存储更改

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

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

希望这有帮助!

参考:创建匿名文本

最新更新