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

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

Introduction

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

Prototype

public void setFormFlattening(final boolean flat) 

Source Link

Document

Determines if the fields are flattened on close.

Usage

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

License:Open Source License

@Override
public void flattenPdf(InputStream srcPdf, OutputStream destPdf) throws IOException {
    PdfProcessor processor = new PdfProcessor(srcPdf, destPdf) {
        @Override//from   w ww  .jav a 2 s. co m
        void handleProcessing(PdfReader reader, PdfStamper stamper) throws IOException, DocumentException {
            if (isXfaForm(reader)) {
                throw new IllegalArgumentException("Does not support XFA form.");
            } else {
                stamper.setFormFlattening(true);
                stamper.close();
            }
        }
    };
    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  a  v  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:om.edu.squ.squportal.portlet.tsurvey.dao.pdf.TeachingSurveyPdfImpl.java

License:Open Source License

/**
 * //from  www .  j av a 2s .c  o 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:org.roda.common.certification.PDFSignatureUtils.java

public static void runDigitalSignatureStrip(Path input, Path output) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(input.toString());
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(output.toString()));
    stamper.setFormFlattening(true);
    stamper.close();/*ww  w .j  a v  a2s .  co m*/
    reader.close();
}

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";
    }// www  . j  a v  a  2s  .c om

    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:org.smap.sdal.managers.PDFSurveyManager.java

License:Open Source License

public String createPdf(OutputStream outputStream, String basePath, String serverRoot, String remoteUser,
        String language, boolean generateBlank, String filename, boolean landscape, // Set true if landscape
        HttpServletResponse response) throws Exception {

    if (language != null) {
        language = language.replace("'", "''"); // Escape apostrophes
    } else {//  w ww  . ja  v a  2 s. c  o  m
        language = "none";
    }

    mExcludeEmpty = survey.exclude_empty;

    User user = null;

    ServerManager serverManager = new ServerManager();
    ServerData serverData = serverManager.getServer(sd, localisation);

    UserManager um = new UserManager(localisation);
    int[] repIndexes = new int[20]; // Assume repeats don't go deeper than 20 levels

    Document document = null;
    PdfWriter writer = null;
    PdfReader reader = null;
    PdfStamper stamper = null;

    try {

        // 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");
            FontFactory.register("/Library/Fonts/NotoSans-Bold.ttf", "notosansbold");
            FontFactory.register("/Library/Fonts/NotoSansBengali-Regular.ttf", "bengali");
            FontFactory.register("/Library/Fonts/NotoSansBengali-Bold.ttf", "bengalibold");
        } 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/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Bold.ttf", "notosansbold");
            FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Regular.ttf", "bengali");
            FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Bold.ttf", "bengalibold");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFontLink = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("notosans", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        defaultFontBold = FontFactory.getFont("notosansbold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        arabicFont = FontFactory.getFont("arabic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        bengaliFont = FontFactory.getFont("bengali", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        bengaliFontBold = FontFactory.getFont("bengalibold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        defaultFontLink.setColor(BaseColor.BLUE);

        /*
         * Get the results and details of the user that submitted the survey
         */

        log.info("User Ident who submitted the survey: " + survey.instance.user);
        String userName = survey.instance.user;
        if (userName == null) {
            userName = remoteUser;
        }
        if (userName != null) {
            user = um.getByIdent(sd, userName);
        }

        // If a filename was not specified then get one from the survey data
        // This filename is returned to the calling program so that it can be used as a permanent name for the temporary file created here
        // If the PDF is to be returned in an http response then the header is set now before writing to the output stream
        log.info("Filename passed to createPDF is: " + filename);
        if (filename == null) {
            filename = survey.getInstanceName() + ".pdf";
        } else {
            if (!filename.endsWith(".pdf")) {
                filename += ".pdf";
            }
        }

        // 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);
            GeneralUtilityMethods.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
         */
        File templateFile = GeneralUtilityMethods.getPdfTemplate(basePath, survey.displayName, survey.p_id);

        /*
         * Get dependencies between Display Items, for example if a question result should be added to another
         *  question's results
         */
        GlobalVariables gv = new GlobalVariables();
        if (!generateBlank) {
            for (int i = 0; i < survey.instance.results.size(); i++) {
                getDependencies(gv, survey.instance.results.get(i), survey, i);
            }
        }
        gv.mapbox_key = serverData.mapbox_default;
        int oId = GeneralUtilityMethods.getOrganisationId(sd, remoteUser);

        languageIdx = GeneralUtilityMethods.getLanguageIdx(survey, language);
        if (templateFile.exists()) {

            log.info("PDF Template Exists");
            String templateName = templateFile.getAbsolutePath();

            reader = new PdfReader(templateName);
            stamper = new PdfStamper(reader, outputStream);

            for (int i = 0; i < survey.instance.results.size(); i++) {
                fillTemplate(gv, stamper.getAcroFields(), survey.instance.results.get(i), basePath, null, i,
                        serverRoot, stamper, oId);
            }
            if (user != null) {
                fillTemplateUserDetails(stamper.getAcroFields(), user, basePath);
            }
            stamper.setFormFlattening(true);

        } else {
            log.info("++++No template exists creating a pdf file programmatically");

            /*
             * Create a PDF without the stationary
             * If we need to add a letter head then create document in two passes, the second pass adds the letter head
             * Else just create the document directly in a single pass
             */
            Parser parser = getXMLParser();

            // Step 1 - Create the underlying document as a byte array
            if (landscape) {
                document = new Document(PageSize.A4.rotate());
            } else {
                document = new Document(PageSize.A4);
            }
            document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
            writer = PdfWriter.getInstance(document, outputStream);

            writer.setInitialLeading(12);

            writer.setPageEvent(new PdfPageSizer(survey.displayName, survey.projectName, user, basePath, null,
                    marginLeft, marginRight, marginTop_2, marginBottom_2));
            document.open();

            // If this form has data maintain a list of parent records to lookup ${values}
            ArrayList<ArrayList<Result>> parentRecords = null;
            if (!generateBlank) {
                parentRecords = new ArrayList<ArrayList<Result>>();
            }

            for (int i = 0; i < survey.instance.results.size(); i++) {
                processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot,
                        generateBlank, 0, i, repIndexes, gv, false, parentRecords, remoteUser, oId);
            }

            fillNonTemplateUserDetails(document, user, basePath);

            // Add appendix
            if (gv.hasAppendix) {
                document.newPage();
                document.add(new Paragraph("Appendix", defaultFontBold));

                for (int i = 0; i < survey.instance.results.size(); i++) {
                    processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot,
                            generateBlank, 0, i, repIndexes, gv, true, parentRecords, remoteUser, oId);
                }
            }

        }

    } finally {
        if (document != null)
            try {
                document.close();
            } catch (Exception e) {
            }
        ;
        if (writer != null)
            try {
                writer.close();
            } catch (Exception e) {
            }
        ;
        if (stamper != null)
            try {
                stamper.close();
            } catch (Exception e) {
            }
        ;
        if (reader != null)
            try {
                reader.close();
            } catch (Exception e) {
            }
        ;
    }

    return filename;

}

From source file:PdfFormFiller.WrongParamsExeption.java

License:GNU General Public License

public static void fillPDFFile(String pdf_filename_in, String pdf_filename_out, String fields_filename,
        String font_file, String op, Boolean flatten, Boolean verbose) {
    OutputStream os;//from  w ww .  j  a  v  a  2  s  .com
    PdfStamper stamp;
    try {
        PdfReader reader = new PdfReader(pdf_filename_in);

        if (pdf_filename_out != null) {
            os = new FileOutputStream(pdf_filename_out);
        } else {
            os = System.out;
        }

        stamp = new PdfStamper(reader, os, '\0');

        AcroFields form = stamp.getAcroFields();

        if (op.equals("list")) {
            formList(form);
        } else {
            if (font_file != null) {
                BaseFont bf = BaseFont.createFont(font_file, BaseFont.IDENTITY_H, true);
                form.addSubstitutionFont(bf);
            }
            Map<String, String> fields = readFile(fields_filename);
            for (Map.Entry<String, String> entry : fields.entrySet()) {
                if (verbose)
                    System.out.println("Field name = '" + entry.getKey() + "', New field value: '"
                            + entry.getValue() + "'");
                form.setField(entry.getKey(), entry.getValue());
            }

            stamp.setFormFlattening(flatten);
            stamp.close();
        }
    } catch (FileNotFoundException e) {
        System.err.println("FileNotFoundException: " + e.getMessage());
        System.exit(2);
    } catch (IOException e) {
        System.err.println("Input output error: " + e.getMessage());
        System.exit(3);
    } catch (DocumentException e) {
        System.err.println("Error while processing document: " + e.getMessage());
        System.exit(4);
    }
}

From source file:se.inera.intyg.intygstyper.fk7263.pdf.PdfDefaultGenerator.java

License:Open Source License

