Example usage for com.itextpdf.text.pdf PdfStamper getAcroFields

List of usage examples for com.itextpdf.text.pdf PdfStamper getAcroFields

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfStamper getAcroFields.

Prototype

public AcroFields getAcroFields() 

Source Link

Document

Gets the AcroFields object that allows to get and set field values and to merge FDF forms.

Usage

From source file:ExternalNonFormClasses.RequestFormBrowser.java

public void disableFormOnly(boolean choice) { //save data
    try {/* w w w. j ava  2s  .  com*/
        PdfReader pdfTemplate = new PdfReader(
                "C:\\Users\\mrRNBean\\Documents\\NetBeansProjects\\BRMS_V2\\build\\templates\\" + form_name
                        + ".pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(
                "C:\\Users\\mrRNBean\\Documents\\NetBeansProjects\\BRMS_V2\\build\\printables\\" + form_name
                        + ".pdf");
        PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
        stamper.setFormFlattening(true);

        if (choice) { //post-request
            //manipiulate form fields--------------------------------------------------------------------
            stamper.getAcroFields().setField("12", "CHORVES");
            //String x = stamper.getAcroFields().getField("province");
            //-------------------------------------------------------------------------------------------

            //get field form_vars from form tb
            //slice data with delimiter and store to array
            //fetch array
            //use as basis for loop
            //get field using variable name in each array entry
            //every field entry should be added to a string concatenation
            //save string concatenation and form in "printables/" to FormRequest.tb
        }

        stamper.close();
        pdfTemplate.close();
    } catch (IOException | DocumentException ex) {
        Logger.getLogger(RequestFormBrowser.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fattura.Fattura.java

public void setFattura(String cliente, String data, AtomicInteger numerofattura, PdfStamper s)
        throws SQLException, DocumentException, FileNotFoundException, IOException { //Ho messo che il numero della fattura va passato come parametro, voglio capire se si pu fare altrimenti (con un contatore)

    try {//from   www . j av  a  2s. c o m

        s.getAcroFields().setField("Num", numerofattura.toString()); // sistemare
        s.getAcroFields().setField("Data", data);
        s.getAcroFields().setField("Nome", cliente);
        PdfContentByte content = s.getUnderContent(1);//1 for the first page
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
        content.beginText();
        content.setFontAndSize(bf, 7);
        inserisciDatiMaglie(cliente, data, s);
        inserisciDatiBorse(cliente, data, s);
        inserisciDatiPanta(cliente, data, s);
        inserisciDatiGiubb(cliente, data, s);
        inserisciDatiFelpe(cliente, data, s);
        inserisciDatiPubb(cliente, data, s);
        setImporti(s);
        content.endText();
        s.close();

    } catch (IOException | DocumentException e) {

    }
}

From source file:fattura.Fattura.java

public void setImporti(PdfStamper s) throws IOException, DocumentException {
    float imponibile = 0;
    float totiva;
    for (int i = 0; i < importi.size(); i++)
        imponibile += importi.get(i);/*from   w ww  . ja  v  a2 s.c o  m*/
    String convertitore = String.valueOf(imponibile);
    s.getAcroFields().setField("Imponibile", convertitore);
    totiva = (float) (1.22 * imponibile); //calcola l'iva sull'imponibile
    convertitore = String.valueOf(totiva); //converte totiva in stringa per stamparla su pdf
    s.getAcroFields().setField("IVA", "22%");
    s.getAcroFields().setField("Totale", convertitore);
}

From source file:gov.nih.nci.firebird.service.pdf.PdfServiceBean.java

License:Open Source License

@Override
public void fillOutForm(InputStream formInputStream, OutputStream filledOutFormOutputStream,
        final PdfFormValues values) throws IOException {
    PdfProcessor processor = new PdfProcessor(formInputStream, filledOutFormOutputStream) {
        @Override/*from ww  w .  j  a v  a2  s. com*/
        void handleProcessing(PdfReader reader, PdfStamper stamper) throws IOException, DocumentException {
            AcroFields fields = stamper.getAcroFields();
            addFieldValues(fields, values.getValueMap());
            if (!values.getAdditionalContent().isEmpty()) {
                values.getAdditionalContent().appendContent(reader, stamper);
            }
        }
    };
    processor.process();
}

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   w w w .  j  av a 2  s . c o  m*/

    //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;/*ww  w  .  j ava2 s  .  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:om.edu.squ.squportal.portlet.tsurvey.dao.pdf.TeachingSurveyPdfImpl.java

License:Open Source License

/**
 * //from   w w w . j  av  a  2 s  . co m
 * method name  : getPdfSurveyAnalysis
 * @param object
 * @param semesterYear
 * @param questionByYear
 * @param questionSetNo
 * @param byos
 * @param inputStream
 * @param res
 * @return
 * @throws DocumentException
 * @throws IOException
 * TeachingSurveyPdfImpl
 * return type  : OutputStream
 * 
 * purpose      : Generate PDF content
 *
 * Date          :   Mar 28, 2016 7:21:04 PM
 */
public OutputStream getPdfSurveyAnalysis(Object object, String semesterYear, String questionByYear,
        int questionSetNo, ByteArrayOutputStream byos, InputStream inputStream, ResourceResponse res)
        throws DocumentException, IOException {

    Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, BaseColor.BLACK);

    PdfReader pdfTemplate = new PdfReader(inputStream);
    PdfStamper pdfStamper = new PdfStamper(pdfTemplate, byos);
    Survey survey = (Survey) object;
    String sectionNos = "";
    String seatsTaken = "";
    DecimalFormat formatter = new DecimalFormat("###.##");

    String RIGHT = Constants.RIGHT;
    String CENTER = Constants.CENTER;
    String LEFT = Constants.LEFT;

    pdfStamper.getAcroFields().setField("txtCourse", survey.getCourseCode() + " / " + survey.getCourseName());
    pdfStamper.getAcroFields().setField("txtCollegeName", survey.getCollegeName());

    for (SurveyResponse resp : survey.getSurveyResponses()) {
        sectionNos = sectionNos + resp.getSectionNo() + " ";
        seatsTaken = String.valueOf(resp.getSeatsTaken());
    }

    pdfStamper.getAcroFields().setField("txtSectionNo", sectionNos);
    pdfStamper.getAcroFields().setField("txtDepartmentName", survey.getDepartmentName());
    pdfStamper.getAcroFields().setField("txtEmpName", survey.getEmpName());
    pdfStamper.getAcroFields().setField("txtStudentRegistered", seatsTaken);

    pdfStamper.getAcroFields().setField("txtSemesterYear", semesterYear);

    pdfStamper.getAcroFields().setGenerateAppearances(true);

    /* ****************** */

    PdfPTable table = new PdfPTable(13);

    table.addCell(getPdfCell("", 2, 0, font, LEFT));
    table.addCell(getPdfCell(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.teaching.items", null), 2, 0,
            font, CENTER));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.number", null), 0,
                    6, font, CENTER));
    table.addCell(getPdfCell(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.percentage", null), 2, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.mean", null), 0, 4,
            font, CENTER));

    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree.strong", null), 0,
                    0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree", null), 0,
            0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree.strong", null),
            0, 0, font, CENTER));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.applicable.not", null), 0,
                    0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.total", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.sect", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.crs", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.dept", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.col", null), 0, 0,
            font, CENTER));

    /* ---------------------------------------------------------------------------- */
    table.addCell(getPdfCell("", 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.items", null),
            0, 12, font, CENTER));

    int cTotal = 0;
    float cPctVal = 0f;
    float cSectionMean = 0f;
    float cCourseMean = 0f;
    float cDepart = 0f;
    float cCollege = 0f;
    int rowCount = 0;

    for (SurveyResponse sures : survey.getSurveyResponses()) {
        for (Analysis analysis : sures.getAnalysisList()) {
            if (analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14")
                    || analysis.getQuestion().equals(questionByYear)) {
                /***  First part    ***/
                table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font));
                table.addCell(
                        getPdfCell(
                                UtilProperty.getMessage("prop.course.teaching.survey.analysis.set"
                                        + questionSetNo + ".question" + analysis.getQuestionLabel(), null),
                                0, 0, font, LEFT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT));

                cTotal = cTotal + analysis.getTotal();
                cPctVal = cPctVal + analysis.getPercentageResponse();
                cSectionMean = cSectionMean + analysis.getSectionMean();
                cCourseMean = cCourseMean + analysis.getCollegeMean();
                cDepart = cDepart + analysis.getDepartmentMean();
                cCollege = cCollege + analysis.getCollegeMean();
                rowCount = rowCount + 1;

            }
        }
    }

    /***  First part - Summary   ***/
    table.addCell(getPdfCell(String.valueOf(""), 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0,
            0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(""), 0, 5, font));
    table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT));

    table.addCell(getPdfCell("", 0, 13, font));

    table.addCell(getPdfCell("", 0, 0, font));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.teaching.items", null), 0,
                    12, font, LEFT));

    cTotal = 0;
    cPctVal = 0f;
    cSectionMean = 0f;
    cCourseMean = 0f;
    cDepart = 0f;
    cCollege = 0f;
    rowCount = 0;
    for (SurveyResponse sures : survey.getSurveyResponses()) {
        for (Analysis analysis : sures.getAnalysisList()) {
            if (!(analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14")
                    || analysis.getQuestion().equals(questionByYear))) {

                table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font));
                table.addCell(
                        getPdfCell(
                                UtilProperty.getMessage("prop.course.teaching.survey.analysis.set"
                                        + questionSetNo + ".question" + analysis.getQuestionLabel(), null),
                                0, 0, font, LEFT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT));

                cTotal = cTotal + analysis.getTotal();
                cPctVal = cPctVal + analysis.getPercentageResponse();
                cSectionMean = cSectionMean + analysis.getSectionMean();
                cCourseMean = cCourseMean + analysis.getCollegeMean();
                cDepart = cDepart + analysis.getDepartmentMean();
                cCollege = cCollege + analysis.getCollegeMean();
                rowCount = rowCount + 1;

            }

        }

    }

    /***  Second part - Summary   ***/
    table.addCell(getPdfCell(String.valueOf(""), 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0,
            0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(""), 0, 5, font));
    table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT));

    if (!survey.getMessage().equals("")) {
        table.addCell(getPdfCell("", 0, 13, font));
        table.addCell(getPdfCell("", 0, 0, font));
        table.addCell(getPdfCell(survey.getMessage(), 0, 12, font, CENTER));
    }

    table.setTotalWidth(750);
    table.setLockedWidth(true);
    table.setWidths(new float[] { 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });

    ColumnText column = new ColumnText(pdfStamper.getOverContent(1));
    Rectangle rectPage1 = new Rectangle(120, 20, 659, 480);

    column.setSimpleColumn(rectPage1);
    column.addElement(table);

    int status = column.go();

    pdfStamper.setFormFlattening(true);

    pdfStamper.close();

    pdfTemplate.close();

    res.setContentType("application/pdf");

    return res.getPortletOutputStream();

}

