我有一个不包含任何字体的现有PDF(仅图像)。我想使用低级画布操作将一些其他文本标记到首页上。当我在iText 7中执行此操作时,生成的PDF缺少字体资源字典条目(在分析生成的文件时将导致NPE)。
除了canvas.setFontAndSize()之外,我还需要做些其他事情来获取要添加到输出中的字体资源吗?
这是一个重新测试问题的单元测试:
public class CheckFontResourceInclusion {
@Test
public void test() throws Exception {
// create a document to stamp
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(PdfDocument doc = new PdfDocument(new PdfWriter(baos))){
doc.addNewPage();
}
// stamp it
StampingProperties stampProps = new StampingProperties();
PdfFont font = PdfFontFactory.createFont();
ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
try(PdfDocument doc = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())), new PdfWriter(resultStream), stampProps)){
PdfPage page = doc.getPage(1);
PdfCanvas canvas = new PdfCanvas(page.newContentStreamAfter(), new PdfResources(), doc);
canvas.beginText();
canvas.setTextRenderingMode(2);
canvas.setFontAndSize(font, 42);
canvas.setTextMatrix(1, 0, 0, -1, 100, 100);
canvas.showText("TEXT TO STAMP");
canvas.endText();
}
// parse text
try(PdfDocument doc = new PdfDocument(new PdfReader(new ByteArrayInputStream(resultStream.toByteArray())))){
LocationTextExtractionStrategy strat = new LocationTextExtractionStrategy();
PdfCanvasProcessor processor = new PdfCanvasProcessor(strat);
processor.processPageContent(doc.getPage(1));
Assert.assertEquals("TEXT TO STAMP", strat.getResultantText());
}
}
}
这是导致的失败:
java.lang.NullPointerException
at com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor$SetTextFontOperator.invoke(PdfCanvasProcessor.java:811)
at com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor.invokeOperator(PdfCanvasProcessor.java:456)
at com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor.processContent(PdfCanvasProcessor.java:285)
at com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor.processPageContent(PdfCanvasProcessor.java:306)
at
答案 0 :(得分:0)
错误与此earlier question中的错误相同:您使用了一个一次性资源对象,因此结果中缺少字体资源。
您可以通过使用实际的页面资源来解决此问题。只需替换
PdfCanvas canvas = new PdfCanvas(page.newContentStreamAfter(), new PdfResources(), doc);
作者
PdfCanvas canvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), doc);