0

I have a pdf which contains a lot of invisible paths. Since the amount of path produces problems later on, I would like to remove the ones that have white colors.

So far I am trying to do this with a ContentScanner:

public class FilterWhitePathScanner implements Scanner {
private static final Logger LOG = LoggerFactory.getLogger(FilterWhitePathScanner.class);

private int count = 0;

public void scan(ContentScanner level) {
    if (level == null)
        return;

    while (level.moveNext()) {
        ContentObject object = level.getCurrent();
        if (object instanceof ContainerObject) {
            // Scan the inner level!
            scan(level.getChildLevel());
        } else if (object instanceof org.pdfclown.documents.contents.objects.Path) {
            AffineTransform ctm = level.getState().getCtm();
            Color<?> strokeColor = level.getState().getStrokeColor();
            Color<?> fillColor = level.getState().getFillColor();
            if (checkWhite(fillColor) && checkWhite(strokeColor)) {
                level.remove();
            } else {
                LOG.info("Stroke Color " + strokeColor + " - Fill Color " + fillColor);
            }
        } else {
            LOG.info("Object:" + object);
        }
    }
}

It recognizes the paths correctly, but in the end these are not removed from the PDF. Here the code handling the PDF (it extracts only one page from the source pdf):

        Document targetDoc = new File().getDocument();
        targetDoc.getPages().add(sourceDoc.getPages().get(pageNum).clone(targetDoc));
        Page page = targetDoc.getPages().get(0);
        Contents contents = page.getContents();
        FilterWhitePathScanner filterWhitePathScanner = new FilterWhitePathScanner();
        filterWhitePathScanner.scan(new ContentScanner(contents));
        LOG.info("White Paths: " + filterWhitePathScanner.getCount());
        targetDoc.getFile().save(tempFilePath.toFile(), SerializationModeEnum.Standard);

The saved PDF file still contains the paths I tried to remove. How can I remove objects from the PDF finally?

Thanks, Thomas

Thomas Letsch
  • 930
  • 1
  • 8
  • 15

1 Answers1

1

Finally found the solution in the Java doc: You have to call contents.flush(); to persist the changes into the pdf file.

So I added this line to the PDF handling code before calling save and it works!

Thomas Letsch
  • 930
  • 1
  • 8
  • 15