Created
February 24, 2015 09:46
-
-
Save kBashar/3e19c44b2022a5364c1e to your computer and use it in GitHub Desktop.
It's a simple class to print strings in a pdf page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kbashar.pdfboxtry; | |
import org.apache.pdfbox.cos.COSArray; | |
import org.apache.pdfbox.cos.COSStream; | |
import org.apache.pdfbox.cos.COSString; | |
import org.apache.pdfbox.pdmodel.PDDocument; | |
import org.apache.pdfbox.pdmodel.PDPage; | |
import org.apache.pdfbox.util.PDFOperator; | |
import java.io.IOException; | |
import java.util.List; | |
/** | |
* Created by kbashar on 2/24/15. | |
*/ | |
public class StringPrinting { | |
public void printString(String fileName) throws IOException { | |
PDDocument document = PDDocument.load(fileName); | |
List<PDPage> pages = document.getDocumentCatalog().getAllPages(); | |
PDPage firstPage = pages.get(0); | |
COSStream stream = firstPage.getContents().getStream(); | |
List tokens = stream.getStreamTokens(); | |
for (int j =0;j<tokens.size();j++) { | |
Object obj = tokens.get(j); | |
//System.out.println(obj.toString()); | |
if (obj instanceof PDFOperator) { | |
PDFOperator op = (PDFOperator) obj; | |
if( op.getOperation().equals( "Tj" ) ) | |
{ | |
//Tj takes one operator and that is the string | |
//to display so lets update that operator | |
COSString previous = (COSString)tokens.get( j-1 ); | |
System.out.println(previous); | |
String string = previous.getString(); | |
System.out.println(string); | |
} | |
else if (op.getOperation().equals("TJ")) { | |
COSArray previous = (COSArray) tokens.get(j - 1); | |
for (int k = 0; k < previous.size(); k++) { | |
Object arrElement = previous.getObject(k); | |
if (arrElement instanceof COSString) { | |
COSString cosString = (COSString) arrElement; | |
String string = cosString.getString(); | |
System.out.print(string); | |
} | |
} | |
//System.out.println(); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) { | |
StringPrinting strPrnt = new StringPrinting(); | |
try { | |
if (args.length==1) { | |
strPrnt.printString(args[0]); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment