Professional Documents
Culture Documents
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
PDFReader
PDFStamper
AcroForms
set/get fields
Example 5
(Set, Get, Rename Fields)
import java.io.*;
import java.util.*;
import com.lowagie.text.pdf.*;
clsStart();
}
private String clsStart() {
String s ="\n\nimport java.util.*;";
s+="\n\npublic class " + className + " implements PdfForm{";
s+="\n\n private HashMap data = new HashMap();";
s+="\n private String pdfTemplateName = \""+formName+"\";\n";
return s;
}
public Irs1040() {}
public void setFirstName(String value) {
data.put("firstName", value);
}
public void setLastName(String value) {
data.put("lastName", value);
}
A First Full Example
• Write the data to the wrapper classes
• Use the original PDF forms as templates
• Use PdfStamper to get the PDF fields
• Set the field values in the form.
• Set form flattening to make the data fields
no longer editable.
Populating the PDF
Wrapper SomeForm.pdf
PDFReader
PDFStamper
AcroForms
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
try{
String templateName = pdfForm.getPdfTemplateName();
PdfReader reader = new PdfReader(templateName);
PdfStamper stamp = new PdfStamper(reader,
new FileOutputStream(outputPDF));
AcroFields acroFields = stamp.getAcroFields();
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
try{
// this is a blank document we will be adding pages to
Document mergedPDF = new Document();
// makes copies of PDF documents.
PdfCopy writer = new PdfCopy(mergedPDF, outStream);
// open the document so we can add content
mergedPDF.open();
if(value != null){
String fieldStringValue = (String) value;
form.setField(fieldName, fieldStringValue);
}
}
//gets rid of editable fields, makes them part of the document
stamp.setFormFlattening(true);
try{
PdfProcessor processor = new PdfProcessor(forms,
new FileOutputStream("C:\\itext\\myResults", false));
}catch(FileNotFoundException ex){
ex.printStackTrace();
}
}
Output Demo
PDFs in a Web Application
• Create the document using the iText API
and a ByteArrayOutputStream
• Set HTTP response headers
• Get ServletOutputStream object
• Write document bytes to the
ServletOutputStream
• Flush the ServletOutputStream
Example 8 (Servlet Code)
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;