Example usage for com.itextpdf.text.pdf AcroFields getFields

List of usage examples for com.itextpdf.text.pdf AcroFields getFields

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf AcroFields getFields.

Prototype

public Map<String, Item> getFields() 

Source Link

Document

Gets all the fields.

Usage

From source file:com.mycompany.mavenproject1.SubmitForm.java

public void extractFromPdf(String src, String dest) throws DocumentException, IOException {

    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));

    PushbuttonField button = new PushbuttonField(stamper.getWriter(), new Rectangle(36, 700, 112, 730), "get");

    //stamper.getWriter().addJavaScript(Utilities.readFileToString(RESOURCE));
    button.setText("SAVE My INFO");
    button.setBackgroundColor(new GrayColor(0.7f));
    button.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField submit = button.getField();

    /*/*from  ww w. j  av a 2s  .  c o m*/
          button.setBackgroundColor(new GrayColor(0.7f));
          button.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
     */

    //PdfFormField pull_data = upload_info.getField();
    //  pull_data.setAction(PdfAction.javaScript(Utilities.readFileToString(submit_button_script), stamper.getWriter()));
    stamper.getWriter().addJavaScript(Utilities.readFileToString(checkbox));
    stamper.getWriter().addJavaScript(Utilities.readFileToString(upload_info));
    //PushbuttonField submitButton=stamper.getAcroFields().getNewPushbuttonFromField("UseSavedInfo");
    //PdfFormField field=submitButton.getField();
    //field.setAction(PdfAction.javaScript("app.alert('hello')" ,stamper.getWriter()));
    /*
     PushbuttonField useMySavedInfo = new PushbuttonField(
      stamper.getWriter(), new Rectangle(36, 1000, 559, 806), "MySavedInfo" );
      useMySavedInfo.setText("Upload info");
      useMySavedInfo.setBackgroundColor(new GrayColor(0.7f));
      useMySavedInfo.setVisibility(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
       PdfFormField  extractInfo=useMySavedInfo.getField();
    */
    //  extractInfo.setAction(PdfAction.javaScript("alert('hello')", stamper.getWriter()));
    //  extractInfo.setAction(PdfAction.);
    //stamper.

    /*
    AcroFields fields = stamper.getAcroFields();
     PushbuttonField submitButton=fields.getNewPushbuttonFromField("SubmitForm");
    */
    //System.out.println(submitButton.getAppearance().getHeight());
    //System.out.println(submitButton.getAppearance().getWidth());
    //System.out.println(submitButton.getAppearance());
    //submitButton
    //submitButton.getField().get
    //submitButton.getWriter().setAdditionalAction(, PdfAction.javaScript("app.alert('os')",stamper.getWriter()));
    //submitButton.getWriter().setAdditionalAction(PdfName., action);
    //PdfFormField sb=submitButton.getField();
    //sb.setAction(PdfAction.javaScript("app.alert('test')", stamper.getWriter()));

    // sumbitInfo.setAction(PdfAction.javaScript("app.alert('test')", stamper.getWriter()));
    //submit.setAction(PdfAction.javaScript("app.alert('test')", stamper.getWriter()));

    //PushbuttonField useInfo = fields.getNewPushbuttonFromField("UseSavedInfo");
    //PdfAnnotation getInfo=useInfo.getField();
    //getInfo.setAction(PdfAction.javaScript("app.alert('action!')", stamper.getWriter()));

    // ffield.SetAdditionalActions(PdfName.E, PdfAction("app.alert('action!')"));

    AcroFields fields = stamper.getAcroFields();

    // PushbuttonField saveInfo = fields.getNewPushbuttonFromField("SaveInfo");
    //   PdfFormField fd=saveInfo.getField();
    //fd.setAction(PdfAction.createSubmitForm("http://127.0.0.1/index.php",null,PdfAction.SUBMIT_HTML_FORMAT));
    //PdfAppearance pa =saveInfo.getAppearance();
    // pa.setAction(PdfAction.createSubmitForm("http://127.0.0.1/index.php",null,PdfAction.SUBMIT_HTML_FORMAT), 0, 0, 0, 0);
    Set<String> fldNames = fields.getFields().keySet();

    //AcroFields fields = stamper.getAcroFields();
    for (String fldName : fldNames) {
        System.out.println(fldName + ": " + fields.getField(fldName));
    }
    //submit.setAdditionalAction(PdfAction.javaScript(Utilities.readFileToString(submit_button_script), stamper.getWriter()));
    //http://www.mycrewid.com/Alexander/index.php
    //submit.setAction(PdfAction.createSubmitForm(
    //       "http://127.0.0.1/index.php", null,
    //     PdfAction.SUBMIT_HTML_FORMAT));
    submit.setAction(
            PdfAction.javaScript(Utilities.readFileToString(submit_button_script), stamper.getWriter()));
    stamper.addAnnotation(submit, 1);
    stamper.close();
    //PdfAction.javaScript("this.getField('FirstName').value=util.printd(\"dd mmmm yyyy\",new Date())",stamper.getWriter());

    //stamper.addAnnotation(submitButton, 1);
    //stamper.addAnnotation(sb,1);
    // submit.setAdditionalActions(PdfName.E, PdfAction.javaScript(Utilities.readFileToString(submit_button_script),stamper.getWriter()));

}

