Reputation: 21
I'm using pdfbox 2.0.8 - need to create a layer and add some graphic there.
I started from How do I make modifications to existing layer(Optional Content Group) in pdf?
which however is based on 1.8. I tried to adapt to 2.0 and managed to create the layer, but it is completely unclear how then you can create a new resource and add it to the layer - i.e. how the props.putMapping(resourceName, layer); which was in 1.8 has to be rewritten
Upvotes: 1
Views: 1552
Reputation: 96064
Equivalent to the PDFBox 1.8 code in the answer referenced by the OP is the following code:
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();
}
which can be used like this:
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
)
Upvotes: 1