[英]Change color of PDF annotations with iText
I want to change the color of all my highlighting annotations of my PDF. 我想更改我所有PDF突出显示注释的颜色。 There is the function
com.itextpdf.text.pdf.PdfAnnotation.setColor(BaseColor color)
, how can I call this function? 有功能
com.itextpdf.text.pdf.PdfAnnotation.setColor(BaseColor color)
,该如何调用该功能? 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 . 不幸的是,iText
PdfAnnotation
类仅用于从头开始创建新的注释 ,而不是预先存在的包装器 。
Thus, you essentially have to manipulate your PdfDictionary curAnnot
with lowlevel methods like 因此,您基本上必须使用类似下面这样的低级方法来操作
PdfDictionary curAnnot
curAnnot.put(PdfName.C, new PdfArray(new float[]{1, 0, 0}));
This entry for the name C is specified as 名称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:
C数组(可选; PDF 1.1)在0.0到1.0范围内的数字数组,表示用于以下目的的颜色:
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;
0无颜色 transparent
透明
1 DeviceGray
1个设备灰色
3 DeviceRGB
3个设备RGB
4 DeviceCMYK
4个设备CMYK
(Table 164 – Entries common to all annotation dictionaries – ISO 32000-1 )
(表164 –所有注释词典共有的条目– ISO 32000-1 )
PS: Don't forget to eventually store the changes using something like 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);
You will also need a PdfWriter to write to your pdf and the information about the rectangle that you are drawing on the PDF. 您还需要一个PdfWriter来写到pdf以及有关您在PDF上绘制的矩形的信息。
Hope this helps! 希望这可以帮助!
Reference: creating anootations itext 参考: 创建修饰词itext
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.