From source file:com.pdfExtract.pdfExtract.java

public void scanFields(String sourceFile, String destinationFile, int index) throws IOException {

    // le fichier existe dj ?
    File f = new File(destinationFile);
    if (f.exists() && !f.isDirectory()) {
        JOptionPane optionPane = new JOptionPane("Le fichier existe dj.\nRemplacer le fichier ?\n",
                JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
    }/*from   w w w . j  a v a2 s  . co  m*/

    PdfReader pdfReader;
    pdfReader = new PdfReader(sourceFile);
    AcroFields acroFields = pdfReader.getAcroFields();

    // Create a reader to extract info
    PrintWriter writer = new PrintWriter(new FileOutputStream(destinationFile, true));

    // Create a reader to extract info
    PdfReader reader = new PdfReader(sourceFile);
    // Get the fields from the reader (read-only!!!)
    AcroFields form = reader.getAcroFields();

    Set<String> fields = form.getFields().keySet();

    // affichage entete (nom des champs)
    if (index == 0) {
        for (String key : fields) {
            writer.append(key + ";");
        }
        writer.append("\n");
    }

    // affichage valeur des champs
    for (String key : fields) {
        String t;
        t = form.getField(key);
        writer.append(form.getField(key));
        writer.append(";");
    }

    writer.append("\n");
    writer.close();

}

From source file:com.wabacus.system.assistant.PdfAssistant.java

License:Open Source License

private ByteArrayOutputStream showReportOneRowDataOnPdf(ReportRequest rrequest,
        Map<String, AbsReportType> mReportTypeObjs, IComponentConfigBean ccbean, PDFExportBean pdfbean,
        int rowidx) throws Exception {
    PdfReader pdfTplReader = null;/*from  w  ww.j a va2 s  . co m*/
    InputStream istream = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        istream = WabacusAssistant.getInstance().readFile(pdfbean.getPdftemplate());
        if (istream == null)
            return null;
        pdfTplReader = new PdfReader(new BufferedInputStream(istream));
        PdfStamper stamp = new PdfStamper(pdfTplReader, baos);
        /* ?? */
        AcroFields form = stamp.getAcroFields();
        form.addSubstitutionFont(bfChinese);
        boolean flag = true;
        if (pdfbean != null && pdfbean.getInterceptorObj() != null) {
            flag = pdfbean.getInterceptorObj().beforeDisplayPdfPageWithTemplate(ccbean, mReportTypeObjs, rowidx,
                    stamp);
        }
        if (flag) {
            Map<String, Item> mFields = form.getFields();
            if (mFields != null) {
                String fieldValueTmp = null;
                for (String fieldNameTmp : mFields.keySet()) {
                    fieldValueTmp = getPdfFieldValueByName(rrequest, mReportTypeObjs, ccbean, fieldNameTmp,
                            rowidx);//?
                    if (pdfbean != null && pdfbean.getInterceptorObj() != null) {
                        fieldValueTmp = pdfbean.getInterceptorObj().beforeDisplayFieldWithTemplate(ccbean,
                                mReportTypeObjs, rowidx, stamp, fieldNameTmp, fieldValueTmp);
                    }
                    if (fieldValueTmp != null)
                        form.setField(fieldNameTmp, fieldValueTmp);
                }
            }
        }
        if (pdfbean != null && pdfbean.getInterceptorObj() != null) {
            pdfbean.getInterceptorObj().afterDisplayPdfPageWithTemplate(ccbean, mReportTypeObjs, rowidx, stamp);
        }
        stamp.setFormFlattening(true);
        stamp.close();
    } finally {
        try {
            if (istream != null)
                istream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (pdfTplReader != null)
            pdfTplReader.close();
    }
    return baos;
}

From source file:Logica.LogicaReserva.java

private void GenerarDocumento(Reserva nuevaReserva) throws IOException, DocumentException {
    //String dirPath = "C:\\";
    String fileName = "Base reserva.pdf";
    HashMap fieldsWithValues = new HashMap();
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfReader reader = new PdfReader(fileName);
    PdfStamper stamper = new PdfStamper(reader, baosPDF);
    AcroFields form = stamper.getAcroFields();
    HashMap fields = (HashMap) form.getFields();
    Set keys = fields.keySet();/*from   ww w .  ja v  a 2  s . c  om*/

    //Metodo que retorna map de datos que queremos obtener de objeto para agregar a PDF    
    fieldsWithValues = crearHashMapReserva(nuevaReserva, keys);

    //Iteracion sobre campos de pdf
    Iterator itr = keys.iterator();
    while (itr.hasNext()) {
        String fieldName = (String) itr.next();
        String fieldValue = fieldsWithValues.get(fieldName) != null ? (String) (fieldsWithValues.get(fieldName))
                : "";
        form.setField(fieldName, fieldValue);
        form.setFieldProperty(fieldName, "setfflags", PdfFormField.FF_READ_ONLY, null);

    }
    stamper.setFormFlattening(true);
    stamper.close();
    reader.close();

    //Guardando cambios
    String nombre;
    DateFormat fecha = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss");
    nombre = fecha.format(nuevaReserva.getFechaHasta());
    String nombreydir = "Documentos\\Documento Reserva -" + nombre + "-.pdf";
    OutputStream pdf = new FileOutputStream(nombreydir);
    baosPDF.writeTo(pdf);
    pdf.close();

    Hilo h1 = new Hilo("email", nombreydir, nuevaReserva.getCliente().getCorreo());
    h1.start();

    try {
        File archivo = new File(nombreydir);
        Desktop.getDesktop().open(archivo);
    } catch (IOException ex) {
    }
    //EnvioEmail(nombreydir, nuevaReserva.getCliente().getCorreo());
}

From source file:my.charpdf.DandDcharPDFUI.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    String inputFile;/*from   w  w  w .  jav a 2s  . c  o m*/
    inputFile = jTextField1.getText().replace("\n", "").replace("\r", "");
    String pcName = "";
    String pcRace = "";
    String pcAlign = "";
    String pcBackG = "";
    String pcExp = "";
    String pcProfBonus = "";
    String pcStrScore = "";
    String pcStrMod = "";
    String pcDexScore = "";
    String pcDexMod = "";
    String pcConScore = "";
    String pcConMod = "";
    String pcIntScore = "";
    String pcIntMod = "";
    String pcWisScore = "";
    String pcWisMod = "";
    String pcChaScore = "";
    String pcChaMod = "";
    String pcClassLevel = "";
    String pcPerc = "";
    if (!inputFile.equals("")) {
        try {
            Builder parser = new Builder();
            Document doc = parser.build("file:///" + inputFile);

            Element root = doc.getRootElement();
            Elements character = root.getChildElements();

            pcName = character.get(0).getFirstChildElement("name").getValue();
            pcRace = character.get(0).getFirstChildElement("race").getValue();
            pcExp = character.get(0).getFirstChildElement("exp").getValue();
            pcAlign = character.get(0).getFirstChildElement("alignment").getValue();
            pcBackG = character.get(0).getFirstChildElement("background").getValue();
            pcProfBonus = character.get(0).getFirstChildElement("profbonus").getValue();
            pcPerc = character.get(0).getFirstChildElement("perception").getValue();

            //Integer numChildren = character.get(0).getChildCount();
            //System.out.println(numChildren);

            Elements pcAttrs = character.get(0).getChildElements("abilities").get(0).getChildElements();
            Elements pcClasses = character.get(0).getChildElements("classes").get(0).getChildElements();

            for (int i = 0; i < pcAttrs.size(); i++) {
                if (pcAttrs.get(i).getLocalName().equals("strength")) {
                    pcStrScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcStrMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("dexterity")) {
                    pcDexScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcDexMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("constitution")) {
                    pcConScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcConMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("intelligence")) {
                    pcIntScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcIntMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("wisdom")) {
                    pcWisScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcWisMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("charisma")) {
                    pcChaScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcChaMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                }
            }

            for (int i = 0; i < pcClasses.size(); i++) {
                // Gets the list of classes
                //System.out.println(pcClasses.get(i).getLocalName());
                String tempClass = pcClasses.get(i).getChildElements("name").get(0).getValue();
                String tempLevel = pcClasses.get(i).getChildElements("level").get(0).getValue();
                pcClassLevel += tempClass + " " + tempLevel + " / ";
            }
            pcClassLevel = pcClassLevel.substring(0, pcClassLevel.length() - 2);

            //for(i = 0; i < numClasses; i++) {
            //    System.out.println(charac);
            //}

            String inputTemplate = "resources/DandD5e-template.pdf";

            String outputPDF = "resources/" + pcName + ".pdf";

            PdfReader reader = new PdfReader(inputTemplate);
            PdfStamper stamper;
            stamper = new PdfStamper(reader, new FileOutputStream(outputPDF));
            AcroFields form = reader.getAcroFields();

            Set<String> fields = form.getFields().keySet();

            for (String key : fields) {
                //System.out.println(key);
                switch (form.getFieldType(key)) {
                case AcroFields.FIELD_TYPE_CHECKBOX:
                    //System.out.println(key + ": Checkbox");
                    break;
                case AcroFields.FIELD_TYPE_COMBO:
                    //System.out.println(key + ": Combo");
                    break;
                case AcroFields.FIELD_TYPE_LIST:
                    //System.out.println(key + ": List");
                    break;
                case AcroFields.FIELD_TYPE_NONE:
                    //System.out.println(key + ": None");
                    break;
                case AcroFields.FIELD_TYPE_PUSHBUTTON:
                    //System.out.println(key + ": Pushbutton");
                    break;
                case AcroFields.FIELD_TYPE_RADIOBUTTON:
                    //System.out.println(key + ": Radio");
                    break;
                case AcroFields.FIELD_TYPE_SIGNATURE:
                    //System.out.println(key + ": Signature");
                    break;
                case AcroFields.FIELD_TYPE_TEXT:
                    //System.out.println(key + ": Text");
                    break;
                default:
                    //System.out.println(key + ": ???");
                }
            }
            stamper.getAcroFields().setField("Race ", pcRace);
            stamper.getAcroFields().setField("CharacterName", pcName);
            stamper.getAcroFields().setField("XP", pcExp);
            stamper.getAcroFields().setField("Alignment", pcAlign);
            stamper.getAcroFields().setField("Background", pcBackG);
            int tempPB = Integer.parseInt(pcProfBonus);
            if (tempPB > 0) {
                pcProfBonus = "+" + pcProfBonus;
            }
            stamper.getAcroFields().setField("ProfBonus", pcProfBonus);

            //Attributes
            stamper.getAcroFields().setField("STR", pcStrScore);
            stamper.getAcroFields().setField("STRmod", pcStrMod);
            stamper.getAcroFields().setField("DEX", pcDexScore);
            stamper.getAcroFields().setField("DEXmod ", pcDexMod);
            stamper.getAcroFields().setField("CON", pcConScore);
            stamper.getAcroFields().setField("CONmod", pcConMod);
            stamper.getAcroFields().setField("INT", pcIntScore);
            stamper.getAcroFields().setField("INTmod", pcIntMod);
            stamper.getAcroFields().setField("WIS", pcWisScore);
            stamper.getAcroFields().setField("WISmod", pcWisMod);
            stamper.getAcroFields().setField("CHA", pcChaScore);
            stamper.getAcroFields().setField("CHamod", pcChaMod);

            stamper.getAcroFields().setField("ClassLevel", pcClassLevel);
            stamper.getAcroFields().setField("Passive", pcPerc);

            stamper.close();
            reader.close();
        } catch (java.io.IOException | DocumentException e) {
            System.err.println("1st Catch, that didn't go well: " + e.getMessage());
        } catch (ParsingException e) {
            System.err.println("2nd Catch, that didn't go well: " + e.getMessage());
        }
    }
}

