This repository has been archived by the owner on Jun 12, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FormFillFlatten.java
70 lines (59 loc) · 1.93 KB
/
FormFillFlatten.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.*;
import java.util.Iterator;
// itext
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
// JSON-java
import org.json.JSONObject;
import org.json.JSONException;
public class FormFillFlatten
{
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());
}
}
}