1 31 package org.pdfbox.examples.persistence; 32 33 import java.io.IOException ; 34 import java.io.OutputStream ; 35 import java.io.FileOutputStream ; 36 37 import java.util.Iterator ; 38 39 import org.pdfbox.pdfparser.PDFParser; 40 41 import org.pdfbox.pdfwriter.COSWriter; 42 43 import org.pdfbox.cos.COSDocument; 44 import org.pdfbox.cos.COSString; 45 import org.pdfbox.cos.COSBase; 46 import org.pdfbox.cos.COSDictionary; 47 import org.pdfbox.cos.COSObject; 48 import org.pdfbox.cos.COSName; 49 50 import org.pdfbox.exceptions.COSVisitorException; 51 52 58 public class FieldsDoc 59 { 60 63 public FieldsDoc() 64 { 65 super(); 66 } 67 78 public void doIt(String in, String out, String name, String value) throws IOException , COSVisitorException 79 { 80 java.io.InputStream is = null; 81 COSDocument doc = null; 82 OutputStream os = null; 83 COSWriter writer = null; 84 try 85 { 86 is = new java.io.FileInputStream (in); 87 PDFParser parser = new PDFParser(is); 88 parser.parse(); 89 90 doc = parser.getDocument(); 91 92 setField(doc, new COSString(name), new COSString(value)); 93 94 os = new FileOutputStream (out); 95 writer = new COSWriter(os); 96 97 writer.write(doc); 98 99 } 100 finally 101 { 102 is.close(); 103 doc.close(); 104 os.close(); 105 writer.close(); 106 } 107 } 108 115 public static void main(String [] args) 116 { 117 FieldsDoc app = new FieldsDoc(); 118 try 119 { 120 if( args.length != 4 ) 121 { 122 app.usage(); 123 } 124 else 125 { 126 app.doIt( args[0], args[1], args[2], args[3]); 127 } 128 } 129 catch (Exception e) 130 { 131 e.printStackTrace(); 132 } 133 } 134 144 public void setField(COSDocument doc, COSString name, COSString value) 145 { 146 for (Iterator i = doc.getObjects().iterator(); i.hasNext();) 147 { 148 COSObject obj = (COSObject) i.next(); 149 COSBase base = obj.getObject(); 150 if (base instanceof COSDictionary) 151 { 152 COSDictionary dict = (COSDictionary) base; 153 COSBase type = dict.getItem(COSName.TYPE); 154 if (type != null && type.equals(COSName.getPDFName("Annot"))) 155 { 156 COSBase subtype = dict.getItem(COSName.getPDFName("Subtype")); 157 if (subtype != null && subtype.equals(COSName.getPDFName("Widget"))) 158 { 159 COSBase fname = dict.getItem(COSName.getPDFName("T")); 161 if (fname != null && fname.equals(name)) 162 { 163 dict.setItem(COSName.getPDFName("V"), value); 164 } 165 } 166 } 167 } 168 } 169 } 170 173 private void usage() 174 { 175 System.err.println( "usage: " + this.getClass().getName() + " <input-file> <output-file> <name> <value>" ); 176 } 177 } | Popular Tags |