In last version of PDFbox 2.0.27 and previous version, when stream draw a PDFormXObject all disabled optional content group reappears.
This bug block all work with layered pdf. There is a way to totally removed ocg ? Do you have an idea ?
Edit : In a new PDocument, I add this pdf with multiple ocg.
https://www.pdfill.com/example/pdf_layer_new.pdf
Result with all ocg visible (WeTransfer file available 7 days) :
https://wetransfer.com/downloads/6550dcb45764d65fe96945b36e5d5b7220221010104929/2f07fd
PDDocument tmpPDFDocument = PDDocument.load(server.pdf());
LayerUtility utility = new LayerUtility(tmpPDFDocument);
PDFormXObject mapPDF = utility.importPageAsForm(tmpPDFDocument, 0);
stream.drawForm(form);
Edit 2 :
I try to clean maximum my code and after trying many times with 2.0.27, maybe it's my fault, do you see any error here ?
Result : https://wetransfer.com/downloads/8d8f27f182c5b47bc7226acd5595dff620221011134625/97ea54
public void createFile2(File output, LayoutPage layoutPage, LocalServer server) throws IOException {
// Creation du fichier de sortie
if (!output.exists() && !output.createNewFile())
throw new IOException();
// initialise le format de la page pdf
PDRectangle box = new PDRectangle(0f, 0f, 3000, 3000);
PDPage page = new PDPage(box);
// creation du document pdf avec la page, le document doit rester ouvert
// pendant toute l'impression (ignore sonar recommendation)
PDDocument document = new PDDocument();
document.addPage(page);
// initialise le context
PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.OVERWRITE, true, true);
PDDocument tmpPDFDocument = PDDocument.load(server.pdf()); // file url to import here
LayerUtility utility = new LayerUtility(tmpPDFDocument);
utility.wrapInSaveRestore(tmpPDFDocument.getPage(0));
PDFormXObject mapPDF = utility.importPageAsForm(tmpPDFDocument, 0);
stream.drawForm(mapPDF);
stream.close();
document.save(output);
document.close();
}
```
Correct
LayerUtility utility = new LayerUtility(tmpPDFDocument);
to
LayerUtility utility = new LayerUtility(document);
LayerUtility must be initialized with the document you want to modify.