FormFill.java

package org.faceless.web;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.faceless.pdf2.*;

/**
 * An example which fills out a W8 tax form from a servlet.
 */
public class FormFillServlet extends HttpServlet {

    private PDF template;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ServletContext context = config.getServletContext();
        InputStream in = context.getResourceAsStream("/products/pdf/examples/fw8eci.pdf");
        try {
            template = new PDF(new PDFReader(in));
            in.close();
        } catch (IOException e) {
            throw new ServletException(e.getMessage());
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PDF pdf = new PDF(template);
        Form form = pdf.getForm();

        /*
         * Fill out the form values from the request.
         */
        ((FormText)form.getElement("f1-1")).setValue(request.getParameter("name"));
        ((FormText)form.getElement("f1-2")).setValue(request.getParameter("country"));
        form.flatten();

        /* 
         * Due to a problem with Internet Explorer we need to set the
         * Content-Length of the response, so we write to a temporary buffer
         * first.
         */
        ByteArrayOutputStream temp = new ByteArrayOutputStream();
        pdf.render(temp);
        temp.close();

        /*
         * Now return the PDF to the browser
         */
        response.setContentType("application/pdf");
        response.setContentLength(temp.size());
        temp.writeTo(response.getOutputStream());
    }

}