Getting PDF page length

650 Views Asked by At

In my articles which formatted PDF, one or more pages may be blanked and I want to detect them and remove from PDF file. If I can identify pages that are less than 60 KB, I think I can detect the pages that are empty. Because they're probably empty.

I tried like this:

var reader = new PdfReader("D:\\_test\\file.pdf");
/*
 * With reader.FileLength, I can get whole pdf file size.
 * But I dont know, how can I get pages'sizes...
 */
for (var i = 1; i <= reader.NumberOfPages; i++)
{
    /*
     * MessageBox.Show(???);
     */
}
1

There are 1 best solutions below

0
On

I would do this in 2 steps:

  • first go over the document using IEventListener to detect which pages are empty
  • once you've determined which pages are empty, simply create a new document by copying the non-empty pages from the source document into the new document

step 1:

List<Integer> emptyPages = new ArrayList<>();
PdfDocument pdfDocument = new PdfDocument(new PdfReader(new File(SRC)));
for(int i=1;i<pdfDocument.getNumberOfPages();i++){
    IsEmptyEventListener l = new IsEmptyEventListener();
    new PdfCanvasProcessor(l).processPageContent(pdfDocument.getPage(i));
    if(l.isEmptyPage()){
        emptyPages.add(i);
    } 
}

Then you need the proper implementation of IsEmptyEventListener. Which may be tricky and depend on your specific document(s). This is a demo.

class IsEmptyEventListener implements IEventListener {
    private int eventCount = 0;
    public void eventOccurred(IEventData data, EventType type){
        // perhaps count only text rendering events?
        eventCount++;
    }
    public boolean isEmptyPage(){ return eventCount < 32; }
}

step 2:

Based on this example: https://developers.itextpdf.com/examples/stamping-content-existing-pdfs/clone-reordering-pages

void copyNonBlankPages(List<Integer> blankPages, PdfDocument src, PdfDocument dst){
    int N = src.getNumberOfPages();
    List<Integer> toCopy = new ArrayList<>();
    for(int i=1;i<N;i++){
        if(!blankPages.contains(i)){
            toCopy.add(i);
        }
    }
    src.copyPagesTo(toCopy, dst);
}