我拥有日期以添加标题&内容& pageNo&坐标值。我想使用这些数据为现有PDF添加注释。 我尝试使用pdfbox(Java)为现有PDF添加注释。我可以添加插入到现有页面最后一部分的注释新页面,但我无法向现有页面添加注释,因为无法理解如何访问现有页面以及如何在页面中添加注释。
以下是我的代码。请解决它。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationTextMarkup;
public class Sample{
private String forannot[][];
Sample(String[][] forannot){
this.forannot = forannot;
}
public void tryaddannot() throws FileNotFoundException, IOException{
PDFParser pps = new PDFParser(new FileInputStream(Filepath);
pps.parse();
PDDocument docs = pps.getPDDocument();
try{
//insert new page
PDPage pages = new PDPage();
docs.addPage(pages);
List<PDAnnotationTextMarkup> annotations = pages.getAnnotations();
//generate instanse for annotation
PDAnnotationTextMarkup txtMark = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
//set the rectangle
PDRectangle position = new PDRectangle();
position.setLowerLeftX(170);
position.setLowerLeftY(125);
position.setUpperRightX(195);
position.setUpperRightY(140);
txtMark.setRectangle(position);
//set the quadpoint
float[] quads = new float[8];
//x1,y1
quads[0] = position.getLowerLeftX();
quads[1] = position.getUpperRightY()-2;
//x2,y2
quads[2] = position.getUpperRightX();
quads[3] = quads[1];
//x3,y3
quads[4] = quads[0];
quads[5] = position.getLowerLeftY()-2;
//x4,y4
quads[6] = quads[2];
quads[7] = quads[5];
txtMark.setQuadPoints(quads);
txtMark.setContents("Highlighted since it's important");
annotations.add(txtMark);
docs.save(Filepath);
} catch (COSVisitorException e) {
e.printStackTrace();
}
finally
{
docs.close();
}
}
}
答案 0 :(得分:2)
要向现有页面添加注释,请执行以下操作:
PDPage page = (PDPage) doc.getDocumentCatalog().getAllPages().get(0);
try
{
List<PDAnnotation> annotations = page.getAnnotations();
您的代码主要使用1.8,这是很难看到的注释。一些代码错误:
变化
PDFParser pps = new PDFParser(new FileInputStream(Filepath);
到
PDFParser pps = new PDFParser(new FileInputStream(Filepath));
并更改
List<PDAnnotationTextMarkup> annotations = pages.getAnnotations();
到
List<PDAnnotation> annotations = pages.getAnnotations();
此外,最好让您的文档像这样:
PDDocument doc = PDDocument.loadNonSeq(new File(...), null);
要查看注释的位置,请在“注释”,“注释列表”的最后一页上单击Adobe Reader。要使注释更加明显,请添加以下内容:
PDGamma colourBlue = new PDGamma();
colourBlue.setB(1);
txtMark.setColour(colourBlue);