Example usage for com.lowagie.text.pdf XfaForm XfaForm

List of usage examples for com.lowagie.text.pdf XfaForm XfaForm

Introduction

In this page you can find the example usage for com.lowagie.text.pdf XfaForm XfaForm.

Prototype

public XfaForm(PdfReader reader) throws IOException, ParserConfigurationException, SAXException 

Source Link

Document

A constructor from a PdfReader.

Usage

From source file:com.servoy.extensions.plugins.pdf_forms.servlets.PDFServlet.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String hostname = request.getServerName();
    int port = request.getServerPort();
    String base = request.getScheme() + "://" + hostname;
    // fix for bad pdf behavior, if we add default port it will not work!!!!!
    if (port != 80 && port != 443)
        base += ":" + port;
    String uri = request.getRequestURI();//with servlet name
    String path = request.getPathInfo(); //without servlet name

    Connection conn = null;/*from  w ww .  j  a v  a  2  s.  co  m*/
    ServletOutputStream out = null;
    try {
        // Determine target page.
        if (path == null) {
            response.sendRedirect(request.getRequestURI() + "/");
            return;
        } else if ("/".equals(path)) {
            response.sendError(404);
            return;
        } else if (path.startsWith("/pdf_forms/pdf_form")) {
            addHeaders(response);

            String s_action_id = request.getParameter("action_id");
            int action_id = Utils.getAsInteger(s_action_id);
            conn = app.getDBServerConnection(PDF_SERVER, null);
            if (conn == null)
                Debug.error("Could not find Server " + PDF_SERVER);
            if (action_id > 0 && conn != null) {

                Statement st = conn.createStatement();
                ResultSet rs = st.executeQuery(
                        "select form_id,template_id,action_type,closed from pdf_actions where action_id = "
                                + action_id);
                if (rs.next()) {
                    int form_id = rs.getInt(1);
                    int template_id = rs.getInt(2);
                    int action_type = rs.getInt(3);
                    int closed = rs.getInt(4);

                    if (closed == 0) {
                        Map<String, String> values = new HashMap<String, String>();
                        byte[] pdfContent = null;
                        Statement stContent = conn.createStatement();
                        ResultSet rsContent = stContent.executeQuery(
                                "select actual_pdf_form from pdf_templates where template_id = " + template_id);
                        if (rsContent.next()) {
                            pdfContent = rsContent.getBytes(1);
                        }
                        PdfReader reader = new PdfReader(pdfContent);
                        XfaForm xfa = new XfaForm(reader);
                        FDFDoc outputFDF = null;
                        if (!xfa.isXfaPresent()) {
                            outputFDF = new FDFDoc();
                        }

                        String sub = uri.substring(0, uri.length() - path.length());
                        String url = base + sub + "/pdf_forms/pdf_process_data";

                        if (action_type == EDIT || !xfa.isXfaPresent()) {
                            values.put(ACTION_PROPERTY, Integer.toString(action_id));
                            Debug.trace("Using " + URL_PROPERTY + ": " + url);
                            values.put(URL_PROPERTY, url);
                        }
                        //fill
                        Statement st1 = conn.createStatement();
                        ResultSet rs1 = st1.executeQuery(
                                "select value_name,field_value from pdf_form_values where form_id = "
                                        + form_id);
                        while (rs1.next()) {
                            String name = rs1.getString(1);
                            String val = rs1.getString(2);
                            if (val != null)
                                values.put(name, val);
                        }
                        rs1.close();
                        st1.close();

                        //get name
                        String filename = "fromdb";
                        boolean skipButton = false;
                        Statement st2 = conn.createStatement();
                        ResultSet rs2 = st2.executeQuery(
                                "select filename,skip_placing_submit_button from pdf_templates where template_id = "
                                        + template_id);
                        if (rs2.next()) {
                            filename = rs2.getString(1);
                            skipButton = rs2.getBoolean(2);
                        }
                        rs2.close();
                        st2.close();

                        String templateLocation = request.getParameter("overrideTemplateLocation");
                        ;
                        if (templateLocation == null) {
                            if (genericTemplateLocation == null) {
                                templateLocation = base + sub + "/pdf_forms/pdf_template/" + filename
                                        + "?template_id=" + template_id + "&rnd=" + rnd.nextInt();
                            } else {
                                templateLocation = genericTemplateLocation + filename;
                            }
                        }
                        if (outputFDF != null) {
                            outputFDF.SetFile(templateLocation);

                            StringBuffer sb = new StringBuffer();
                            if (action_type == EDIT) {
                                if (!skipButton) {
                                    sb.append("var inch = 72;\n");
                                    sb.append("var aRect = this.getPageBox( {nPage: 0} );\n");
                                    sb.append("aRect[0] = 1;\n");//.5*inch; // position rectangle (.5 inch, .5 inch) 
                                    sb.append("aRect[2] = aRect[0]+.5*inch;\n"); // from upper left hand corner of page. 
                                    sb.append("aRect[1] -= 1;//.5*inch;\n"); // Make it .5 inch wide 
                                    sb.append("aRect[3] = aRect[1] - 24;\n");// and 24 points high 
                                    //                     sb.append("var aRect2 = this.getPageBox( {nPage: 0} );\n");
                                    //                     sb.append("aRect2[0] = .5*inch; // position rectangle (.5 inch, .5 inch)\n");
                                    //                     sb.append("aRect2[2] = aRect2[0]+.5*inch; // from upper left hand corner of page.\n");
                                    //                     sb.append("aRect2[1] -= .5*inch; // Make it .5 inch wide\n");
                                    //                     sb.append("aRect2[3] = aRect2[1] - 24; // and 24 points high\n");
                                    sb.append("var f = this.addField('servoySubmit', 'button', 0, aRect )\n");
                                    sb.append("f.setAction('MouseUp', 'this.submitForm(\"" + url + "?action_id="
                                            + action_id + "\")');\n");
                                    sb.append("f.display = display.noPrint;\n");
                                    sb.append("f.borderStyle = border.b;\n");
                                    sb.append("f.highlight = 'push';\n");
                                    sb.append("f.textSize = 0; // auto sized\n");
                                    sb.append("f.textColor = color.blue;\n");
                                    sb.append("f.fillColor = color.green;//ltGray;\n");
                                    sb.append("f.print = false;\n");
                                    // sb.append("f.textFont = font.ZapfD\n");
                                    sb.append("f.buttonSetCaption('Submit')\n");
                                    sb.append("f.delay = false;\n");
                                    //                     sb.append("var h = this.addField('pdmSubmitAction', 'text', 0, aRect2 )\n");
                                    //                     sb.append("h.visible = display.hidden;\n");
                                    //                     sb.append("h.defaultValue = '"+action_id+"';\n");
                                    //                     sb.append("h.readonly = true;\n");
                                }
                            } else {
                                sb.append("for (var i = 0; i < this.numFields; i++)\n");
                                sb.append("{\n");
                                sb.append("    var fname = this.getNthFieldName(i);\n");
                                sb.append("    if (fname != 'pdmSubmitAction')\n");
                                sb.append("    {\n");
                                sb.append("        var ef = this.getField(fname);\n");
                                sb.append("        ef.readonly = true;\n");
                                sb.append("    }\n");
                                sb.append("}\n");
                            }

                            if (sb.length() != 0)
                                outputFDF.SetOnImportJavaScript(sb.toString(), false);

                            Iterator<String> it = values.keySet().iterator();
                            while (it.hasNext()) {
                                String name = it.next();
                                outputFDF.SetValue(name, values.get(name));
                            }
                        }
                        out = response.getOutputStream();
                        if (outputFDF != null) {
                            response.setContentType("application/vnd.fdf");
                            outputFDF.Save(out);
                        } else {
                            response.setContentType("application/vnd.adobe.xdp+xml");
                            StringBuffer buffer = new StringBuffer();
                            buffer.append("<?xml version='1.0' encoding='UTF-8'?>\n");
                            buffer.append("<?xfa generator='AdobeDesigner_V7.0' APIVersion='2.2.4333.0'?>\n");
                            buffer.append("<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\">\n");
                            buffer.append(
                                    "<xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\">\n");
                            buffer.append("<xfa:data>\n");
                            buffer.append("<form>\n");
                            Iterator<String> it = values.keySet().iterator();
                            while (it.hasNext()) {
                                String name = it.next();
                                buffer.append("<" + name + ">" + values.get(name) + "</" + name + ">\n");
                            }
                            buffer.append("</form>\n");
                            buffer.append("</xfa:data>\n");
                            buffer.append("</xfa:datasets>\n");
                            buffer.append("<pdf href=\"" + templateLocation.replace("&", "&amp;")
                                    + "\" xmlns=\"http://ns.adobe.com/xdp/pdf/\">\n");
                            buffer.append("</pdf>\n");
                            buffer.append("</xdp:xdp>");
                            out.print(buffer.toString());
                        }
                    } else {
                        String msg = "<html><head><title></title></head><body>Security violation, use the pdf system to edit pdfs</body></html>";
                        response.setContentType("text/html");
                        Writer wr = response.getWriter();
                        wr.write(msg);
                        wr.close();
                    }
                }
                rs.close();
                st.close();
            }
        } else if (path.startsWith("/pdf_forms/pdf_template")) {
            addHeaders(response);

            String s_template_id = request.getParameter("template_id");
            int template_id = Utils.getAsInteger(s_template_id);
            if (template_id > 0) {
                conn = app.getDBServerConnection(PDF_SERVER, null);
                if (conn == null)
                    Debug.error("Could not find Server " + PDF_SERVER);
                if (conn != null) {
                    Statement st = conn.createStatement();
                    ResultSet rs = st.executeQuery(
                            "select actual_pdf_form from pdf_templates where template_id = " + template_id);
                    if (rs.next()) {
                        response.setContentType("application/pdf");
                        byte[] array = rs.getBytes(1);
                        if (array != null) {
                            response.setContentLength(array.length);
                            out = response.getOutputStream();
                            out.write(array);
                        } else {
                            //missing??
                            response.sendError(404);
                        }
                    }
                    rs.close();
                    st.close();
                }
                return;
            }
            response.sendError(404);
            return;
        } else {
            response.sendError(404);
            return;
        }
    } catch (Exception e) {
        Debug.error(e);
    } finally {
        if (conn != null)
            Utils.closeConnection(conn);
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:questions.forms.FillDynamicXfa2.java

public static void main(String[] args) {
    try {/*from  w ww .java 2s  .  co m*/
        // getting new data from a "datasets" XML snippet
        File file = new File(RESOURCE_DATA);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document newdoc = db.parse(file);
        Element element = newdoc.getDocumentElement();
        NodeList nodelist = element.getElementsByTagNameNS("http://www.xfa.org/schema/xfa-data/1.0/", "data");
        Node newdata = nodelist.item(0);

        // replacing the XFA in an existing document
        PdfReader reader = new PdfReader(RESOURCE_PDF);
        XfaForm xfa = new XfaForm(reader);
        Document doc = xfa.getDomDocument();
        NodeList list = doc.getElementsByTagNameNS("http://www.xfa.org/schema/xfa-data/1.0/", "datasets");
        list.item(0).replaceChild(doc.importNode(newdata, true), list.item(0).getFirstChild());
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        xfa.setDomDocument(doc);
        xfa.setChanged(true);
        XfaForm.setXfa(xfa, stamper.getReader(), stamper.getWriter());
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:questions.forms.ReadXfa2.java

public static void main(String[] args) {
    try {/*from  www. ja  va  2  s  . c  o m*/
        PdfReader reader = new PdfReader(RESOURCE);
        FileOutputStream os = new FileOutputStream(RESULT);
        XfaForm xfa = new XfaForm(reader);
        Document doc = xfa.getDomDocument();
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.transform(new DOMSource(doc), new StreamResult(os));
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}