PDDocument overlay1Doc = PDDocument.load(overlay1);
try
{
LayerUtility layerUtil = new LayerUtility(targetDoc);
PDXObjectForm form = layerUtil.importPageAsForm(overlay1Doc, 0);
PDDocumentCatalog catalog = targetDoc.getDocumentCatalog();
PDPage targetPage = (PDPage)catalog.getAllPages().get(0);
layerUtil.wrapInSaveRestore(targetPage);
AffineTransform at = new AffineTransform();
PDOptionalContentGroup ocg = layerUtil.appendFormAsLayer(
targetPage, form, at, "overlay");
//This is how the layer could be disabled after adding it
//catalog.getOCProperties().setGroupEnabled(ocg.getName(), false);
targetDoc.save(targetFile.getAbsolutePath());
}
finally
{
targetDoc.close();
overlay1Doc.close();
}
PDDocument doc = PDDocument.load(targetFile);
try
{
PDDocumentCatalog catalog = doc.getDocumentCatalog();
//OCGs require PDF 1.5 or later
//TODO need some comfortable way to enable/check the PDF version
//assertEquals("%PDF-1.5", doc.getDocument().getHeaderString());
//assertEquals("1.5", catalog.getVersion());
PDPage page = (PDPage)catalog.getAllPages().get(0);
PDPropertyList props = page.findResources().getProperties();
assertNotNull(props);
PDOptionalContentGroup ocg = props.getOptionalContentGroup(COSName.getPDFName("MC0"));
assertNotNull(ocg);
assertEquals("overlay", ocg.getName());
PDOptionalContentProperties ocgs = catalog.getOCProperties();
PDOptionalContentGroup overlay = ocgs.getGroup("overlay");
assertEquals(ocg.getName(), overlay.getName());
}
finally
{