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();
}
(AddContentToOCG)
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
)