From source file:org.alfresco.extension.countersign.behavior.SignableDocumentBehavior.java

License:Open Source License

/**
 * When the "signable" aspect is applied, extract the signature fields and add them
 * to the multivalue property/*  w  w  w  .  ja  v a 2  s .com*/
 */
public void onAddAspect(NodeRef nodeRef, QName aspectTypeQName) {
    try {
        // when the aspect is added, extract the signature fields from the PDF
        ArrayList<String> signatureFields = new ArrayList<String>();
        ContentReader pdfReader = serviceRegistry.getContentService().getReader(nodeRef,
                ContentModel.PROP_CONTENT);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());
        AcroFields form = reader.getAcroFields();
        Map<String, Item> fields = form.getFields();
        Iterator<String> it = fields.keySet().iterator();
        while (it.hasNext()) {
            String fieldName = it.next();
            if (form.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE) {
                // add this signature field to the list of available fields
                signatureFields.add(fieldName);
            }
        }
        serviceRegistry.getNodeService().setProperty(nodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS,
                signatureFields);

    } catch (IOException ex) {
        logger.error("Error extracting PDF signature fields from document: " + ex);
    }
}

From source file:org.cejug.footprint.FootPrint.java

License:Open Source License

public byte[] generate() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*w w w .  jav  a2s  .c o  m*/
        PdfStamper stamper = new PdfStamper(reader, baos);
        AcroFields fields = stamper.getAcroFields();
        Set<String> keys = fields.getFields().keySet();
        for (String k : keys) {
            fields.setField(k, values.get(k));
        }
        stamper.close();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
    }
    return baos.toByteArray();
}

