Chapter 9: Integrating iText in your web applications

These examples were written in the context of Chapter 9 of the book "iText in Action - Second Edition".

Files: 
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.IOException;
import java.util.Date;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
 
public class Hello extends HttpServlet {
 
    /**
     * A simple Hello World Servlet.
     * @see HttpServlet#doGet(
     *      HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/pdf");
        try {
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter.getInstance(document, response.getOutputStream());
            // step 3
            document.open();
            // step 4
            document.add(new Paragraph("Hello World"));
            document.add(new Paragraph(new Date().toString()));
            // step 5
            document.close();
        } catch (DocumentException de) {
            throw new IOException(de.getMessage());
        }
    }
 
    /**
     * A serial version uid
     */
    private static final long serialVersionUID = 4262544639420765610L;
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
 
public class PdfServlet extends HttpServlet {
 
    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        try {
            // Get the text that will be added to the PDF
            String text = request.getParameter("text");
            if (text == null || text.trim().length() == 0) {
                 text = "You didn't enter any text.";
            }
            // step 1
            Document document = new Document();
            // step 2
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            // step 3
            document.open();
            // step 4
            document.add(new Paragraph(String.format(
                "You have submitted the following text using the %s method:",
                request.getMethod())));
            document.add(new Paragraph(text));
            // step 5
            document.close();
 
            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();
        }
        catch(DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 6067021675155015602L;
 
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import part2.chapter08.Subscribe;
 
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PushbuttonField;
 
public class SubmitForm {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter09/submit_me.pdf";
 
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     * @param dest the resulting PDF
     * @throws IOException
     * @throws DocumentException
     */
    public void manipulatePdf(String src, String dest)
        throws IOException, DocumentException {
        // create a reader
        PdfReader reader = new PdfReader(src);
        // create a stamper
        PdfStamper stamper = new PdfStamper(reader,
            new FileOutputStream(dest));
        // create a submit button that posts the form as an HTML query string
        PushbuttonField button1 = new PushbuttonField(
            stamper.getWriter(), new Rectangle(90, 660, 140, 690), "post");
        button1.setText("POST");
        button1.setBackgroundColor(new GrayColor(0.7f));
        button1.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
        PdfFormField submit1 = button1.getField();
        submit1.setAction(PdfAction.createSubmitForm(
            "/book/request", null,
            PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES));
        // add the button
        stamper.addAnnotation(submit1, 1);
        // create a submit button that posts the form as FDF
        PushbuttonField button2 = new PushbuttonField(
            stamper.getWriter(), new Rectangle(200, 660, 250, 690), "FDF");
        button2.setBackgroundColor(new GrayColor(0.7f));
        button2.setText("FDF");
        button2.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
        PdfFormField submit2 = button2.getField();
        submit2.setAction(PdfAction.createSubmitForm(
            "/book/request", null, PdfAction.SUBMIT_EXCL_F_KEY));
        // add the button
        stamper.addAnnotation(submit2, 1);
        // create a submit button that posts the form as XFDF
        PushbuttonField button3 = new PushbuttonField(
                stamper.getWriter(), new Rectangle(310, 660, 360, 690), "XFDF");
        button3.setBackgroundColor(new GrayColor(0.7f));
        button3.setText("XFDF");
        button3.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
        PdfFormField submit3 = button3.getField();
        submit3.setAction(PdfAction.createSubmitForm(
            "/book/request", null, PdfAction.SUBMIT_XFDF));
        // add the button
        stamper.addAnnotation(submit3, 1);
        // create a reset button
        PushbuttonField button4 = new PushbuttonField(
            stamper.getWriter(), new Rectangle(420, 660, 470, 690), "reset");
        button4.setBackgroundColor(new GrayColor(0.7f));
        button4.setText("RESET");
        button4.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
        PdfFormField reset = button4.getField();
        reset.setAction(PdfAction.createResetForm(null, 0));
        // add the button
        stamper.addAnnotation(reset, 1);
        // close the stamper
        stamper.close();
        reader.close();
    }
 
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException, DocumentException {
        new Subscribe().createPdf(Subscribe.FORM);
        new SubmitForm().manipulatePdf(Subscribe.FORM, RESULT);
    }
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class ShowData
 */
public class ShowData extends HttpServlet {
 
    /**
     * Show keys and values passed to the query string with GET
     * as plain text.
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    @SuppressWarnings("unchecked")
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        Enumeration<String> parameters = request.getParameterNames();
        String parameter;
        while (parameters.hasMoreElements()) {
            parameter = parameters.nextElement();
            out.println(
                String.format("%s: %s", parameter, request.getParameter(parameter)));
        }
    }
 
    /**
     * Shows the stream passed to the server with POST as plain text.
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("text/plain");
        OutputStream os = response.getOutputStream();
        InputStream is = request.getInputStream();
        byte[] b = new byte[256];  
        int read;  
        while ((read = is.read(b)) != -1) {  
            os.write(b, 0, read);  
        } 
    }
 
    /**
     * Serial version UID
     */
    private static final long serialVersionUID = 388110564278942780L;
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PushbuttonField;
import com.itextpdf.text.pdf.TextField;
 
public class FormServlet extends HttpServlet {
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/pdf");
        try {
            // We get a resource from our web app
            InputStream is
                = getServletContext().getResourceAsStream("/subscribe.pdf");
            // We create a reader with the InputStream
            PdfReader reader = new PdfReader(is, null);
            // We create an OutputStream for the new PDF
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // Now we create the PDF
            PdfStamper stamper = new PdfStamper(reader, baos);
            // We add a submit button to the existing form
            PushbuttonField button = new PushbuttonField(
                stamper.getWriter(), new Rectangle(90, 660, 140, 690), "submit");
            button.setText("POST");
            button.setBackgroundColor(new GrayColor(0.7f));
            button.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
            PdfFormField submit = button.getField();
            submit.setAction(PdfAction.createSubmitForm(
                "/book/form", null, PdfAction.SUBMIT_HTML_FORMAT));
            stamper.addAnnotation(submit, 1);
            stamper.close();
            reader.close();
            // We write the PDF bytes to the OutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
        } catch (DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/pdf");
        try {
            // We get a resource from our web app
            InputStream is
                = getServletContext().getResourceAsStream("/subscribe.pdf");
            // We create a reader with the InputStream
            PdfReader reader = new PdfReader(is, null);
            // We create an OutputStream for the new PDF
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // Now we create the PDF
            PdfStamper stamper = new PdfStamper(reader, baos);
            // We alter the fields of the existing PDF
            AcroFields fields = stamper.getAcroFields();
            fields.setFieldProperty(
                "personal.password", "clrfflags", TextField.PASSWORD, null);
            Set<String> parameters = fields.getFields().keySet();
            for (String parameter : parameters) {
                fields.setField(parameter, request.getParameter(parameter));
            }
            stamper.setFormFlattening(true);
            stamper.close();
            reader.close();
            // We write the PDF bytes to the OutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
        } catch (DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * A serial version UID
     */
    private static final long serialVersionUID = 4423393678732940807L;
 
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.itextpdf.text.pdf.FdfWriter;
 
public class CreateFDF extends HttpServlet {
 
    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/vnd.adobe.fdf");
        response.setHeader("Content-Disposition",
            "attachment; filename=\"subscribe.fdf\"");
        FdfWriter fdf = new FdfWriter();
        fdf.setFieldAsString("personal.name", request.getParameter("name"));
        fdf.setFieldAsString("personal.loginname", request.getParameter("loginname"));
        fdf.setFieldAsString("personal.password", request.getParameter("password"));
        fdf.setFieldAsString("personal.reason", request.getParameter("reason"));
        fdf.setFile("subscribe.pdf");
        fdf.writeTo(response.getOutputStream());
    }
 
    /**
     * Serial version UID
     */
    private static final long serialVersionUID = 4841218549441233308L;
 
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.FdfReader;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PushbuttonField;
import com.itextpdf.text.pdf.TextField;
 
public class FDFServlet extends HttpServlet {
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/pdf");
        try {
            // We get a resource from our web app
            InputStream is
                = getServletContext().getResourceAsStream("/subscribe.pdf");
            // We create a reader with the InputStream
            PdfReader reader = new PdfReader(is, null);
            // We create an OutputStream for the new PDF
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // Now we create the PDF
            PdfStamper stamper = new PdfStamper(reader, baos);
            // We add a submit button to the existing form
            PushbuttonField button = new PushbuttonField(
                stamper.getWriter(), new Rectangle(90, 660, 140, 690), "submit");
            button.setText("POST");
            button.setBackgroundColor(new GrayColor(0.7f));
            button.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
            PdfFormField submit = button.getField();
            submit.setAction(PdfAction.createSubmitForm("/book/fdf", null, 0));
            stamper.addAnnotation(submit, 1);
            // We add an extra field that can be used to upload a file
            TextField file = new TextField(
                stamper.getWriter(), new Rectangle(160, 660, 470, 690), "image");
            file.setOptions(TextField.FILE_SELECTION);
            file.setBackgroundColor(new GrayColor(0.9f));
            PdfFormField upload = file.getTextField();
            upload.setAdditionalActions(PdfName.U,
                PdfAction.javaScript(
                    "this.getField('image').browseForFileToSubmit();"
                    + "this.getField('submit').setFocus();",
                    stamper.getWriter()));
            stamper.addAnnotation(upload, 1);
            // Close the stamper
            stamper.close();
            reader.close();
            // We write the PDF bytes to the OutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
        } catch (DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
            "inline; filename=\"your.pdf\"");
        try {
            // Create a reader that interprets the request's input stream
            FdfReader fdf = new FdfReader(request.getInputStream());
            // We get a resource from our web app
            InputStream is
                = getServletContext().getResourceAsStream("/subscribe.pdf");
            // We create a reader with the InputStream
            PdfReader reader = new PdfReader(is, null);
            // We create an OutputStream for the new PDF
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // Now we create the PDF
            PdfStamper stamper = new PdfStamper(reader, baos);
            // We alter the fields of the existing PDF
            AcroFields fields = stamper.getAcroFields();
            fields.setFields(fdf);
            stamper.setFormFlattening(true);
            // Gets the image from the FDF file
            try {
                Image img = Image.getInstance(fdf.getAttachedFile("image"));
                img.scaleToFit(100, 100);
                img.setAbsolutePosition(90, 590);
                stamper.getOverContent(1).addImage(img);
            }
            catch(IOException ioe) {
                ColumnText.showTextAligned(stamper.getOverContent(1),
                        Element.ALIGN_LEFT, new Phrase("No image posted!"), 90, 660, 0);
            }
            // close the stamper
            stamper.close();
            reader.close();
            fdf.close();
            // We write the PDF bytes to the OutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
        } catch (DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * Serial Version UID.
     */
    private static final long serialVersionUID = 2157128985625139848L;
 
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PushbuttonField;
import com.itextpdf.text.pdf.XfdfReader;
 
public class XFDFServlet extends HttpServlet {
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/pdf");
        try {
            // We get a resource from our web app
            InputStream is
                = getServletContext().getResourceAsStream("/subscribe.pdf");
            // We create a reader with the InputStream
            PdfReader reader = new PdfReader(is, null);
            // We create an OutputStream for the new PDF
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // Now we create the PDF
            PdfStamper stamper = new PdfStamper(reader, baos);
            // We add a submit button to the existing form
            PushbuttonField button = new PushbuttonField(
                stamper.getWriter(), new Rectangle(90, 660, 140, 690), "submit");
            button.setText("POST");
            button.setBackgroundColor(new GrayColor(0.7f));
            button.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
            PdfFormField submit = button.getField();
            submit.setAction(PdfAction.createSubmitForm(
                "/book/xfdf", null, PdfAction.SUBMIT_XFDF));
            stamper.addAnnotation(submit, 1);
            stamper.close();
            reader.close();
            // We write the PDF bytes to the OutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
        } catch (DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("application/pdf");
        try {
            // Create a reader that interprets the request's input stream
            XfdfReader xfdf = new XfdfReader(request.getInputStream());
            // We get a resource from our web app
            InputStream is
                = getServletContext().getResourceAsStream("/subscribe.pdf");
            // We create a reader with the InputStream
            PdfReader reader = new PdfReader(is, null);
            // We create an OutputStream for the new PDF
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // Now we create the PDF
            PdfStamper stamper = new PdfStamper(reader, baos);
            // We alter the fields of the existing PDF
            AcroFields fields = stamper.getAcroFields();
            fields.setFields(xfdf);
            // close the stamper
            stamper.close();
            reader.close();
            // We write the PDF bytes to the OutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
        } catch (DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 7582490560292953774L;
 
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
import part2.chapter08.Subscribe;
 
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Utilities;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PushbuttonField;
 
public class JSForm {
 
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter09/javascript.pdf";
    /** Path to the resources. */
    public static final String JS1 = "resources/js/post_from_html.js";
    /** Path to the resources. */
    public static final String JS2 = "resources/js/post_to_html.js";
 
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     * @param dest the resulting PDF
     * @throws IOException
     * @throws DocumentException
     */
    public void manipulatePdf(String src, String dest)
        throws IOException, DocumentException {
        // create a reader
        PdfReader reader = new PdfReader(src);
        // create a stamper
        PdfStamper stamper = new PdfStamper(reader,
            new FileOutputStream(dest));
        // Add an open action
        PdfWriter writer = stamper.getWriter();
        PdfAction action =
            PdfAction.javaScript(Utilities.readFileToString(JS1), writer);
        writer.setOpenAction(action);
        // create a submit button that posts data to the HTML page
        PushbuttonField button1 = new PushbuttonField(
            stamper.getWriter(), new Rectangle(90, 660, 160, 690), "post");
        button1.setText("POST TO HTML");
        button1.setBackgroundColor(new GrayColor(0.7f));
        button1.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
        PdfFormField submit1 = button1.getField();
        submit1.setAction(
            PdfAction.javaScript(Utilities.readFileToString(JS2), writer));
        // add the button
        stamper.addAnnotation(submit1, 1);
        // close the stamper
        stamper.close();
        reader.close();
    }
 
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException, DocumentException {
        new Subscribe().createPdf(Subscribe.FORM);
        new JSForm().manipulatePdf(Subscribe.FORM, RESULT);
    }
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.util.EmptyStackException;
import java.util.Stack;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
import com.itextpdf.text.Anchor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.TextElementArray;
import com.itextpdf.text.Font.FontFamily;
 
public class XmlHandler extends DefaultHandler {
 
    /** The Document to which the content is written. */
    protected Document document;
 
    /**
     * This is a <CODE>Stack</CODE> of objects, waiting to be added to the
     * document.
     */
    protected Stack<TextElementArray> stack = new Stack<TextElementArray>();
 
    /** This is the current chunk to which characters can be added. */
    protected Chunk currentChunk = null;
 
    /** Stores the year when it's encountered in the XML. */
    protected String year = null;
    /** Stores the duration when it's encountered in the XML. */
    protected String duration = null;
    /** Stores the imdb ID when it's encountered in the XML. */
    protected String imdb = null;
 
    /**
     * Creates a handler for an iText Document.
     * @param document the document to which content needs to be added.
     */
    public XmlHandler(Document document) {
        this.document = document;
    }
 
    /**
     * @see org.xml.sax.ContentHandler#characters(char[], int, int)
     */
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        String content = new String(ch, start, length);
        if (content.trim().length() == 0)
            return;
        if (currentChunk == null) {
            currentChunk = new Chunk(content.trim());
        }
        else {
            currentChunk.append(" ");
            currentChunk.append(content.trim());
        }
    }
 
    /**
     * @see org.xml.sax.ContentHandler#startElement(java.lang.String,
     *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        try {
            if ("directors".equals(qName) || "countries".equals(qName)) {
                stack.push(new List(List.UNORDERED));
            } else if ("director".equals(qName)
                    || "country".equals(qName)) {
                stack.push(new ListItem());
            }
            else if ("movie".equals(qName)) {
                flushStack();
                Paragraph p = new Paragraph();
                p.setFont(new Font(FontFamily.HELVETICA, 14, Font.BOLD));
                stack.push(p);
                year = attributes.getValue("year");
                duration = attributes.getValue("duration");
                imdb = attributes.getValue("imdb");
            }
            else if ("original".equals(qName)) {
                stack.push(new Paragraph("Original title: "));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * @see org.xml.sax.ContentHandler#endElement(java.lang.String,
     *      java.lang.String, java.lang.String)
     */
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        try {
            updateStack();
            if ("directors".equals(qName)) {
                flushStack();
                Paragraph p = new Paragraph(
                    String.format("Year: %s; duration: %s; ", year, duration));
                Anchor link = new Anchor("link to IMDB");
                link.setReference(
                    String.format("http://www.imdb.com/title/tt%s/", imdb));
                p.add(link);
                stack.push(p);
            }
            else if ("countries".equals(qName) || "title".equals(qName)) {
                flushStack();
            } else if ("original".equals(qName)
                    || "movie".equals(qName)) {
                currentChunk = Chunk.NEWLINE;
                updateStack();
            } else if ("director".equals(qName)
                    || "country".equals(qName)) {
                ListItem listItem = (ListItem) stack.pop();
                List list = (List) stack.pop();
                list.add(listItem);
                stack.push(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * If the currentChunk is not null, it is forwarded to the stack and made
     * null.
     */
    private void updateStack() {
        if (currentChunk != null) {
            TextElementArray current;
            try {
                current = stack.pop();
                if (!(current instanceof Paragraph)
                        || !((Paragraph) current).isEmpty())
                    current.add(new Chunk(" "));
            } catch (EmptyStackException ese) {
                current = new Paragraph();
            }
            current.add(currentChunk);
            stack.push(current);
            currentChunk = null;
        }
    }
 
    /**
     * Flushes the stack, adding all objects in it to the document.
     */
    private void flushStack() {
        try {
            while (stack.size() > 0) {
                Element element = (Element) stack.pop();
                try {
                    TextElementArray previous = (TextElementArray) stack.pop();
                    previous.add(element);
                    stack.push(previous);
                } catch (EmptyStackException es) {
                    document.add(element);
                }
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
 
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.IOException;
import java.io.InputStream;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
 
public class MovieServlet extends HttpServlet {
 
    /**
     * Reads an XML file and serves it as PDF to the browser.
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        try {
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter.getInstance(document, response.getOutputStream());
            // step 3
            document.open();
            // step 4
            InputStream is
                = getServletContext().getResourceAsStream("/movies.xml");
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
            parser.parse(new InputSource(is), new XmlHandler(document));
            // step 5
            document.close();
        } catch (DocumentException e) {
            throw new IOException(e.getMessage());
        } catch (ParserConfigurationException e) {
            throw new IOException(e.getMessage());
        } catch (SAXException e) {
            throw new IOException(e.getMessage());
        }
    }
 
    /**
     * Serial version UID
     */
    private static final long serialVersionUID = -6015985931115167175L;
 
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringReader;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
 
import com.lowagie.database.DatabaseConnection;
import com.lowagie.database.HsqldbConnection;
import com.lowagie.filmfestival.Country;
import com.lowagie.filmfestival.Director;
import com.lowagie.filmfestival.Movie;
import com.lowagie.filmfestival.PojoFactory;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.PdfWriter;
 
public class HtmlMovies1 {
 
    /** The resulting HTML file. */
    public static final String HTML = "results/part3/chapter09/movies_1.html";
    /** The resulting PDF file. */
    public static final String PDF = "results/part3/chapter09/html_movies_1.pdf";
 
    /** The StyleSheet. */
    protected StyleSheet styles = null;
    /** Extra properties. */
    protected HashMap<String,Object> providers = null;
 
    /**
     * Main method.
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException 
     * @throws SQLException
     */
    public static void main(String[] args)
        throws IOException, DocumentException, SQLException {
        new HtmlMovies1().createHtmlAndPdf(HTML, PDF);
    }
 
    /**
     * Creates a list with movies in HTML and PDF simultaneously.
     * @param html a path to the resulting HTML file
     * @param pdf a path to the resulting PDF file
     * @throws SQLException
     * @throws IOException
     * @throws DocumentException
     */
    public void createHtmlAndPdf(String html, String pdf)
        throws SQLException, IOException, DocumentException {
        // Create a database connection
        DatabaseConnection connection = new HsqldbConnection("filmfestival");
        // Create a stream to produce HTML
        PrintStream out = new PrintStream(new FileOutputStream(html));
        out.println("<html>\n<body>");
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(pdf));
        // step 3
        document.open();
        // step 4
        List<Movie> movies = PojoFactory.getMovies(connection);
        String snippet;
        for (Movie movie : movies) {
            // create the snippet
            snippet = createHtmlSnippet(movie);
            // use the snippet for the HTML page
            out.println(snippet);
            // use the snippet for the PDF document
            List<Element> objects
                = HTMLWorker.parseToList(
                    new StringReader(snippet), styles, providers);
            for (Element element : objects)
                document.add(element);
        }
        // step 5
        document.close();
        // flush and close the HTML stream
        out.print("</body>\n</html>");
        out.flush();
        out.close();
        // close the database connection
        connection.close();
    }
 
    /**
     * Sets the styles for the HTML to PDF conversion
     * @param styles a StyleSheet object
     */
    public void setStyles(StyleSheet styles) {
        this.styles = styles;
    }
 
    /**
     * Set some extra properties.
     * @param providers the properties map
     */
    public void setProviders(HashMap<String, Object> providers) {
        this.providers = providers;
    }
 
    /**
     * Creates an HTML snippet with info about a movie.
     * @param movie the movie for which we want to create HTML
     * @return a String with HTML code
     */
    public String createHtmlSnippet(Movie movie) {
        StringBuffer buf = new StringBuffer("\t<span class=\"title\">");
        buf.append(movie.getMovieTitle());
        buf.append("</span><br />\n");
        buf.append("\t<ul>\n");
        for (Country country : movie.getCountries()) {
            buf.append("\t\t<li class=\"country\">");
            buf.append(country.getCountry());
            buf.append("</li>\n");
        }
        buf.append("\t</ul>\n");
        buf.append("\tYear: <i>");
        buf.append(movie.getYear());
        buf.append(" minutes</i><br />\n");
        buf.append("\tDuration: <i>");
        buf.append(movie.getDuration());
        buf.append(" minutes</i><br />\n");
        buf.append("\t<ul>\n");
        for (Director director : movie.getDirectors()) {
            buf.append("\t\t<li><span class=\"director\">");
            buf.append(director.getName());
            buf.append(", ");
            buf.append(director.getGivenName());
            buf.append("</span></li>\n");
        }
        buf.append("\t</ul>\n");
        return buf.toString();
    }
}
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part3.chapter09;
 
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import com.lowagie.filmfestival.Movie;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocListener;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.Image;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.html.simpleparser.ChainedProperties;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.ImageProvider;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.PdfWriter;
 
public class HtmlMovies2 extends HtmlMovies1 {
 
    /**
     * Inner class implementing the ImageProvider class.
     * This is needed if you want to resolve the paths to images.
     */
    public static class MyImageFactory implements ImageProvider {
        public Image getImage(String src, Map<String, String> h,
                ChainedProperties cprops, DocListener doc) {
            try {
                return Image.getInstance(
                    String.format("resources/posters/%s",
                        src.substring(src.lastIndexOf("/") + 1)));
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }    
    }
 
    /**
     * Inner class implementing the FontProvider class.
     * This is needed if you want to select the correct fonts.
     */
    public static class MyFontFactory implements FontProvider {
        public Font getFont(String fontname,
                String encoding, boolean embedded, float size,
                int style, BaseColor color) {
            return new Font(FontFamily.TIMES_ROMAN, size, style, color);
        }
 
        public boolean isRegistered(String fontname) {
            return false;
        }
    }
 
    /** The resulting HTML file. */
    public static final String HTML
        = "results/part3/chapter09/movies_2.html";
    /** The resulting PDF file. */
    public static final String RESULT1
        = "results/part3/chapter09/html_movies_2.pdf";
    /** Another resulting PDF file. */
    public static final String RESULT2
        = "results/part3/chapter09/html_movies_3.pdf";
 
    /**
     * Main method.
     * 
     * @param args no arguments needed
     * @throws IOException
     * @throws DocumentException
     * @throws SQLException
     */
    public static void main(String[] args)
        throws IOException, DocumentException, SQLException {
        HtmlMovies2 movies = new HtmlMovies2();
        // create a StyleSheet
        StyleSheet styles = new StyleSheet();
        styles.loadTagStyle("ul", "indent", "10");
        styles.loadTagStyle("li", "leading", "14");
        styles.loadStyle("country", "i", "");
        styles.loadStyle("country", "color", "#008080");
        styles.loadStyle("director", "b", "");
        styles.loadStyle("director", "color", "midnightblue");
        movies.setStyles(styles);
        // create extra properties
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put(HTMLWorker.FONT_PROVIDER, new MyFontFactory());
        map.put(HTMLWorker.IMG_PROVIDER, new MyImageFactory());
        movies.setProviders(map);
        // creates HTML and PDF (reusing a method from the super class)
        movies.createHtmlAndPdf(HTML, RESULT1);
        // creates another PDF file
        movies.createPdf(RESULT2);
    }
 
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename)
        throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(RESULT2));
        // step 3
        document.open();
        // step 4
        List<Element> objects
            = HTMLWorker.parseToList(new FileReader(HTML), null, providers);
        for (Element element : objects) {
            document.add(element);
        }
        // step 5
        document.close();
    }
 
    /**
     * Creates an HTML snippet with info about a movie.
     * @param movie the movie for which we want to create HTML
     * @return a String with HTML code
     */
    public String createHtmlSnippet(Movie movie) {
        StringBuffer buf = new StringBuffer("<table width=\"500\">\n<tr>\n");
        buf.append("\t<td><img src=\"../../../resources/posters/");
        buf.append(movie.getImdb());
        buf.append(".jpg\" /></td>\t<td>\n");
        buf.append(super.createHtmlSnippet(movie));
        buf.append("\t</td>\n</tr>\n</table>");
        return buf.toString();
    }
 
}
File nameRaw URLUpdated
Hello.javaHello.java2015-10-10 3:04 pm
PdfServlet.javaPdfServlet.java2015-10-10 3:04 pm
SubmitForm.javaSubmitForm.java2015-10-10 3:04 pm
ShowData.javaShowData.java2015-10-10 3:04 pm
FormServlet.javaFormServlet.java2015-10-10 3:04 pm
CreateFDF.javaCreateFDF.java2015-10-10 3:04 pm
FDFServlet.javaFDFServlet.java2015-10-10 3:04 pm
XFDFServlet.javaXFDFServlet.java2015-10-10 3:04 pm
JSForm.javaJSForm.java2015-10-10 3:04 pm
XmlHandler.javaXmlHandler.java2015-10-10 3:04 pm
MovieServlet.javaMovieServlet.java2015-10-10 3:04 pm
HtmlMovies1.javaHtmlMovies1.java2015-10-10 3:04 pm
HtmlMovies2.javaHtmlMovies2.java2015-10-10 3:04 pm
C# port: 
File nameRaw URLUpdated
Hello.csHello.cs2015-10-10 3:05 pm
PdfServlet.csPdfServlet.cs2015-10-10 3:05 pm
SubmitForm.csSubmitForm.cs2015-10-10 3:05 pm
ShowData.csShowData.cs2015-10-10 3:05 pm
FormServlet.csFormServlet.cs2015-10-10 3:05 pm
CreateFDF.csCreateFDF.cs2015-10-10 3:05 pm
FDFServlet.csFDFServlet.cs2015-10-10 3:05 pm
XFDFServlet.csXFDFServlet.cs2015-10-10 3:05 pm
JSForm.csJSForm.cs2015-10-10 3:05 pm
XmlHandler.csXmlHandler.cs2015-10-10 3:05 pm
MovieServlet.csMovieServlet.cs2015-10-10 3:05 pm
HtmlMovies1.csHtmlMovies1.cs2015-10-10 3:05 pm
HtmlMovies2.csHtmlMovies2.cs2015-10-10 3:05 pm