Example usage for org.apache.pdfbox.pdmodel.interactive.form PDField getFullyQualifiedName

List of usage examples for org.apache.pdfbox.pdmodel.interactive.form PDField getFullyQualifiedName

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.interactive.form PDField getFullyQualifiedName.

Prototype

public String getFullyQualifiedName() 

Source Link

Document

Returns the fully qualified name of the field, which is a concatenation of the names of all the parents fields.

Usage

From source file:FormFiller.java

private static void fillPdf(HashMap dealerTrackData, String inputFileName, String outputDir,
        String outputFormType) {/* w ww.  j  a  v a2 s.c o m*/
    try {
        PDDocument pdfTemplate = PDDocument.load(new File(inputFileName));

        PDDocumentCatalog docCatalog = pdfTemplate.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();

        List<PDField> fieldList = acroForm.getFields();

        String[] fieldArray = new String[fieldList.size()];
        int i = 0;
        for (PDField sField : fieldList) {
            fieldArray[i] = sField.getFullyQualifiedName();
            i++;
        }

        for (String f : fieldArray) {
            PDField field = acroForm.getField(f);
            String value = (String) dealerTrackData.get(f);
            if (value != null) {
                try {
                    field.setValue(value);
                } catch (IllegalArgumentException e) {
                    System.err.println("Could not insert: " + f + ".");
                }
            }
        }

        pdfTemplate.save(outputDir + "/" + dealerTrackData.get("fullName") + " " + outputFormType + ".pdf");

        // printing - need to look into the long form stuff!
        if (print && !inputFileName.contains("Title Guarantee"))
            printPdf(pdfTemplate, dealerTrackData, inputFileName,
                    inputFileName.contains("Purchase Contract") ? 2 : 1);

        pdfTemplate.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ch.vaudoise.vaapi.dctm.resource.root.LoadAndSetPDF.java

public static void setPDF(String nom, String prenom, String adresse, String telephone, String commentaire,
        String description) throws IOException {
    String adressePart1 = null;/*  w ww.  j av  a2 s .c  om*/
    String adressePart2 = null;
    String[] adresseTab = adressParser(adresse);
    if (adresseTab.length > 0) {
        adressePart1 = (adresseTab[0] + " " + adresseTab[1]);
        adressePart2 = (adresseTab[2] + " " + adresseTab[3]);
    }
    //Loading an existing document 
    File file = new File("C:\\Temp\\declaration.pdf");
    try (PDDocument document = PDDocument.load(file)) {

        PDDocumentCatalog docCatalog = document.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();

        // Get field names
        List<PDField> fieldList = acroForm.getFields();

        // String the object array
        String[] fieldArray = new String[fieldList.size()];
        int i = 0;
        for (PDField sField : fieldList) {
            fieldArray[i] = sField.getFullyQualifiedName();
            i++;
        }

        // Loop through each field in the array and fill the blanks
        for (String f : fieldArray) {
            PDField field = acroForm.getField(f);
            //                System.out.println(f);
            switch (f) {
            case "Nom prnom ou raison sociale": {
                if (nom != null && nom != null) {
                    field.setValue(nom + " " + prenom);
                    break;
                } else {
                    field.setValue("Faten");
                    break;
                }
            }
            case "Adresse": {
                if (adressePart1 != null) {
                    field.setValue(adressePart1);
                    break;
                } else {
                    field.setValue("Rue des moulins 12");
                    break;
                }
            }
            case "NPA et localit": {
                if (adressePart2 != null) {
                    field.setValue(adressePart2);
                    break;
                } else {
                    field.setValue("1006 lausanne");
                    break;
                }
            }
            case "Tlphone et et fax": {
                if (telephone != null) {
                    field.setValue(telephone);
                    break;
                } else {
                    field.setValue("");
                    break;
                }
            }
            case "Email": {
                field.setValue("");
                break;
            }
            case "Nom de la personne de contact": {
                field.setValue(nom + " " + prenom);
                break;
            }
            case "CCP ou compte bancaire": {
                field.setValue("");
                break;
            }
            case "Si oui N TVA": {
                field.setValue("");
                break;
            }
            case "Si oui compagnie": {
                field.setValue("");
                break;
            }
            case "Numro de contrat dassurance ex1234562200": {
                field.setValue("1234564100");
                break;
            }
            case "Remarques": {
                if (commentaire != null) {
                    field.setValue(commentaire);
                    break;
                } else {
                    field.setValue("Rien  signaler ...");
                    break;
                }
            }
            case "Description de": {
                if (description != null) {
                    field.setValue(description);
                    break;
                } else {
                    field.setValue("Rien  signaler ...");
                    break;
                }
            }
            }
        }
        //Saving the document
        document.save("C:/temp/declarationRemplie.pdf");

        //Closing the document  
        document.close();
    }

}

From source file:com.fangxin365.core.utils.PDFMerger.java

License:Apache License

/**
 * Merge the contents of the source form into the destination form for the
 * destination file./*  www .j  ava 2 s . c o  m*/
 * 
 * @param cloner
 *            the object cloner for the destination document
 * @param destAcroForm
 *            the destination form
 * @param srcAcroForm
 *            the source form
 * @throws IOException
 *             If an error occurs while adding the field.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void mergeAcroForm(PDFCloneUtility cloner, PDAcroForm destAcroForm, PDAcroForm srcAcroForm)
        throws IOException {
    List destFields = destAcroForm.getFields();
    List srcFields = srcAcroForm.getFields();
    if (srcFields != null) {
        if (destFields == null) {
            destFields = new COSArrayList();
            destAcroForm.setFields(destFields);
        }
        Iterator srcFieldsIterator = srcFields.iterator();
        while (srcFieldsIterator.hasNext()) {
            PDField srcField = (PDField) srcFieldsIterator.next();
            PDField destField = PDFieldFactory.createField(destAcroForm,
                    (COSDictionary) cloner.cloneForNewDocument(srcField.getDictionary()));
            // if the form already has a field with this name then we need
            // to rename this field
            // to prevent merge conflicts.
            if (destAcroForm.getField(destField.getFullyQualifiedName()) != null) {
                destField.setPartialName("dummyFieldName" + (nextFieldNum++));
            }
            destFields.add(destField);
        }
    }
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

License:Apache License

/**
 * Add Field to Page Map.// www  . j a va 2 s .c  o  m
 *
 * @param objMap {@link Map} of {@link COSDictionary} objects by
 * Page Number.
 * @param field {@link PDField}
 * @param map {@link Map}
 * @throws IOException IOException
 */
private void addFieldToPageMap(final Map<COSDictionary, Integer> objMap, final PDField field,
        final Map<Integer, List<PDField>> map) throws IOException {

    List<PDAnnotationWidget> widgets = field.getWidgets();

    if (field instanceof PDNonTerminalField) {
        PDNonTerminalField tf = (PDNonTerminalField) field;

        for (PDField f : tf.getChildren()) {
            addFieldToPageMap(objMap, f, map);
        }

    } else {

        if (!CollectionUtils.isEmpty(widgets)) {

            LOG.log(Level.FINE, "addFieldToPageMap='" + field.getFullyQualifiedName() + "',class="
                    + field.getClass().getName());

            Integer page = getPageNumber(objMap, field);

            if (!map.containsKey(page)) {
                map.put(page, new ArrayList<>());
            }

            map.get(page).add(field);

        } else {

            LOG.log(Level.FINE, "skip addFieldToPageMap='" + field.getFullyQualifiedName() + "',class="
                    + field.getClass().getName());
        }
    }
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

License:Apache License

/**
 * Create {@link List} of {@link WorkflowOutputPdfFormField}.
 * @param form {@link FormJSON}//from   w ww  .  j a v a  2s .c  o  m
 * @param fields {@link List} of {@link PDField}
 * @param map {@link Map} of {@link PDField} to {@link FormJSONField}
 * @return {@link List} of {@link WorkflowOutputPdfFormField}
 */
private List<WorkflowOutputFormField> createFieldOutputs(final FormJSON form, final List<PDField> fields,
        final Map<PDField, FormJSONField> map) {

    List<WorkflowOutputFormField> list = new ArrayList<>();

    for (PDField pdfield : fields) {

        FormJSONField field = map.get(pdfield);

        WorkflowOutputFormField wo = buildWorkflowOuputFormField(form, field, pdfield.getFullyQualifiedName());

        list.add(wo);
    }

    return list;
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

License:Apache License

/**
 * Get Page Number for {@link PDField}.//from w  w  w .j  av a 2 s . c  o m
 * @param objMap {@link Map} of {@link COSDictionary} and Page Number
 * @param field {@link PDField}
 * @param widget {@link PDAnnotationWidget}
 * @return {@link Integer}
 */
private Integer getPageNumber(final Map<COSDictionary, Integer> objMap, final PDField field,
        final PDAnnotationWidget widget) {

    COSDictionary cosObject = widget.getCOSObject();

    if (objMap.containsKey(cosObject)) {
        return objMap.get(cosObject);
    }

    throw new PdfConversionException("cannot find page for " + field.getFullyQualifiedName());
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

License:Apache License

/**
 * Take {@link PDField} objects from {@link PDDocument}
 * and create {@link PDField} from them.
 *
 * @param doc {@link PDDocument}/*from w w  w.  j a v  a  2 s . co m*/
 * @param objMap {@link Map} of {@link COSDictionary} and Page Number
 * @return {@link Map} of {@link PDField} by page number
 * @throws IOException IOException
 */
private Map<Integer, List<PDField>> getPDFields(final PDDocument doc, final Map<COSDictionary, Integer> objMap)
        throws IOException {

    PDDocumentCatalog dc = doc.getDocumentCatalog();
    PDAcroForm pdform = dc.getAcroForm();

    Map<Integer, List<PDField>> map = new HashMap<>();

    for (PDField field : pdform.getFields()) {

        if (field instanceof PDPushButton) {
            LOG.log(Level.FINE, "skip addFieldToPageMap='" + field.getFullyQualifiedName() + "',class="
                    + field.getClass().getName());
            continue;
        }

        addFieldToPageMap(objMap, field, map);
    }

    for (Map.Entry<Integer, List<PDField>> e : map.entrySet()) {
        Collections.sort(e.getValue(), new PDFieldComparator());
    }

    return map;
}

From source file:fys.BagagedatabaseController.java

private void sendToDatabase(int dr_id, int dr_personId, int dr_lafId, int tableFrom, int status, String airport,
        String frontname, String surname, String address, String shipaddress, String residence, String zipcode,
        String country, String phone, String mail, String labelnumber, String filePath, String flightnumber,
        String destination, int type, String brand, Integer color, String characteristics)
        throws IOException, SQLException {

    try {//  w w w .  jav  a 2s . com
        conn = fys.connectToDatabase(conn);
        stmt = conn.createStatement();

        //connectToDatabase(conn, stmt, "test", "root", "root");
        String sql_person = "UPDATE bagagedatabase.person SET first_name='" + frontname + "'," + "surname='"
                + surname + "', address='" + address + "'," + "residence='" + residence + "', zip_code='"
                + zipcode + "'," + "country='" + country + "', phone='" + phone + "'," + "mail='" + mail + "'"
                + "WHERE person_id='" + dr_personId + "'";
        stmt.executeUpdate(sql_person);

        String sql_lost = "";
        String sql_airport = "";
        String sql_status = "";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date();
        String dateTimeString = dateFormat.format(date);
        String[] tokens = dateTimeString.split(" ");
        if (tokens.length != 2) {
            throw new IllegalArgumentException();
        }
        String dateString = tokens[0];
        String timeString = tokens[1];

        if (tableFrom == 0) { //0 = bagagedatabase.lost
            sql_lost = "UPDATE bagagedatabase.lost SET status='" + status + "'," + "picture='" + filePath
                    + "', type='" + type + "', brand='" + brand + "'," + "color='" + color
                    + "', characteristics='" + characteristics + "'" + "WHERE id='" + dr_id + "'";

            //Registreer de status van een bagage.
            sql_status = "INSERT INTO luggage_status VALUES(" + dr_id + ", '" + dateString + "', '" + timeString
                    + "', '" + status + "', 0);";

            switch (status) {
            //case 0: Gaat van lost naar status Gevonden
            case 0:
                sql_airport = "UPDATE bagagedatabase.airport SET airport_found='" + airport + "',"
                        + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "',"
                        + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'";
                break;
            //case 3: Gaat van lost naar status Afgehandeld
            case 3:
                sql_airport = "UPDATE bagagedatabase.airport SET airport_found='" + airport + "',"
                        + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "',"
                        + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'";
                break;
            //default: Gaat van lost naar status Vermist, Vernietigd, Nooit Gevonden of Depot 
            default:
                sql_airport = "UPDATE bagagedatabase.airport SET airport_lost='" + airport + "',"
                        + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "',"
                        + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'";
                break;
            }
        } else if (tableFrom == 1) { //1 = bagagedatabase.found
            sql_lost = "UPDATE bagagedatabase.found SET status='" + status + "'," + "picture='" + filePath
                    + "', type='" + type + "', brand='" + brand + "'," + "color='" + color
                    + "', characteristics='" + characteristics + "'" + "WHERE id='" + dr_id + "'";

            //Registreer de status van een bagage.
            sql_status = "INSERT INTO luggage_status VALUES(" + dr_id + ", '" + dateString + "', '" + timeString
                    + "', '" + status + "', 1);";

            switch (status) {
            //case 1: Gaat van found naar status Vermist
            case 1:
                sql_airport = "UPDATE bagagedatabase.airport SET airport_lost='" + airport + "',"
                        + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "',"
                        + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'";
                break;
            //case 3: Gaat van found naar status Afgehandeld
            case 3:
                sql_airport = "UPDATE bagagedatabase.airport SET airport_lost='" + airport + "',"
                        + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "',"
                        + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'";
                break;
            //default: Gaat van found naar status Gevonden, Vernietigd, Nooit gevonden, Depot 
            default:
                sql_airport = "UPDATE bagagedatabase.airport SET airport_found='" + airport + "',"
                        + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "',"
                        + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'";
                break;
            }
        }
        if (status != 6) {
            stmt.executeUpdate(sql_lost);
        }
        stmt.executeUpdate(sql_airport);
        if (status != fys.getStatusString(dr_status)) {
            stmt.executeUpdate(sql_status);
        }

        if (status != 3) {
            int pageid = 4;
            int type_email = 0;
            if (mailInput.getText() == null || !FYS.isValidEmailAddress(mailInput.getText())
                    || mailInput.getText().trim().isEmpty()) {

            } else {
                // Email bericht filteren op sommige woorden.
                String getmessage = fys.replaceEmail(
                        fys.replaceEmail_tF(
                                fys.Email_Message(type_email, fys.Email_Language(mailInput.getText()), pageid),
                                mailInput.getText(), Integer.parseInt(tableFromLabel.getText())),
                        mailInput.getText());
                // Email versturen
                fys.sendEmail(mailInput.getText(),
                        fys.Email_Subject(type_email, fys.Email_Language(mailInput.getText()), pageid),
                        getmessage, "Sent message successfully....");
            }
        }

        /*Indien de status wordt veranderd naar afgehandeld wordt er een DHL-
        formulier gemaakt. DISCLAIMER: Het DHL-formulier dat gemaakt wordt is
        gebaseerd op het officile DHL-emailshipment formulier dat is te vinden
        op 'http://www.dhl.com/en/express/resource_center/emailship.html'.
        Het formulier is gekopieerd en aangepast d.m.v. Adobe Acrobat DC en is 
        louter bedoeld voor demonstratieve doeleinden.
         */
        if (status == 3) { //Afgehandeld
            //Maak nieuwe PDF-document aan de hand van de template
            File pdfdoc = new File("src/fys/templates/dhltemplate.pdf");
            PDDocument document;
            document = PDDocument.load(pdfdoc);

            //Laad alle inputvelden op het formulier
            PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
            List<PDField> fields = acroForm.getFields();

            //Vul alle inputvelden in met de waardes uit de database
            for (PDField field : fields) {
                if (field.getFullyQualifiedName().equals("companyName_field")) {
                    field.setValue("Corendon");
                }
                if (field.getFullyQualifiedName().equals("country_field")) {
                    field.setValue(country);
                }
                if (field.getFullyQualifiedName().equals("address_field")) {
                    field.setValue(shipaddress);
                }
                if (field.getFullyQualifiedName().equals("city_field")) {
                    field.setValue(residence);
                }
                if (field.getFullyQualifiedName().equals("postcode_field")) {
                    field.setValue(zipcode);
                }
                if (field.getFullyQualifiedName().equals("contactPerson_field")) {
                    field.setValue(frontname + " " + surname);
                }
                if (field.getFullyQualifiedName().equals("phone_field")) {
                    field.setValue(phone);
                }
                if (field.getFullyQualifiedName().equals("type_field")) {
                    field.setValue("International NonDocument");
                }
                if (field.getFullyQualifiedName().equals("product_field")) {
                    field.setValue("Express WorldWide");
                }
                if (field.getFullyQualifiedName().equals("notification_field")) {
                    field.setValue("fysepsilon@gmail.com ");
                }
                if (field.getFullyQualifiedName().equals("content_field")) {
                    field.setValue(fys.getBaggageType(type));
                }
                if (field.getFullyQualifiedName().equals("date_field")) {
                    field.setValue(dateString);
                }
            }

            //Sla het document op
            document.save("src/fys/formulieren/dhlFormulier" + frontname + surname + dr_personId + ".pdf");
            document.close();

            int pageid = 5;
            int type_email = 0;

            if (mailInput.getText() == null || !FYS.isValidEmailAddress(mailInput.getText())
                    || mailInput.getText().trim().isEmpty()) {

            } else {
                // Email bericht filteren op sommige woorden.            
                String getmessage = fys.replaceEmail(
                        fys.replaceEmail_tF(
                                fys.Email_Message(type_email, fys.Email_Language(mailInput.getText()), pageid),
                                mailInput.getText(), Integer.parseInt(tableFromLabel.getText())),
                        mailInput.getText());
                // Email versturen
                fys.sendEmail(mailInput.getText(),
                        fys.Email_Subject(type_email, fys.Email_Language(mailInput.getText()), pageid),
                        getmessage, "Sent message successfully....");
            }
        }

        if (status == 4) { //Nooit gevonden
            int pageid = 6; //Pagina id
            int type_email = 3; //Onbekend
            int language_email = 1; //Nederlands ?!
            String email_paymentdepartment = "fysepsilon@gmail.com"; // Betalingsafdeling mail
            if (mailInput.getText() == null || !FYS.isValidEmailAddress(mailInput.getText())
                    || mailInput.getText().trim().isEmpty()) {

            } else {
                // Email bericht filteren op sommige woorden.            
                String getmessage = fys.replaceEmail(
                        fys.replaceEmail_tF(fys.Email_Message(type_email, language_email, pageid),
                                mailInput.getText(), Integer.parseInt(tableFromLabel.getText())),
                        mailInput.getText());
                // Email versturen
                fys.sendEmail(email_paymentdepartment, fys.Email_Subject(type_email, language_email, pageid),
                        getmessage, "Sent message successfully....");
            }
        }

        pictureButton.setText(taal[44]);
        fys.changeToAnotherFXML(taal[100], "bagagedatabase.fxml");
        conn.close();
    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
    }
}

From source file:fys.StatistiekenController.java

@FXML
private void handleExportToPDFAction(ActionEvent event) throws IOException {
    if ((dateFrom.getText() == null || dateFrom.getText().trim().isEmpty())
            || (dateTo.getText() == null || dateTo.getText().trim().isEmpty())) {
        ErrorLabel.setText(taal[93]);//from  w w w.j a  v a2  s. c  o m
        ErrorLabel.setVisible(true);
    } else {
        String dateFromInput = dateFrom.getText();
        String dateToInput = dateTo.getText();
        //Doe dit alleen wanneer er waardes zijn ingevuld.
        lineChart.setAnimated(false);
        pieChart.setAnimated(false);
        //PIECHART
        //Maak alle data en aantallen weer leeg.
        int luggage = 0, foundAmount = 0, lostAmount = 0, destroyAmount = 0, settleAmount = 0,
                neverFoundAmount = 0, depotAmount = 0;
        int jan = 0, feb = 0, mar = 0, apr = 0, mei = 0, jun = 0, jul = 0, aug = 0, sep = 0, okt = 0, nov = 0,
                dec = 0;
        total = 0;
        series.getData().clear();
        pieChartData = FXCollections.observableArrayList();

        //Krijg alle data voor de pietchart die tussen de periode van DateFrom en DateTo ligt.
        try {
            conn = fys.connectToDatabase(conn);
            stmt = conn.createStatement();
            //connectToDatabase(conn, stmt, "test", "root", "root"); 
            String sql = "SELECT status, date, COUNT(status) AS Count FROM bagagedatabase.luggage_status "
                    + "WHERE date >= \"" + fys.convertToDutchDate(dateFromInput) + "\" " + "AND date <= \""
                    + fys.convertToDutchDate(dateToInput) + "\" " + "GROUP BY status";
            //Voeg alle aantallen per status toe aan variabelen.
            try (ResultSet rs = stmt.executeQuery(sql)) {
                while (rs.next()) {
                    luggage++;
                    //Retrieve by column name
                    foundAmount = (rs.getInt("status") == 0 ? rs.getInt("Count") : foundAmount);
                    lostAmount = (rs.getInt("status") == 1 ? rs.getInt("Count") : lostAmount);
                    destroyAmount = (rs.getInt("status") == 2 ? rs.getInt("Count") : destroyAmount);
                    settleAmount = (rs.getInt("status") == 3 ? rs.getInt("Count") : settleAmount);
                    neverFoundAmount = (rs.getInt("status") == 4 ? rs.getInt("Count") : neverFoundAmount);
                    depotAmount = (rs.getInt("status") == 5 ? rs.getInt("Count") : depotAmount);
                }
            }
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }

        //Voeg de waardes toe aan de array.
        pieChartData = FXCollections.observableArrayList(new PieChart.Data(ExportToPdfTexts[15], foundAmount),
                new PieChart.Data(ExportToPdfTexts[16], lostAmount),
                new PieChart.Data(ExportToPdfTexts[17], destroyAmount),
                new PieChart.Data(ExportToPdfTexts[18], settleAmount),
                new PieChart.Data(ExportToPdfTexts[19], neverFoundAmount),
                new PieChart.Data(ExportToPdfTexts[20], depotAmount));

        //Update de titel
        pieChart.setTitle(ExportToPdfTexts[0]);

        //Update de piechart met de gevraagde gegevens.
        pieChart.setData(pieChartData);

        //Voor elke aantal tel ze met elkaar op en sla het op bij total.
        for (PieChart.Data d : pieChart.getData()) {
            total += d.getPieValue();
        }

        //Verander de tekst van elke piechartdata. naar: (aantal statusnaam: percentage).
        pieChartData.forEach(data -> data.nameProperty().bind(Bindings.concat((int) data.getPieValue(), " ",
                data.getName(), ": ",
                (total == 0 || (int) data.getPieValue() == 0) ? 0 : (int) (data.getPieValue() / total * 100),
                "%")));

        //LINECHART
        //Krijg alle data voor de linechart die tussen de periode van DateFrom en DateTo ligt.
        try {
            conn = fys.connectToDatabase(conn);
            stmt = conn.createStatement();
            String sql = "SELECT date, COUNT(date) as Count FROM bagagedatabase.luggage_status "
                    + "WHERE status = 6 AND date >= \"" + fys.convertToDutchDate(dateFromInput) + "\" "
                    + "AND date <= \"" + fys.convertToDutchDate(dateToInput) + "\" " + "GROUP BY date";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                //Retrieve by column name
                //Voeg alle aantallen per maand toe aan variabelen.
                if (rs.getString("date") != null) {
                    //Krijg van elke date record de maand eruit.
                    String str[] = rs.getString("date").split("-");
                    int month = Integer.parseInt(str[1]);
                    jan = (month == 1 ? jan += rs.getInt("Count") : jan);
                    feb = (month == 2 ? feb += rs.getInt("Count") : feb);
                    mar = (month == 3 ? mar += rs.getInt("Count") : mar);
                    apr = (month == 4 ? apr += rs.getInt("Count") : apr);
                    mei = (month == 5 ? jan += rs.getInt("Count") : mei);
                    jun = (month == 6 ? jun += rs.getInt("Count") : jun);
                    jul = (month == 7 ? jul += rs.getInt("Count") : jul);
                    aug = (month == 8 ? aug += rs.getInt("Count") : aug);
                    sep = (month == 9 ? sep += rs.getInt("Count") : sep);
                    okt = (month == 10 ? okt += rs.getInt("Count") : okt);
                    nov = (month == 11 ? nov += rs.getInt("Count") : nov);
                    dec = (month == 12 ? dec += rs.getInt("Count") : dec);
                }
            }
            rs.close();
            conn.close();
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }

        //Update de titel
        lineChart.setTitle(ExportToPdfTexts[1]);

        //Update de linechart naar de waardes die gewenst is.
        series.setName(ExportToPdfTexts[2]);
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[3], jan));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[4], feb));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[5], mar));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[6], apr));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[7], mei));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[8], jun));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[9], jul));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[10], aug));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[11], sep));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[12], okt));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[13], nov));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[14], dec));

        //Update de piechart en linechart voordat er een screenshot van genomen wordt.
        lineChart.applyCss();
        lineChart.layout();
        pieChart.applyCss();
        pieChart.layout();

        //Maak een screenshot van de piechart en linechart.
        savePieChartAsPng();
        saveLineChartAsPng();

        try {

            //Krijg de datum van vandaag voor pdf.
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            String dateString = dateFormat.format(date);

            //Krijg de content van de template pdf en maake nieuw pdf aan.
            File pdfdoc = new File("src/fys/templates/statisticstemplate.pdf");
            PDDocument document = null;
            document = PDDocument.load(pdfdoc);
            PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
            List<PDField> fields = acroForm.getFields();

            // set the text in the form-field <-- does work
            //Verander voor elk veld de waardes.
            for (PDField field : fields) {
                if (field.getFullyQualifiedName().equals("found")) {
                    field.setValue(String.valueOf(foundAmount));
                }
                if (field.getFullyQualifiedName().equals("lost")) {
                    field.setValue(String.valueOf(lostAmount));
                }
                if (field.getFullyQualifiedName().equals("destroyed")) {
                    field.setValue(String.valueOf(destroyAmount));
                }
                if (field.getFullyQualifiedName().equals("completed")) {
                    field.setValue(String.valueOf(settleAmount));
                }
                if (field.getFullyQualifiedName().equals("neverfound")) {
                    field.setValue(String.valueOf(neverFoundAmount));
                }
                if (field.getFullyQualifiedName().equals("depot")) {
                    field.setValue(String.valueOf(depotAmount));
                }

                if (field.getFullyQualifiedName().equals("jan")) {
                    field.setValue(String.valueOf(jan));
                }
                if (field.getFullyQualifiedName().equals("feb")) {
                    field.setValue(String.valueOf(feb));
                }
                if (field.getFullyQualifiedName().equals("mar")) {
                    field.setValue(String.valueOf(mar));
                }
                if (field.getFullyQualifiedName().equals("apr")) {
                    field.setValue(String.valueOf(apr));
                }
                if (field.getFullyQualifiedName().equals("may")) {
                    field.setValue(String.valueOf(mei));
                }
                if (field.getFullyQualifiedName().equals("jun")) {
                    field.setValue(String.valueOf(jun));
                }
                if (field.getFullyQualifiedName().equals("jul")) {
                    field.setValue(String.valueOf(jul));
                }
                if (field.getFullyQualifiedName().equals("aug")) {
                    field.setValue(String.valueOf(aug));
                }
                if (field.getFullyQualifiedName().equals("sep")) {
                    field.setValue(String.valueOf(sep));
                }
                if (field.getFullyQualifiedName().equals("oct")) {
                    field.setValue(String.valueOf(okt));
                }
                if (field.getFullyQualifiedName().equals("nov")) {
                    field.setValue(String.valueOf(nov));
                }
                if (field.getFullyQualifiedName().equals("dec")) {
                    field.setValue(String.valueOf(dec));
                }
                if (field.getFullyQualifiedName().equals("date")) {
                    field.setValue(String.valueOf(dateString));
                }
                if (field.getFullyQualifiedName().equals("period")) {
                    field.setValue(String.valueOf(dateFromInput + " | " + dateToInput));
                }
            }

            //Retrieving the page
            PDPage page = document.getPage(0);

            //Creating PDImageXObject object
            loginController login = new loginController();
            PDImageXObject pieChartImage = PDImageXObject
                    .createFromFile("src/fys/statistieken/PieChart_" + login.getUsersName() + ".png", document);
            PDImageXObject lineChartImage = PDImageXObject.createFromFile(
                    "src/fys/statistieken/LineChart_" + login.getUsersName() + ".png", document);

            //creating the PDPageContentStream object
            PDPageContentStream contents = new PDPageContentStream(document, page, true, true, true);

            //Drawing the image in the PDF document
            contents.drawImage(pieChartImage, 75, 0, 350, 300);
            contents.drawImage(lineChartImage, 425, 0, 350, 300);

            //Closing the PDPageContentStream object
            contents.close();

            //Sla het docment op.
            document.save("src/fys/statistieken/statistics" + dateFromInput + dateToInput + ".pdf");
            document.close();

            //Verwijder de plaatjes die waren opgeslagen.
            savePieChartAsPng().delete();
            saveLineChartAsPng().delete();

            //Sluit de popup
            home_pane.setDisable(false);
            pdfPane.setVisible(false);
        } catch (IOException ex) {
            Logger.getLogger(StatistiekenController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.isisaddons.module.pdf.fixture.dom.templates.CustomerConfirmation.java

License:Apache License

/**
 * Loads the template pdf file and populates it with the order details
 *
 * @param order The order with the details for the pdf document
 * @return The populated PDF document/*from  ww w .  ja v a  2s.co m*/
 * @throws Exception If the loading or the populating of the document fails for some reason
 */
private PDDocument loadAndPopulateTemplate(Order order) throws Exception {
    PDDocument pdfDocument = PDDocument.load(new ByteArrayInputStream(pdfAsBytes));

    PDAcroForm pdfForm = pdfDocument.getDocumentCatalog().getAcroForm();

    List<PDField> fields = pdfForm.getFields();
    SortedSet<OrderLine> orderLines = order.getOrderLines();
    for (PDField field : fields) {

        String fullyQualifiedName = field.getFullyQualifiedName();
        if ("orderDate".equals(fullyQualifiedName)) {
            field.setValue(order.getDate().toString());
        } else if ("orderNumber".equals(fullyQualifiedName)) {
            field.setValue(order.getNumber());
        } else if ("customerName".equals(fullyQualifiedName)) {
            field.setValue(order.getCustomerName());
        } else if ("message".equals(fullyQualifiedName)) {
            String message = "You have ordered '" + orderLines.size() + "' products";
            field.setValue(message);
        } else if ("preferences".equals(fullyQualifiedName)) {
            field.setValue(order.getPreferences());
        }
    }

    int i = 1;
    Iterator<OrderLine> orderLineIterator = orderLines.iterator();
    while (i < 7 && orderLineIterator.hasNext()) {
        OrderLine orderLine = orderLineIterator.next();

        String descriptionFieldName = "orderLine|" + i + "|desc";
        pdfForm.getField(descriptionFieldName).setValue(orderLine.getDescription());

        String costFieldName = "orderLine|" + i + "|cost";
        pdfForm.getField(costFieldName).setValue(orderLine.getDescription());

        String quantityFieldName = "orderLine|" + i + "|quantity";
        pdfForm.getField(quantityFieldName).setValue(orderLine.getDescription());
        i++;
    }

    return pdfDocument;
}