我正在使用pdfbox 2.0.8 - 需要创建一个图层并在那里添加一些图形。
我开始了 How do I make modifications to existing layer(Optional Content Group) in pdf?然而它基于1.8。我试图适应2.0并设法创建图层,但是完全不清楚如何创建新资源并将其添加到图层 - 即props.putMapping(resourceName,layer);在1.8中必须重写
答案 0 :(得分:1)
等同于the answer referenced by the OP中的PDFBox 1.8代码,代码如下:
void addTextToLayer(PDDocument document, int pageNumber, String layerName, float x, float y, String text) throws IOException
{
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDOptionalContentProperties ocprops = catalog.getOCProperties();
if (ocprops == null)
{
ocprops = new PDOptionalContentProperties();
catalog.setOCProperties(ocprops);
}
PDOptionalContentGroup layer = null;
if (ocprops.hasGroup(layerName))
{
layer = ocprops.getGroup(layerName);
}
else
{
layer = new PDOptionalContentGroup(layerName);
ocprops.addGroup(layer);
}
PDPage page = (PDPage) document.getPage(pageNumber);
PDResources resources = page.getResources();
if (resources == null)
{
resources = new PDResources();
page.setResources(resources);
}
PDFont font = PDType1Font.HELVETICA;
PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true);
contentStream.beginMarkedContent(COSName.OC, layer);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(x, y);
contentStream.showText(text);
contentStream.endText();
contentStream.endMarkedContent();
contentStream.close();
}
可以这样使用:
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
addTextToLayer(document, 0, "MyLayer", 30, 600, "Text in new layer 'MyLayer'");
addTextToLayer(document, 0, "MyOtherLayer", 230, 550, "Text in new layer 'MyOtherLayer'");
addTextToLayer(document, 0, "MyLayer", 30, 500, "Text in existing layer 'MyLayer'");
addTextToLayer(document, 0, "MyOtherLayer", 230, 450, "Text in existing layer 'MyOtherLayer'");
document.save(new File(RESULT_FOLDER, "TextInOCGs.pdf"));
document.close();
(AddContentToOCG test testAddContentToNewOrExistingOCG
)