From source file:Operaciones.ResponsablesOP.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);/*w  w w . j  ava 2s.com*/

    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        Orden ord = (Orden) session.get(Orden.class, Integer.parseInt(t_orden.getText()));
        Configuracion con = (Configuracion) session.get(Configuracion.class, 1);
        Date fecha = new Date();
        Date fecha1 = new Date();
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
        String valor = dateFormat.format(fecha);

        File folder = new File("reportes/" + ord.getIdOrden());
        folder.mkdirs();
        PdfReader reader = new PdfReader("imagenes/PlantillaHojaAsignacion.pdf");
        PdfStamper stamp = new PdfStamper(reader,
                new FileOutputStream("reportes/" + ord.getIdOrden() + "/" + valor + "-HojaAsignacion.pdf"));
        PdfContentByte cb = stamp.getUnderContent(1);
        AcroFields fdfDoc = stamp.getAcroFields();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);

        cb.beginText();
        fdfDoc.setField("orden", String.valueOf(ord.getIdOrden()));

        if (ord.getCompania() != null)
            fdfDoc.setField("compania", ord.getCompania().getNombre());
        else
            fdfDoc.setField("compania", "");

        if (ord.getSiniestro() != null)
            fdfDoc.setField("siniestro", ord.getSiniestro());
        else
            fdfDoc.setField("siniestro", "");

        if (ord.getPoliza() != null)
            fdfDoc.setField("poliza", ord.getPoliza());
        else
            fdfDoc.setField("poliza", "");
        if (ord.getFecha() != null)
            fdfDoc.setField("apertura", ord.getFecha().toString());
        else
            fdfDoc.setField("apertura", "");
        if (ord.getFechaSiniestro() != null)
            fdfDoc.setField("f_siniestro", ord.getFechaSiniestro().toString());
        else
            fdfDoc.setField("f_siniestro", "");
        if (ord.getInciso() != null)
            fdfDoc.setField("inciso", ord.getInciso());
        else
            fdfDoc.setField("inciso", "");

        if (ord.getTipo() != null)
            fdfDoc.setField("unidad", ord.getTipo().getTipoNombre());
        else
            fdfDoc.setField("unidad", "");
        if (ord.getModelo() != null)
            fdfDoc.setField("modelo", ord.getModelo().toString());
        else
            fdfDoc.setField("modelo", "");
        if (ord.getMarca() != null)
            fdfDoc.setField("marca", ord.getMarca().getMarcaNombre());
        else
            fdfDoc.setField("marca", "");
        if (ord.getNoEconomico() != null)
            fdfDoc.setField("economico", ord.getNoEconomico());
        else
            fdfDoc.setField("economico", "");
        if (ord.getNoMotor() != null)
            fdfDoc.setField("no_motor", ord.getNoMotor());
        else
            fdfDoc.setField("no_motor", "");
        if (ord.getNoSerie() != null)
            fdfDoc.setField("no_serie", ord.getNoSerie());
        else
            fdfDoc.setField("no_serie", "");

        //tabla 
        if (ord.getEmpleadoByRHojalateria() != null)
            fdfDoc.setField("HOJALATERIA", ord.getEmpleadoByRHojalateria().getIdEmpleado().toString());
        else
            fdfDoc.setField("HOJALATERIA", "");
        if (ord.getEmpleadoByRHojalateria() != null)
            fdfDoc.setField("R_H", ord.getEmpleadoByRHojalateria().getNombre().toString());
        else
            fdfDoc.setField("R_H", "");

        if (ord.getEmpleadoByRMecanica() != null)
            fdfDoc.setField("MECANICA", ord.getEmpleadoByRMecanica().getIdEmpleado().toString());
        else
            fdfDoc.setField("MECANICA", "");
        if (ord.getEmpleadoByRMecanica() != null)
            fdfDoc.setField("R_M", ord.getEmpleadoByRMecanica().getNombre().toString());
        else
            fdfDoc.setField("R_M", "");

        if (ord.getEmpleadoByRSuspension() != null)
            fdfDoc.setField("SUSPENSIN", ord.getEmpleadoByRSuspension().getIdEmpleado().toString());
        else
            fdfDoc.setField("SUSPENSIN", "");
        if (ord.getEmpleadoByRSuspension() != null)
            fdfDoc.setField("R_S", ord.getEmpleadoByRSuspension().getNombre().toString());
        else
            fdfDoc.setField("R_S", "");

        if (ord.getEmpleadoByRElectrico() != null)
            fdfDoc.setField("ELECTRICO", ord.getEmpleadoByRElectrico().getIdEmpleado().toString());
        else
            fdfDoc.setField("ELECTRICO", "");

        if (ord.getEmpleadoByRElectrico() != null)
            fdfDoc.setField("R_E", ord.getEmpleadoByRElectrico().getNombre().toString());
        else
            fdfDoc.setField("R_E", "");

        if (ord.getEmpleadoByRPintura() != null)
            fdfDoc.setField("PINTURA", ord.getEmpleadoByRPintura().getIdEmpleado().toString());
        else
            fdfDoc.setField("PINTURA", "");
        if (ord.getEmpleadoByRPintura() != null)
            fdfDoc.setField("R_P", ord.getEmpleadoByRPintura().getNombre().toString());
        else
            fdfDoc.setField("R_P", "");

        //FECHAS
        String valor1 = "";
        if (ord.getRHojalateriaFecha() != null) {
            fecha1 = ord.getRHojalateriaFecha();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_H", valor1);
        } else {
            fdfDoc.setField("F_H", valor1);
        }
        if (ord.getRMecanicaFecha() != null) {
            fecha1 = ord.getRMecanicaFecha();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_M", valor1);
        } else {
            fdfDoc.setField("F_M", valor1);
        }
        if (ord.getRSuspensionFecha() != null) {
            fecha1 = ord.getRSuspensionFecha();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_S", valor1);
        } else {
            fdfDoc.setField("F_S", valor1);
        }
        if (ord.getRElectricoFecha() != null) {
            fecha1 = ord.getRElectricoFecha();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_E", valor1);
        } else {
            fdfDoc.setField("F_E", valor1);
        }
        if (ord.getRPinturaFecha() != null) {
            fecha1 = ord.getRPinturaFecha();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_P", valor1);
        } else {
            fdfDoc.setField("F_P", valor1);
        }
        //ASIGNO OPERARIO
        if (ord.getUsuarioByRHojalateriaAsigno() != null)
            fdfDoc.setField("A_H", ord.getUsuarioByRHojalateriaAsigno().getIdUsuario());
        else
            fdfDoc.setField("A_H", "");

        if (ord.getUsuarioByRMecanicaAsigno() != null)
            fdfDoc.setField("A_M", ord.getUsuarioByRMecanicaAsigno().getIdUsuario());
        else
            fdfDoc.setField("A_M", "");
        if (ord.getUsuarioByRSuspensionAsigno() != null)
            fdfDoc.setField("A_S", ord.getUsuarioByRSuspensionAsigno().getIdUsuario());
        else
            fdfDoc.setField("A_S", "");
        if (ord.getUsuarioByRElectricoAsigno() != null)
            fdfDoc.setField("A_E", ord.getUsuarioByRElectricoAsigno().getIdUsuario());
        else
            fdfDoc.setField("A_E", "");

        if (ord.getUsuarioByRPinturaAsigno() != null)
            fdfDoc.setField("A_P", ord.getUsuarioByRPinturaAsigno().getIdUsuario());
        else
            fdfDoc.setField("A_P", "");
        //LIMITE
        if (ord.getHojalateriaLimite() != null) {
            fecha1 = ord.getHojalateriaLimite();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_H_L", valor1);
        } else {
            fdfDoc.setField("F_H_L", "");
        }
        if (ord.getMecanicaLimite() != null) {
            fecha1 = ord.getMecanicaLimite();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_M_L", valor1);
        } else {
            fdfDoc.setField("F_M_L", "");
        }
        if (ord.getSuspensionLimite() != null) {
            fecha1 = ord.getSuspensionLimite();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_S_L", valor1);
        } else {
            fdfDoc.setField("F_S_L", "");
        }
        if (ord.getElectricoLimite() != null) {
            fecha1 = ord.getElectricoLimite();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_E_L", valor1);
        } else {
            fdfDoc.setField("F_E_L", "");
        }
        if (ord.getPinturaLimite() != null) {
            fecha1 = ord.getPinturaLimite();
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            valor1 = dateFormat.format(fecha1);
            fdfDoc.setField("F_P_L", valor1);
        } else {
            fdfDoc.setField("F_P_L", "");
        }

        Foto[] fotos = (Foto[]) ord.getFotos().toArray(new Foto[0]);
        for (int k = 0; k < fotos.length - 1; k++) {
            for (int f = 0; f < (fotos.length - 1) - k; f++) {
                if (fotos[f].getFecha().after(fotos[f + 1].getFecha()) == true) {
                    Foto aux;
                    aux = fotos[f];
                    fotos[f] = fotos[f + 1];
                    fotos[f + 1] = aux;
                }
            }
        }
        if (fotos.length > 0) {
            try {
                Image img;
                img = Image
                        .getInstance("ordenes/" + ord.getIdOrden() + "/miniatura/" + fotos[0].getDescripcion());
                img.setAbsolutePosition(30, 495);
                img.scaleAbsoluteWidth(124);
                img.scaleAbsoluteHeight(80);
                cb.addImage(img, true);
            } catch (Exception e) {
                //e.printStackTrace();
            }
        } else {
        }

        cb.endText();
        stamp.close();

        PDF reporte = new PDF();
        reporte.cerrar();
        reporte.visualizar("reportes/" + ord.getIdOrden() + "/" + valor + "-HojaAsignacion.pdf");
    } catch (Exception e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(this, "No se pudo realizar el reporte si el archivo esta abierto");
    }
    if (session != null)
        if (session.isOpen())
            session.close();
}

