1 31 package org.pdfbox.examples.pdmodel; 32 33 import java.io.IOException ; 34 import java.io.OutputStream ; 35 import java.util.List ; 36 37 import org.pdfbox.cos.COSArray; 38 import org.pdfbox.cos.COSString; 39 import org.pdfbox.exceptions.COSVisitorException; 40 41 import org.pdfbox.pdfparser.PDFStreamParser; 42 import org.pdfbox.pdfwriter.ContentStreamWriter; 43 import org.pdfbox.pdmodel.PDDocument; 44 import org.pdfbox.pdmodel.PDPage; 45 46 import org.pdfbox.pdmodel.common.PDStream; 47 48 import org.pdfbox.util.PDFOperator; 49 50 51 59 public class ReplaceString 60 { 61 64 public ReplaceString() 65 { 66 super(); 67 } 68 69 80 public void doIt( String inputFile, String outputFile, String strToFind, String message) 81 throws IOException , COSVisitorException 82 { 83 PDDocument doc = null; 85 try 86 { 87 doc = PDDocument.load( inputFile ); 88 List pages = doc.getDocumentCatalog().getAllPages(); 89 for( int i=0; i<pages.size(); i++ ) 90 { 91 PDPage page = (PDPage)pages.get( i ); 92 PDStream contents = page.getContents(); 93 PDFStreamParser parser = new PDFStreamParser(contents.getStream() ); 94 parser.parse(); 95 List tokens = parser.getTokens(); 96 for( int j=0; j<tokens.size(); j++ ) 97 { 98 Object next = tokens.get( j ); 99 if( next instanceof PDFOperator ) 100 { 101 PDFOperator op = (PDFOperator)next; 102 if( op.getOperation().equals( "Tj" ) ) 105 { 106 COSString previous = (COSString)tokens.get( j-1 ); 109 String string = previous.getString(); 110 string = string.replaceFirst( strToFind, message ); 111 previous.reset(); 112 previous.append( string.getBytes() ); 113 } 114 else if( op.getOperation().equals( "TJ" ) ) 115 { 116 COSArray previous = (COSArray)tokens.get( j-1 ); 117 for( int k=0; k<previous.size(); k++ ) 118 { 119 Object arrElement = previous.getObject( k ); 120 if( arrElement instanceof COSString ) 121 { 122 COSString cosString = (COSString)arrElement; 123 String string = cosString.getString(); 124 string = string.replaceFirst( strToFind, message ); 125 cosString.reset(); 126 cosString.append( string.getBytes() ); 127 } 128 } 129 } 130 } 131 } 132 PDStream updatedStream = new PDStream(doc); 135 OutputStream out = updatedStream.createOutputStream(); 136 ContentStreamWriter tokenWriter = new ContentStreamWriter(out); 137 tokenWriter.writeTokens( tokens ); 138 page.setContents( updatedStream ); 139 } 140 doc.save( outputFile ); 141 } 142 finally 143 { 144 if( doc != null ) 145 { 146 doc.close(); 147 } 148 } 149 } 150 151 158 public static void main(String [] args) 159 { 160 ReplaceString app = new ReplaceString(); 161 try 162 { 163 if( args.length != 4 ) 164 { 165 app.usage(); 166 } 167 else 168 { 169 app.doIt( args[0], args[1], args[2], args[3] ); 170 } 171 } 172 catch (Exception e) 173 { 174 e.printStackTrace(); 175 } 176 } 177 178 181 private void usage() 182 { 183 System.err.println( "usage: " + this.getClass().getName() + 184 " <input-file> <output-file> <search-string> <Message>" ); 185 } 186 } | Popular Tags |