我一直在尝试编辑 PDF 文档以预先填写表单条目。我已经让它工作了(有点)。我要添加的文本很好。但是,已经存在的其他文本似乎已被替换为“&%£!£!符号。我发现这与下面代码中的“contentStream”部分有关。它似乎是“ setFont" 行。如果我删除它,页面仍然正常...除了“Hello Richard”文本不再显示!
请帮忙!
package pdfboxtest;
import java.awt.Color;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
public class PDFFormFiller {
private static final String R40_NEW_FORM_PATH = "c:\\temp\\hmrc-r40.pdf";
private static final String R40_COMPLETED_FORM_PATH = "c:\\temp\\hmrc-r40-complete.pdf";
public static void main(String[] args) throws Exception {
PDDocument doc = PDDocument.load(R40_NEW_FORM_PATH);
addTextToPage(doc);
doc.save(R40_COMPLETED_FORM_PATH);
doc.close();
}
private static void addTextToPage(PDDocument doc) throws Exception {
List pages = doc.getDocumentCatalog().getAllPages();
PDPage firstPage = (PDPage) pages.get(0);
PDPageContentStream contentStream = new PDPageContentStream(doc, firstPage, true, true);
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 24);
contentStream.beginText();
contentStream.setNonStrokingColor(Color.BLACK);
contentStream.moveTextPositionByAmount(100, 200);
contentStream.drawString("HELLO RICHARD!!");
contentStream.endText();
contentStream.close();
}
}