PDFBox添加的文本未出现在PDF文档中

时间:2017-02-16 18:52:57

标签: pdf pdfbox

我正在使用PDFBox 1.8.10向PDF文档添加文本。 除了在文档中添加文本(使用pdf结构检查器检查)但未在PDF中显示的文档之外,它工作正常。 示例文档位于:https://kali-docs.ks2.fr/share/s/Ut_LdO8LR4WEeEd1y2k58Q

因为我想将一些自定义AlphaConstant设置为文本(和矩形),所以我使用Graphics State Parameter Dictionaries来添加文本。

使用的代码:

PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, pdfPage, true, true);                

this.textGraphicState = new PDExtendedGraphicsState();
textGraphicState.setNonStrokingAlphaConstant(1f);
Map<String, PDExtendedGraphicsState> graphicsStatesMap = pdfPage.getResources().getGraphicsStates();
if (graphicsStatesMap == null)
{
    graphicsStatesMap = new HashMap<String, PDExtendedGraphicsState>();
}
graphicsStatesMap.put("textGraphicState", textGraphicState);
pdfPage.getResources().setGraphicsStates(graphicsStatesMap);
contentStream.appendRawCommands("/textGraphicState gs\n");
contentStream.setNonStrokingColor(fontColor);
contentStream.beginText();
contentStream.setFont( font, fontSize );
contentStream.moveTextPositionByAmount( pagePosX, pagePosY );
contentStream.drawString(text);
contentStream.endText();
contentStream.close();

有什么想法吗?

谢谢, 文森特

1 个答案:

答案 0 :(得分:1)

重置图形状态解决了我的问题(PDPageContentStream构造函数的第五个参数)。

PDPageContentStream contentStream = new PDPageContentStream(pdfDoc,pdfPage,true,true,true);