我正在使用 iText 处理一些注释。
我尝试在现有 PDF 文件上绘制带有文本的图章注释。印章注释确实显示在 PDF 上,但是当我移动印章(或调整大小)时,文本(将所有格式)消失并且无法再恢复。
这是我的代码
PdfReader reader = new PdfReader(SRC_FILE);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(DEST_FILE));
PdfWriter writer = stamper.getWriter();
BaseColor textColor = BaseColor.ORANGE;
BaseColor fillColor = BaseColor.GRAY;
Rectangle rectangle = new Rectangle(150, 250, 450, 320);
PdfAnnotation annotation = PdfAnnotation.createSquareCircle(writer, rectangle, null, true);
annotation.setColor(textColor);
PdfDictionary dict = new PdfDictionary();
PdfTemplate template = PdfTemplate.createTemplate(writer, rectangle.getWidth(), rectangle.getHeight());
template.setBoundingBox(rectangle);
template.setColorFill(fillColor);
//template.setColorStroke(textColor);
template.setLineWidth(4);
template.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(), rectangle.getHeight());
template.closePathFillStroke();
template.setColorFill(textColor);
ColumnText columnText = new ColumnText(template);
columnText.setSimpleColumn(rectangle);
Paragraph p = new Paragraph("This is my test", new Font(Font.FontFamily.HELVETICA, 24, Font.BOLD));
p.setAlignment(Element.ALIGN_CENTER);
p.setLeading(50);
columnText.setAlignment(Element.ALIGN_CENTER);
columnText.addElement(p);
columnText.go();
writer.releaseTemplate(template);
dict.put(PdfName.N, template.getIndirectReference());
annotation.put(PdfName.AP, dict);
annotation.put(PdfName.F, new PdfNumber(4));
stamper.addAnnotation(annotation, 1);
stamper.close();
reader.close();
我也附上了此问题的屏幕截图供您查看。
我做了一些研究,如果我更改线路代码
PdfAnnotation annotation = PdfAnnotation.createSquareCircle(writer, rectangle, null, true);
至
PdfAnnotation annotation= stamper.getWriter().createAnnotation(rectangle, PdfName.FREETEXT);
当我移动图章时,文本仍然存在,但如果我调整矩形大小,文本仍然会消失。