I am working with PDF/A style PDF documents that have a mixture of scanned in, full page size images and then a page or two after the image pages that have text in a ColumnText object.
Using Java, how do i detect which pages have an image?
The intent to detect which pages have either images or text is to determine where the first page with text appears. I need to either edit the text or replace the page(s) with text with updated text. The pages with images would remain untouched.
I'm using iText5 and don't currently have the option of upgrading to iText7.
Here's the solution I implemented with the solution provided by @mkl:
ImageDetector.java
package org.test.pdf;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
public class ImageDetector implements RenderListener {
public void beginTextBlock() { }
public void endTextBlock() { }
public void renderText(TextRenderInfo renderInfo) {
textFound = true;
}
public void renderImage(ImageRenderInfo renderInfo) {
imageFound = true;
}
boolean textFound = false;
boolean imageFound = false;
}
PdfDocumentServiceTest.java
package org.test.pdf;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.test.PdfService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@ActiveProfiles({"local", "testing"})
@DirtiesContext
@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest
public class PdfDocumentServiceTest {
@Autowired
private PdfService pdfService;
@Test
public void testFindImagesInPdf(Long pdfId)) {
final byte[] resource = PdfService.getPdf(pdfId);
int imagePageCount = 0;
int textPageCount = 0;
if (resource != null && resource.length > 0) {
PdfReader reader = new PdfReader(resource);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
ImageDetector imageDetector = new ImageDetector();
parser.processContent(pageNumber, imageDetector);
if (imageDetector.imageFound) {
imagePageCount++;
}
if (imageDetector.textFound) {
textPageCount++;
}
}
Assert.assertTrue(imagePageCount > 0);
Assert.assertTrue(textPageCount > 0);
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…