0

I am using PdfFormXObject pageCopy = sourcePage.CopyAsFormXObject(pdf); to then insert pageCopy into a new PDF page using pdfCanvas.AddXObjectFittedIntoRectangle. The copied page is visible in the new PDF as expected, but it how has it's 'hidden' OCGs visible.

The reason I am doing this is to be able to take a PDF page, scale and crop it and add it to a new PDF where it may be collated with other contents.

Is there a way to remove OCG PDF content prior to create the XObject, or is there a different way of achieving my goal without using the XObject route that allows me to maintain the 'off' status of hidden OCGs

oliver
  • 33
  • 1
  • 1
  • 6

1 Answers1

1

OCG removal functionality is not yet available in iText 7.

There is, however, a workaround that you can try to apply: we can copy all the information about OCGs from your source document to the target document which should create the same OCGs in the target document and preserve default on/off states.

To copy the OCGs, you can copy a page from one document to another one (which is going to copy all the OCGs) and then remove that page.

When the OCG removal functionality becomes available in iText the approach would become cleaner but for now you can use the code similar to the following:

PdfDocument sourceDocument = new PdfDocument(new PdfReader(sourcePdfPath));

PdfDocument targetDocument = new PdfDocument(new PdfWriter(targetPdfPath));

PdfFormXObject pageCopy = sourceDocument.getFirstPage().copyAsFormXObject(targetDocument);
PdfPage page = targetDocument.addNewPage();
PdfCanvas canvas = new PdfCanvas(page);
canvas.addXObject(pageCopy);

// Workaround: copying the page from source document to destination document also copies OCGs
sourceDocument.copyPagesTo(1, 1, targetDocument);
// Workaround: remove the page that we only copied to make sure OCGs are copied
targetDocument.removePage(targetDocument.getNumberOfPages());

sourceDocument.close();
targetDocument.close();
Alexey Subach
  • 11,903
  • 7
  • 34
  • 60