From source file:org.alfresco.extension.countersign.action.executer.PDFAddSignatureFieldActionExecuter.java

License:Open Source License

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef,
 * org.alfresco.service.cmr.repository.NodeRef)
 *//*ww  w  .j  a  va2  s  .c o m*/
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {

    NodeService ns = serviceRegistry.getNodeService();
    if (ns.exists(actionedUponNodeRef) == false) {
        // node doesn't exist - can't do anything
        return;
    }

    String fieldName = (String) ruleAction.getParameterValue(PARAM_FIELDNAME);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);

    JSONObject box;
    int page = -1;

    // parse out the position JSON
    JSONObject positionObj = null;

    try {
        positionObj = (JSONObject) parser.parse(position);
    } catch (ParseException e) {
        logger.error("Could not parse position JSON from Share");
        throw new AlfrescoRuntimeException("Could not parse position JSON from Share");
    }

    // get the page
    page = Integer.parseInt(String.valueOf(positionObj.get("page")));

    // get the box
    box = (JSONObject) positionObj.get("box");

    try {
        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());
        OutputStream cos = serviceRegistry.getContentService()
                .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream();

        PdfStamper stamp = new PdfStamper(reader, cos);

        // does a field with this name already exist?
        AcroFields allFields = stamp.getAcroFields();

        // if this doc is already signed, cannot add a new sig field without 
        if (allFields.getSignatureNames() != null && allFields.getSignatureNames().size() > 0) {
            throw new AlfrescoRuntimeException("This document has signatures applied, "
                    + "adding a new signature field would invalidate existing signatures");
        }

        // cant create duplicate field names
        if (allFields.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE) {
            throw new AlfrescoRuntimeException(
                    "A signature field named " + fieldName + " already exists in this document");
        }

        // create the signature field
        Rectangle pageRect = reader.getPageSizeWithRotation(page);
        Rectangle sigRect = positionBlock(pageRect, box);
        PdfFormField sigField = stamp.addSignature(fieldName, page, sigRect.getLeft(), sigRect.getBottom(),
                sigRect.getRight(), sigRect.getTop());

        // style the field (no borders)
        sigField.setBorder(new PdfBorderArray(0, 0, 0));
        sigField.setBorderStyle(new PdfBorderDictionary(0, PdfBorderDictionary.STYLE_SOLID));
        allFields.regenerateField(fieldName);

        // apply the change and close streams
        stamp.close();
        reader.close();
        cos.close();

        // once the signature field has been added, apply the sig field aspect
        if (!ns.hasAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE)) {
            ns.addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE, null);
        }

        // now update the signature fields metadata
        Serializable currentFields = ns.getProperty(actionedUponNodeRef,
                CounterSignSignatureModel.PROP_SIGNATUREFIELDS);
        ArrayList<String> fields = new ArrayList<String>();

        if (currentFields != null) {
            fields.addAll((List<String>) currentFields);
        }

        fields.add(fieldName);
        ns.setProperty(actionedUponNodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS, fields);
    } catch (IOException ioex) {
        throw new AlfrescoRuntimeException(ioex.getMessage());
    } catch (DocumentException dex) {
        throw new AlfrescoRuntimeException(dex.getMessage());
    }
}

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

License:Open Source License

public byte[] generate() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*  w  w w  . j a va 2  s.co 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();
}