From source file:org.smap.sdal.managers.MiscPDFManager.java

License:Open Source License

public void createUsagePdf(Connection sd, OutputStream outputStream, String basePath,
        HttpServletResponse response, int o_id, int month, int year, String period, String org_name) {

    PreparedStatement pstmt = null;

    if (org_name == null) {
        org_name = "None";
    }// w  w  w.  ja  v a2 s  .c  o  m

    try {

        String filename;

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        filename = org_name + "_" + year + "_" + month + ".pdf";

        /*
         * Get the usage results
         */
        String sql = "SELECT users.id as id," + "users.ident as ident, " + "users.name as name, "
                + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id "
                + "and se.status = 'success' " + "and se.subscriber = 'results_db' "
                + "and extract(month from upload_time) = ? " // current month
                + "and extract(year from upload_time) = ? " // current year
                + "and ue.user_name = users.ident) as month, "
                + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id "
                + "and se.status = 'success' " + "and se.subscriber = 'results_db' "
                + "and ue.user_name = users.ident) as all_time " + "from users " + "where users.o_id = ? "
                + "and not users.temporary " + "order by users.ident;";

        pstmt = sd.prepareStatement(sql);
        pstmt.setInt(1, month);
        pstmt.setInt(2, year);
        pstmt.setInt(3, o_id);
        log.info("Get Usage Data: " + pstmt.toString());

        // If the PDF is to be returned in an http response then set the file name now
        if (response != null) {
            log.info("Setting filename to: " + filename);
            setFilenameInResponse(filename, response);
        }

        /*
         * Get a template for the PDF report if it exists
         * The template name will be the same as the XLS form name but with an extension of pdf
         */
        String stationaryName = basePath + File.separator + "misc" + File.separator + "UsageReportTemplate.pdf";
        File stationaryFile = new File(stationaryName);

        ByteArrayOutputStream baos = null;
        ByteArrayOutputStream baos_s = null;
        PdfWriter writer = null;

        /*
         * Create document in two passes, the second pass adds the letter head
         */

        // Create the underlying document as a byte array
        Document document = new Document(PageSize.A4);
        document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);

        if (stationaryFile.exists()) {
            baos = new ByteArrayOutputStream();
            baos_s = new ByteArrayOutputStream();
            writer = PdfWriter.getInstance(document, baos);
        } else {
            writer = PdfWriter.getInstance(document, outputStream);
        }

        writer.setInitialLeading(12);
        writer.setPageEvent(new PageSizer());
        document.open();

        // Write the usage data
        ResultSet resultSet = pstmt.executeQuery();

        PdfPTable table = new PdfPTable(4);

        // Add the header row
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
        table.getDefaultCell().setBackgroundColor(VLG);

        table.addCell("User Id");
        table.addCell("User Name");
        table.addCell("Usage in Period");
        table.addCell("All Time Usage");

        table.setHeaderRows(1);

        // Add the user data
        int total = 0;
        int totalAllTime = 0;

        table.getDefaultCell().setBackgroundColor(null);
        while (resultSet.next()) {
            String ident = resultSet.getString("ident");
            String name = resultSet.getString("name");
            String monthUsage = resultSet.getString("month");
            int monthUsageInt = resultSet.getInt("month");
            String allTime = resultSet.getString("all_time");
            int allTimeInt = resultSet.getInt("all_time");

            table.addCell(ident);
            table.addCell(name);
            table.addCell(monthUsage);
            table.addCell(allTime);

            total += monthUsageInt;
            totalAllTime += allTimeInt;

        }

        // Add the totals
        table.getDefaultCell().setBackgroundColor(VLG);

        table.addCell("Totals: ");
        table.addCell(" ");
        table.addCell(String.valueOf(total));
        table.addCell(String.valueOf(totalAllTime));

        document.add(table);
        document.close();

        if (stationaryFile.exists()) {

            // Step 2 - Populate the fields in the stationary
            PdfReader s_reader = new PdfReader(stationaryName);
            PdfStamper s_stamper = new PdfStamper(s_reader, baos_s);
            AcroFields pdfForm = s_stamper.getAcroFields();
            Set<String> fields = pdfForm.getFields().keySet();
            for (String key : fields) {
                log.info("Field: " + key);
            }

            pdfForm.setField("billing_period", period);
            pdfForm.setField("organisation", org_name);

            s_stamper.setFormFlattening(true);
            s_stamper.close();

            // Step 3 - Apply the stationary to the underlying document
            PdfReader reader = new PdfReader(baos.toByteArray()); // Underlying document
            PdfReader f_reader = new PdfReader(baos_s.toByteArray()); // Filled in stationary
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            PdfImportedPage letter1 = stamper.getImportedPage(f_reader, 1);
            int n = reader.getNumberOfPages();
            PdfContentByte background;
            for (int i = 0; i < n; i++) {
                background = stamper.getUnderContent(i + 1);
                if (i == 0) {
                    background.addTemplate(letter1, 0, 0);
                }
            }

            stamper.close();
            reader.close();

        }

    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);

    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception", e);

    } finally {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
    }

}

From source file:PdfFormFiller.WrongParamsExeption.java

License:GNU General Public License

public static void formList(AcroFields form) {
    Map<String, AcroFields.Item> map = form.getFields();
    System.out.println("Field names:");
    for (Map.Entry<String, AcroFields.Item> entry : map.entrySet())
        System.out.println(entry.getKey());
    System.out.println("END: Field names");
}