使用pdfbox将便笺添加到pdf

时间:2020-02-24 08:47:42

标签: java pdfbox

我正在尝试使用pdfbox将便笺添加到现有的pdf中。


PDRectangle position = new PDRectangle();
System.out.println(textPosition.getXDirAdj());
position.setUpperRightX(textPosition.getX());
position.setUpperRightY(ph - textPosition.getY());

PDAnnotationTextMarkup polygonMarkup = new PDAnnotationTextMarkup(PDAnnotationMarkup.SUB_TYPE_POLYGON);
polygonMarkup.setContents("text");
polygonMarkup.setRectangle(position);
polygonMarkup.setLocked(true);
polygonMarkup.setReadOnly(true);

annotations.add(polygonMarkup);
page.setAnnotations(annotations);

此代码可以正常工作,但不会产生粘滞便笺,这是我主要关注的问题。

感谢任何潜在客户。

1 个答案:

答案 0 :(得分:1)

@mkl引用

According to the PDF specification, 'a text annotation represents a “sticky note” attached to a point in the PDF document.' Thus, neither the class PDAnnotationTextMarkup nor the subtype SUB_TYPE_POLYGON appears to match your requirements. Instead, you should use the PDAnnotationText class. As an aside, PDAnnotationTextMarkup is documented (JavaDocs) to be the abstract class that represents a text markup annotation. While it is not actually declared abstract, that characterization should make clear that it probably does not work without further ado.

所以我使用了下面的代码,它对我来说就像魔术一样

PDRectangle position = new PDRectangle();
position.setUpperRightX(textPosition.getX());
position.setUpperRightY(ph - textPosition.getY());

position.setLowerLeftX(textPosition.getX()-4);
position.setLowerLeftY(ph - textPosition.getY());
PDGamma colourBlue = new PDGamma();
colourBlue.setB(1);

PDAnnotationText text = new PDAnnotationText();
text.setContents(commentNameWithComments.get(word));
text.setRectangle(position);
text.setOpen(true);
text.setConstantOpacity(50f);

assert annotations != null;
annotations.add(text);
page1.setAnnotations(annotations);
replaceText(word);

这可能对将来的开发人员有用:-)