protected PdfDefaultGenerator(Utlatande intyg, List<Status> statuses, ApplicationOrigin applicationOrigin,
        boolean flatten) throws PdfGeneratorException {
    try {//from   w  w w .j a v a  2 s.c  o  m
        this.intyg = intyg;

        outputStream = new ByteArrayOutputStream();

        PdfReader pdfReader = new PdfReader(PDF_TEMPLATE);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, this.outputStream);
        fields = pdfStamper.getAcroFields();
        generatePdf();

        switch (applicationOrigin) {
        case MINA_INTYG:
            // perform additional decoration for MI originated pdf
            maskSendToFkInformation(pdfStamper);
            markAsElectronicCopy(pdfStamper);
            createRightMarginText(pdfStamper, pdfReader.getNumberOfPages(), intyg.getId(),
                    MINA_INTYG_MARGIN_TEXT);
            break;
        case WEBCERT:
            // perform additional decoration for WC originated pdf
            if (isCertificateSentToFK(statuses)) {
                maskSendToFkInformation(pdfStamper);
                markAsElectronicCopy(pdfStamper);
            }
            createRightMarginText(pdfStamper, pdfReader.getNumberOfPages(), intyg.getId(), WEBCERT_MARGIN_TEXT);
            createSignatureNotRequiredField(pdfStamper, pdfReader.getNumberOfPages());
            break;
        default:
            break;
        }

        pdfStamper.setFormFlattening(flatten);
        pdfStamper.close();

    } catch (Exception e) {
        throw new PdfGeneratorException(e);
    }
}

From source file:se.inera.intyg.intygstyper.fk7263.pdf.PdfEmployeeGenerator.java

License:Open Source License

protected PdfEmployeeGenerator(Utlatande intyg, List<Status> statuses, ApplicationOrigin applicationOrigin,
        List<String> selectedOptionalFields, boolean flatten) throws PdfGeneratorException {
    try {/*from www . ja va 2 s .com*/
        this.intyg = intyg;

        outputStream = new ByteArrayOutputStream();

        PdfReader pdfReader = new PdfReader(PDF_TEMPLATE);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, this.outputStream);
        fields = pdfStamper.getAcroFields();

        switch (applicationOrigin) {
        case MINA_INTYG:
            generateMIPdfWithOptionalFields(selectedOptionalFields);
            // perform additional decoration for MI originated pdf
            maskSendToFkInformation(pdfStamper);
            if (!EmployeeOptionalFields.containsAllValues(selectedOptionalFields)) {
                mark(pdfStamper, WATERMARK_TEXT_CONTENT_IS_CUSTOMIZED, MARK_AS_EMPLOYER_START_X,
                        MARK_AS_EMPLOYER_START_Y, MARK_AS_EMPLOYER_MI_HEIGHT, MARK_AS_EMPLOYER_MI_WIDTH);
            } else {
                markAsElectronicCopy(pdfStamper);
            }

            createRightMarginText(pdfStamper, pdfReader.getNumberOfPages(), intyg.getId(),
                    MINA_INTYG_MARGIN_TEXT);
            break;
        case WEBCERT:
            generateMinimalPdf();

            // perform additional decoration for WC originated pdf
            maskSendToFkInformation(pdfStamper);
            mark(pdfStamper, WATERMARK_TEXT_WC_EMPLOYER_MINIMAL_COPY, MARK_AS_EMPLOYER_START_X,
                    MARK_AS_EMPLOYER_START_Y, MARK_AS_EMPLOYER_WC_HEIGTH, MARK_AS_EMPLOYER_WC_WIDTH);

            createRightMarginText(pdfStamper, pdfReader.getNumberOfPages(), intyg.getId(), WEBCERT_MARGIN_TEXT);
            break;
        default:
            break;
        }

        createSignatureNotRequiredField(pdfStamper, pdfReader.getNumberOfPages());
        pdfStamper.setFormFlattening(flatten);
        pdfStamper.close();

    } catch (Exception e) {
        throw new PdfGeneratorException(e);
    }
}

From source file:se.inera.intyg.intygstyper.ts_bas.pdf.PdfGeneratorImpl.java

License:Open Source License

@Override
public byte[] generatePDF(Utlatande utlatande, ApplicationOrigin applicationOrigin)
        throws PdfGeneratorException {
    try {//from  w  w  w .  j ava2 s  . c  o m
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        PdfReader pdfReader = new PdfReader(getPdfPath(utlatande));
        PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
        pdfStamper.setFormFlattening(formFlattening);
        AcroFields fields = pdfStamper.getAcroFields();
        populatePdfFields(utlatande, fields, applicationOrigin);

        // Decorate PDF depending on the origin of the pdf-call
        switch (applicationOrigin) {
        case MINA_INTYG:
            createLeftMarginText(pdfStamper, pdfReader.getNumberOfPages(), utlatande.getId(),
                    MINA_INTYG_MARGIN_TEXT);
            break;
        case WEBCERT:
            createLeftMarginText(pdfStamper, pdfReader.getNumberOfPages(), utlatande.getId(),
                    WEBCERT_MARGIN_TEXT);
            break;
        default:
            break;
        }

        pdfStamper.close();

        return outputStream.toByteArray();

    } catch (Exception e) {
        throw new PdfGeneratorException(e);
    }
}