If you can assume that an page is empty if there is no text, you can go with the following code. If you have pdfs with pages with only charts, images, ... this won't work I think.
First use xpdf/pdf2text to extract the txt of the pdf. Detect "Page break/new pages" with char 0x0C. To remove empty pages just use pdftk and cat all non-empty pages to a new pdf.
/** page break constant in pdf */
private static final String PAGEBREAK = new String(new byte[] { 0x0C });
/** dummy string for an empty page */
private static final String EMPTY_PAGE = "EMPTY_PAGE";
/**
* @param pdfIn
* @param pdfOut
* @param txt --> contains pdf2txt output of tool xpdf/pdftotext.exe
* @return
* @throws Exception
*/
private static byte[] removeEmptyPages(File pdfIn, File pdfOut, String txt) throws Exception {
// replace "page break" with some dummytext+"page break"
txt = txt.replace(PAGEBREAK, EMPTY_PAGE + PAGEBREAK);
StringTokenizer tokenizer = new StringTokenizer(txt, PAGEBREAK);
int pageCounter = 0;
String pagesWithContent = "";
boolean foundEmptyPage = false;
String currentPage = null;
while (tokenizer.hasMoreTokens()) {
currentPage = tokenizer.nextToken();
pageCounter++;
if (currentPage.equals(EMPTY_PAGE)) {
foundEmptyPage = true;
} else {
pagesWithContent += (pageCounter + " ");
}
}
if (foundEmptyPage) {
String pdfShellCmd = "..\\tools\\pdftk\\bin\\pdftk.exe \"$IN\" cat $PAGES output \"$OUT\"";
String cmd = pdfShellCmd.replace("$IN", pdfIn.toString());
cmd = cmd.replace("$OUT", pdfOut.toString());
cmd = cmd.replace("$PAGES", pagesWithContent);
int resultCode = executeShellCmd(cmd);
if (0 == resultCode) {
return FileTools.readFile(pdfOut).array();
} else {
throw new Exception("Result code for " + cmd + " was " + resultCode);
}
} else {
// if no empty pages, return input file
copyFile(pdfIn, pdfOut);
return read(pdfOut);
}
}