Reputation: 49
I am in a requirement to split a pdf into two, one with image and one with text. I dont want to remove the text which are behind an image and it should be the part of the image pdf. I want to extract only the top layered text in the PDF. Can any one help on this?
I already extracted the image and text into two pdfs by looping through pdf operators. I am facing trouble when not to remove the text behind the PDF.
Upvotes: 1
Views: 545
Reputation: 49
Code for removing text:
PDDocument document = null;
try {
document = PDDocument.load(new File(inputfilePath), password);
PDPageTree allPages = document.getDocumentCatalog().getPages();
for (int i = 0; i < allPages.getCount(); i++) {
PDPage page = (PDPage) allPages.get(i);
PDFStreamParser parser = new PDFStreamParser(page);
parser.parse();
List tokens = parser.getTokens();
List newTokens = new ArrayList();
for (int j = 0; j < tokens.size(); j++) {
Object token = tokens.get(j);
if (token instanceof Operator) {
Operator op = (Operator) token;
if (op.getName().equalsIgnoreCase(
"tj")) {
try {
// remove the one argument to this operator
newTokens.remove(newTokens.size() - 1);
} catch (Exception e) {
e.printStackTrace();
}
continue;
}
// Header doesn't contain versioninfo
}
newTokens.add(token);
}
PDStream newContents = new PDStream(document);
ContentStreamWriter writer = new ContentStreamWriter(newContents.createOutputStream());
writer.writeTokens(newTokens);
// In writeTokens method, I closed the output stream.. This is
// for future reference.. or it will throw stream not closed
// error
newContents.addCompression();
page.setContents(newContents);
if (DEBUG)
System.out.println("Background image pdf creation process");
document.setAllSecurityToBeRemoved(true);
document.save(outputFolder + "/img_" + fileName);
And for removing the images and shades, I used the below code:
for (int j = 0; j < tokens.size(); j++) {
Object token = tokens.get(j);
if (token instanceof Operator) {
Operator op = (Operator) token;
// Text Extraction removing image and shades
if (op.getName().equalsIgnoreCase("do") || op.getName().equalsIgnoreCase("sh")
|| op.getName().equalsIgnoreCase("gs") || op.getName().equalsIgnoreCase("bi")
|| op.getName().equalsIgnoreCase("id") || op.getName().equalsIgnoreCase("ei")
|| op.getName().equalsIgnoreCase("bmc") || op.getName().equalsIgnoreCase("bdc")
|| op.getName().equalsIgnoreCase("emc") || op.getName().equalsIgnoreCase("m")
|| op.getName().equalsIgnoreCase("w")
|| op.getName().equalsIgnoreCase("re")
) {
// remove the one argument to this operator
newTokens.remove(newTokens.size() - 1);
continue;
}
}
newTokens.add(token);
}
Upvotes: 1