public void manipulatePdf(String src, String dest) throws DocumentException, IOException { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); AcroFields fields = stamper.getAcroFields(); fields.setGenerateAppearances(true); /** * This method is used instead 'BaseFont createFont(String name, String encoding, boolean * embedded)' in order to avoid the font cashing. The cashed font could be mistakenly used in * another tests. This could cause a test failure on some platforms. */ BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false, null, null, false); fields.setFieldProperty("test", "textfont", bf, null); fields.setField("test", VALUE); fields.setFieldProperty("test2", "textfont", bf, null); fields.setField("test2", VALUE); stamper.close(); }
public static void fillPdfForm(PdfStamper stamper, Map<String, String> pdfStamps) throws Exception { AcroFields form = stamper.getAcroFields(); Iterator<Entry<String, String>> it = pdfStamps.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next(); form.setField(pairs.getKey(), pairs.getValue()); it.remove(); // avoids a ConcurrentModificationException } }
public static void main(String args[]) { String jsonFilename = args[0]; String inputFilename = args[1]; String outputFilename = args[2]; try { BufferedReader jsonReader = new BufferedReader(new FileReader(jsonFilename)); FileOutputStream outputStream = new FileOutputStream(outputFilename); PdfReader reader = new PdfReader(inputFilename); PdfStamper stamper = new PdfStamper(reader, outputStream); StringBuffer jsonData = new StringBuffer(); String currentLine; // Read in all the JSON data while ((currentLine = jsonReader.readLine()) != null) { jsonData.append(currentLine); } // Convert JSON string into an accessible JSON object JSONObject jsonObj = new JSONObject(jsonData.toString()); Iterator fieldIterator = jsonObj.keys(); AcroFields fields = stamper.getAcroFields(); // Set all the fields based on the JSON config while (fieldIterator.hasNext()) { String fieldName = (String) fieldIterator.next(); String fieldValue = (String) jsonObj.getString(fieldName); fields.setField(fieldName, fieldValue); } // Flatten and save the PDF stamper.setFormFlattening(true); stamper.close(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); } catch (DocumentException e) { System.err.println("DocumentException: " + e.getMessage()); } catch (JSONException e) { System.err.println("JSONException: " + e.getMessage()); } }