Example usage for com.itextpdf.text.pdf PdfWriter setPageEvent

List of usage examples for com.itextpdf.text.pdf PdfWriter setPageEvent

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter setPageEvent.

Prototype


public void setPageEvent(final PdfPageEvent event) 

Source Link

Document

Sets the PdfPageEvent for this document.

Usage

From source file:org.me.modelos.PDFHelper.java

public void tablaToPdf(JTable jTable, File pdfNewFile, String title) {
    try {//from   www  . j  a  va  2s . c o  m
        Font subCategoryFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
        Document document = new Document(PageSize.LETTER.rotate());
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile));
        } catch (FileNotFoundException fileNotFoundException) {
            Message.showErrorMessage(fileNotFoundException.getMessage());
        }

        writer.setBoxSize("art", new Rectangle(150, 10, 700, 580));
        writer.setPageEvent(new HeaderFooterPageEvent());
        document.open();
        document.addTitle(title);

        document.addSubject("Reporte");
        document.addKeywords("reportes, gestion, pdf");
        document.addAuthor("Gestion de Proyectos de software");
        document.addCreator("gestion de proyectos");

        Paragraph parrafo = new Paragraph(title, subCategoryFont);

        PdfPTable table = new PdfPTable(jTable.getColumnCount());
        table.setWidthPercentage(100);
        PdfPCell columnHeader;

        for (int column = 0; column < jTable.getColumnCount(); column++) {
            Font font = new Font(Font.FontFamily.HELVETICA);
            font.setColor(255, 255, 255);
            columnHeader = new PdfPCell(new Phrase(jTable.getColumnName(column), font));
            columnHeader.setHorizontalAlignment(Element.ALIGN_LEFT);
            columnHeader.setBackgroundColor(new BaseColor(96, 125, 139));
            table.addCell(columnHeader);
        }
        table.getDefaultCell().setBackgroundColor(new BaseColor(255, 255, 255));
        table.setHeaderRows(1);
        BaseColor verdad = new BaseColor(255, 255, 255);
        BaseColor falso = new BaseColor(214, 230, 244);
        boolean bandera = false;
        for (int row = 0; row < jTable.getRowCount(); row++) {

            for (int column = 0; column < jTable.getColumnCount(); column++) {

                if (bandera) {
                    table.getDefaultCell().setBackgroundColor(verdad);
                } else {
                    table.getDefaultCell().setBackgroundColor(falso);
                }
                table.addCell(jTable.getValueAt(row, column).toString());
                bandera = !bandera;
            }

        }

        parrafo.add(table);
        document.add(parrafo);
        document.close();
        //JOptionPane.showMessageDialog(null, "Se ha creado el pdf en " + pdfNewFile.getPath(),
        //        "RESULTADO", JOptionPane.INFORMATION_MESSAGE);
    } catch (DocumentException documentException) {
        System.out.println("Se ha producido un error " + documentException);
        JOptionPane.showMessageDialog(null, "Se ha producido un error" + documentException, "ERROR",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.openmrs.module.laboratorymanagement.db.hibernate.LaboratoryDAOimpl.java

License:Open Source License

public void exportPatientReportToPDF(HttpServletRequest request, HttpServletResponse response,
        Map<ConceptName, List<Object[]>> mappedLabExam, String filename, String title, int patientId)
        throws DocumentException, IOException {

    Document document = new Document();
    Patient patient = Context.getPatientService().getPatient(patientId);
    // List<PatientBill> patientBills =
    // (List<PatientBill>)request.getAttribute("reportedPatientBillsPrint");

    /*//w  ww.  j a  va 2 s.c  o  m
     * PatientBill pb = null;
     * 
     * pb = Context.getService(BillingService.class).getPatientBill(
     * Integer.parseInt(request.getParameter("patientBills")));
     */
    /*
     * String filename = pb.getBeneficiary().getPatient().getPersonName()
     * .toString().replace(" ", "_"); filename =
     * pb.getBeneficiary().getPolicyIdNumber().replace(" ", "_") + "_" +
     * filename + ".pdf";
     */
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "report"); // file name

    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    writer.setBoxSize("art", new Rectangle(0, 0, 2382, 3369));
    writer.setBoxSize("art", PageSize.A4);

    HeaderFooterMgt event = new HeaderFooterMgt();
    writer.setPageEvent(event);

    document.open();
    document.setPageSize(PageSize.A4);
    // document.setPageSize(new Rectangle(0, 0, 2382, 3369));

    document.addAuthor(Context.getAuthenticatedUser().getPersonName().toString());// the name of the author

    FontSelector fontTitle = new FontSelector();
    fontTitle.addFont(new Font(FontFamily.COURIER, 10.0f, Font.ITALIC));

    // Report title
    Chunk chk = new Chunk("Printed on : " + (new SimpleDateFormat("dd-MMM-yyyy").format(new Date())));
    chk.setFont(new Font(FontFamily.COURIER, 10.0f, Font.BOLD));
    Paragraph todayDate = new Paragraph();
    todayDate.setAlignment(Element.ALIGN_RIGHT);
    todayDate.add(chk);
    document.add(todayDate);
    document.add(fontTitle.process("REPUBLIQUE DU RWANDA\n"));
    document.add(fontTitle.process("POLICE NATIONALE\n"));
    document.add(fontTitle.process("KACYIRU POLICE HOSPITAL\n"));
    document.add(fontTitle.process("B.P. 6183 KIGALI\n"));
    document.add(fontTitle.process("Tl : 584897\n"));
    document.add(fontTitle.process("E-mail : medical@police.gov.rw"));
    // End Report title

    document.add(new Paragraph("\n"));
    chk = new Chunk("Laboratory results");
    chk.setFont(new Font(FontFamily.COURIER, 10.0f, Font.BOLD));
    chk.setUnderline(0.2f, -2f);
    Paragraph pa = new Paragraph();
    pa.add(chk);
    pa.setAlignment(Element.ALIGN_CENTER);
    document.add(pa);
    document.add(new Paragraph("\n"));

    document.add(fontTitle.process("Family Name: " + patient.getFamilyName() + "\n"));
    document.add(fontTitle.process("Given name: " + patient.getGivenName() + "\n"));
    document.add(fontTitle.process("Age: " + patient.getAge() + "\n"));

    // title row
    FontSelector fontTitleSelector = new FontSelector();
    fontTitleSelector.addFont(new Font(FontFamily.COURIER, 9, Font.ITALIC));
    // Table of identification;
    PdfPTable table = null;
    table = new PdfPTable(2);
    table.setWidthPercentage(100f);

    // tableHeader.addCell(table);

    // document.add(tableHeader);

    document.add(new Paragraph("\n"));

    // Table of lab report items;
    float[] colsWidth = { 6f, 3f, 6f };
    table = new PdfPTable(colsWidth);
    table.setWidthPercentage(100f);
    BaseColor bckGroundTitle = new BaseColor(170, 170, 170);
    BaseColor bckGroundTitl = new BaseColor(Color.yellow);

    // table Header
    PdfPCell cell = new PdfPCell(fontTitleSelector.process("Exam"));

    cell.setBackgroundColor(bckGroundTitle);

    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process("Result"));
    cell.setBackgroundColor(bckGroundTitle);

    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process("Normal Range"));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);
    /*
     * cell = new PdfPCell(fontTitleSelector.process("Date "));
     * cell.setBackgroundColor(bckGroundTitle); table.addCell(cell);
     */

    // normal row
    FontSelector fontselector = new FontSelector();
    fontselector.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

    // empty row
    FontSelector fontTotals = new FontSelector();
    fontTotals.addFont(new Font(FontFamily.COURIER, 9, Font.BOLD));

    // ===========================================================
    for (ConceptName cptName : mappedLabExam.keySet()) {

        cell = new PdfPCell(fontTitleSelector.process("" + cptName));
        cell.setBackgroundColor(bckGroundTitl);

        table.addCell(cell);
        cell = new PdfPCell(fontTitleSelector.process(""));
        table.addCell(cell);
        cell = new PdfPCell(fontTitleSelector.process(""));
        table.addCell(cell);

        List<Object[]> labExamHistory = mappedLabExam.get(cptName);
        for (Object[] labExam : labExamHistory) {
            // table Header
            // Object[] labe = listOflabtest.get(i);
            Obs ob = (Obs) labExam[0];
            cell = new PdfPCell(fontTitleSelector.process("" + ob.getConcept().getName()));

            table.addCell(cell);
            if (ob.getConcept().getDatatype().isNumeric()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueNumeric()));
                table.addCell(cell);

            }

            if (ob.getConcept().getDatatype().isCoded()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueCoded().getName()));
                table.addCell(cell);

            }

            if (ob.getConcept().getDatatype().isText()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueText()));
                table.addCell(cell);

            }

            cell = new PdfPCell(fontTitleSelector.process("" + (labExam[1] != null ? labExam[1] : "-")));
            table.addCell(cell);

            fontselector.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

            // empty row
            // FontSelector fontTotals = new FontSelector();
            fontTotals.addFont(new Font(FontFamily.COURIER, 9, Font.BOLD));

        }

    }

    cell = new PdfPCell(fontTitleSelector.process("Names, Signature et Stamp of Lab Chief\n"
            //+ Context.getAuthenticatedUser().getPersonName()));
            + Context.getUserService().getUser(140).getPersonName()));

    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);
    // ================================================================
    table.addCell(cell);

    document.add(table);

    // Table of signatures;
    table = new PdfPTable(2);
    table.setWidthPercentage(100f);

    cell = new PdfPCell(fontTitleSelector.process(" "));

    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(
            "Names, Signature and  Stamp of Provider\n" + Context.getAuthenticatedUser().getPersonName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);
    document.add(table);
    document.close();

    document.close();
}

From source file:org.openmrs.module.mohtracportal.util.FileExporter.java

License:Open Source License

/**
 * @param request/*from www  .  j  av  a2  s  .  co m*/
 * @param response
 * @param res
 * @param filename
 * @param title
 * @param from
 * @param to
 * @param selectedUsers
 * @throws Exception
 */
public void exportToPDF(HttpServletRequest request, HttpServletResponse response, List<Object> res,
        String filename, String title, String from, String to, List<Integer> selectedUsers) throws Exception {
    SimpleDateFormat sdf = Context.getDateFormat();
    Document document = new Document();

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); // file name

    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    HeaderFooter event = new HeaderFooter();
    writer.setPageEvent(event);

    document.open();
    document.setPageSize(PageSize.A4);

    document.addAuthor(Context.getAuthenticatedUser().getPersonName().getFamilyName() + " "
            + Context.getAuthenticatedUser().getPersonName().getGivenName());// the name of the author

    PersonService ps = Context.getPersonService();

    String users = "";
    for (Integer usrId : selectedUsers) {
        users += ps.getPerson(usrId).getPersonName() + "; ";
    }

    FontSelector fontTitle = new FontSelector();
    fontTitle.addFont(new Font(FontFamily.COURIER, 10.0f, Font.BOLD));

    title = MohTracUtil.getMessage("mohtracportal.report.title", null) + "      : " + title;
    String underLine = "";
    int count = 0;
    while (count < title.length()) {
        count += 1;
        underLine += "_";
    }

    document.add(fontTitle.process(title));// Report title
    if (from.trim().compareTo("") != 0)
        document.add(fontTitle
                .process("\n" + MohTracUtil.getMessage("mohtracportal.from", null) + "      : " + from));// from
    if (to.trim().compareTo("") != 0)
        document.add(
                fontTitle.process("\n" + MohTracUtil.getMessage("mohtracportal.to", null) + "        : " + to));// to
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("mohtracportal.report.created.on", null)
            + " : " + sdf.format(new Date())));// Report date
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("mohtracportal.report.created.by", null)
            + " : " + Context.getAuthenticatedUser().getPersonName()));// Report
    // author

    Integer numberOfPatients = res.size();
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("mohtracportal.numberOfPatients", null) + " : "
            + numberOfPatients.toString()));// Number of patients

    if (users.trim().compareTo("") != 0)
        document.add(fontTitle.process(
                "\n" + MohTracUtil.getMessage("mohtracportal.patient.enterers", null) + " : " + users));// enterer(s)
    document.add(fontTitle.process("\n" + underLine));// Report title
    document.add(new Paragraph("\n\n"));

    boolean hasPrivToViewPatientNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

    // PdfLine line;
    PdfPTable table = null;
    if (hasPrivToViewPatientNames == true) {
        float[] colsWidth = { 1.2f, 5f, 2.7f, 2.7f, 4.2f, 2.7f };
        table = new PdfPTable(colsWidth);
    } else {
        float[] colsWidth = { 1.2f, 2.7f, 2.7f, 4.2f, 2.7f };
        table = new PdfPTable(colsWidth);
    }

    // column number
    table.setTotalWidth(540f);

    // title row
    FontSelector fontTitleSelector = new FontSelector();
    fontTitleSelector.addFont(new Font(FontFamily.COURIER, 9, Font.BOLD));
    BaseColor bckGroundTitle = new BaseColor(170, 170, 170);

    // table Header
    PdfPCell cell = new PdfPCell(
            fontTitleSelector.process(MohTracUtil.getMessage("mohtracportal.report.list.no", null)));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    if (hasPrivToViewPatientNames) {
        cell = new PdfPCell(
                fontTitleSelector.process(MohTracUtil.getMessage("mohtracportal.patient.names", null)));
        cell.setBackgroundColor(bckGroundTitle);
        table.addCell(cell);
    }

    cell = new PdfPCell(fontTitleSelector.process(MohTracPortalTag
            .getIdentifierTypeNameByIdAsString("" + MohTracConfigurationUtil.getTracNetIdentifierTypeId())));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(MohTracPortalTag.getIdentifierTypeNameByIdAsString(
            "" + MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId())));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(MohTracUtil.getMessage("mohtracportal.patient.date.created", null) + "("
                    + Context.getDateFormat().toPattern() + ")"));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(MohTracUtil.getMessage("mohtracportal.numberOfEncounters", null)));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    // normal row
    FontSelector fontselector = new FontSelector();
    fontselector.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

    // empty row
    FontSelector fontEmptyCell = new FontSelector();
    fontEmptyCell.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

    int ids = 0;

    for (Object patient : res) {
        Object[] o = (Object[]) patient;
        ids += 1;

        cell = new PdfPCell(fontselector.process(ids + ""));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);

        if (hasPrivToViewPatientNames) {
            String names = MohTracPortalTag.getPersonNames(Integer.valueOf(o[0].toString()));
            cell = new PdfPCell(fontselector.process(names + ""));
            if (names.compareTo("-") == 0)
                cell.setBackgroundColor(new BaseColor(224, 224, 240));
            if (o[2].toString().compareTo("1") == 0)
                cell.setBackgroundColor(new BaseColor(238, 238, 238));
            if (o[3].toString().compareTo("1") == 0)
                cell.setBackgroundColor(new BaseColor(224, 0, 0));
            table.addCell(cell);
        }

        String tracnetId = MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId(
                Integer.valueOf(o[0].toString()), MohTracConfigurationUtil.getTracNetIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(tracnetId + ""));
        if (tracnetId.compareTo("-") == 0)
            cell.setBackgroundColor(new BaseColor(224, 224, 240));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);

        String cohortId = MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId(
                Integer.valueOf(o[0].toString()),
                MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(cohortId + ""));
        if (cohortId.compareTo("-") == 0)
            cell.setBackgroundColor(new BaseColor(224, 224, 240));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);

        cell = new PdfPCell(fontselector.process(sdf.format(o[1]) + ""));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);

        String numberOfEncounters = MohTracPortalTag
                .getNumberOfEncounterByPatient(Integer.valueOf(o[0].toString()));
        cell = new PdfPCell(fontselector.process(numberOfEncounters + ""));
        if (numberOfEncounters.compareTo("-") == 0)
            cell.setBackgroundColor(new BaseColor(224, 224, 240));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);
    }

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

    log.info("pdf file created");
}

From source file:org.openmrs.module.tracpatienttransfer.util.FileExporter.java

License:Open Source License

/**
 * @param request//from   ww  w. ja  va 2  s .  c  o m
 * @param response
 * @param res
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToPDF(HttpServletRequest request, HttpServletResponse response, List<Integer> res,
        String filename, String title) throws Exception {

    SimpleDateFormat sdf = Context.getDateFormat();

    Document document = new Document();

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); // file name

    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    float[] colsWidth = { 1.6f, 2.7f, 2.7f, 8f, 10.5f, 4f, 5f, 7.5f };//, 9.3f };
    PdfPTable table = new PdfPTable(colsWidth); // column number

    HeaderFooter event = new HeaderFooter(table);
    writer.setPageEvent(event);

    document.setPageSize(PageSize.A4.rotate());
    document.open();

    document.addAuthor(Context.getAuthenticatedUser().getPersonName().getFamilyName() + " "
            + Context.getAuthenticatedUser().getPersonName().getGivenName());// the name of the author

    ObsService os = Context.getObsService();
    FontSelector fontTitle = new FontSelector();
    fontTitle.addFont(new Font(FontFamily.HELVETICA, 8.0f, Font.BOLD));
    document.add(
            fontTitle.process(MohTracUtil.getMessage("tracpatienttransfer.report", null) + "    : " + title));// Report title
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdon", null)
            + " : " + sdf.format(new Date())));// Report date
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdby", null)
            + " : " + Context.getAuthenticatedUser().getPersonName()));// Report
    // author
    document.add(new Paragraph("\n"));

    Paragraph para = new Paragraph("" + title.toUpperCase());
    para.setAlignment(Element.ALIGN_CENTER);
    para.setFont(new Font(FontFamily.HELVETICA, 8.0f, Font.BOLD));
    document.add(para);

    table.setWidthPercentage(100.0f);

    // title row
    FontSelector fontTitleSelector = new FontSelector();
    fontTitleSelector.addFont(new Font(FontFamily.HELVETICA, 8, Font.BOLD));

    // top line of table
    for (int i = 0; i < 8; i++) {
        PdfPCell pdfPCell = new PdfPCell(fontTitleSelector.process(" "));
        pdfPCell.setBorder(PdfPCell.BOTTOM);
        table.addCell(pdfPCell);
    }

    boolean hasRoleToViewPatientsNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

    // table Header
    PdfPCell cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.number")));
    cell.setBorder(Rectangle.LEFT);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(Context.getPatientService()
            .getPatientIdentifierType(TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
            .getName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(Context.getPatientService()
                    .getPatientIdentifierType(
                            TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                    .getName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    if (hasRoleToViewPatientsNames) {
        cell = new PdfPCell(
                fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.names")));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
    }

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.reasonofexit")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.exitwhen")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(ContextProvider.getMessage("Encounter.provider")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.report.location")));
    cell.setBorder(Rectangle.RIGHT);
    table.addCell(cell);

    //      cell = new PdfPCell(fontTitleSelector
    //            .process("Resumed? (reason - by who?)"));
    //      cell.setBorder(Rectangle.RIGHT);
    //      table.addCell(cell);

    // normal row
    FontSelector fontselector = new FontSelector();
    fontselector.addFont(new Font(FontFamily.HELVETICA, 7, Font.NORMAL));

    // empty row
    FontSelector fontEmptyCell = new FontSelector();
    fontEmptyCell.addFont(new Font(FontFamily.HELVETICA, 7, Font.NORMAL));

    int ids = 0;

    for (Integer obsId : res) {
        Obs obs = os.getObs(obsId);
        Integer patientId = obs.getPersonId();
        ids += 1;

        cell = new PdfPCell(fontselector.process(ids + "."));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        String tracnetId = TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(tracnetId + ""));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        String localIdentifierTypeId = TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(
                patientId, TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(localIdentifierTypeId + ""));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        if (hasRoleToViewPatientsNames) {
            String names = TransferOutInPatientTag.getPersonNames(patientId);
            cell = new PdfPCell(fontselector.process(names + ""));
            if (ids == 1)
                cell.setBorder(Rectangle.TOP);
            else
                cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }

        String conceptValue = TransferOutInPatientTag.conceptValueByObs(obs);

        conceptValue += ((obs.getValueCoded().getConceptId()
                .intValue() == TransferOutInPatientConstant.PATIENT_TRANSFERED_OUT)
                        ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                TransferOutInPatientConstant.TRANSFER_OUT_TO_A_LOCATION) + ")"
                        : (obs.getValueCoded().getConceptId()
                                .intValue() == TransferOutInPatientConstant.PATIENT_DEAD)
                                        ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                                TransferOutInPatientConstant.CAUSE_OF_DEATH) + ")"
                                        : "");

        cell = new PdfPCell(fontselector.process(conceptValue));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        cell = new PdfPCell(fontselector.process(sdf.format(obs.getObsDatetime())));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        /*
         * cell=newPdfPCell(fontselector.process(TransferOutInPatientTag.
         * getProviderByObs(obs))); if(ids==1)
         * cell.setBorder(Rectangle.TOP); else
         * cell.setBorder(Rectangle.NO_BORDER);
         */table.addCell(cell);

        cell = new PdfPCell(fontselector.process(obs.getLocation().getName()));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        //         cell = new PdfPCell(fontselector.process(TransferOutInPatientTag
        //               .obsVoidedReason(obs)));
        //         if (ids == 1)
        //            cell.setBorder(Rectangle.TOP);
        //         else
        //            cell.setBorder(Rectangle.NO_BORDER);
        //         table.addCell(cell);
    }

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

    log.info("pdf file created");
}

From source file:org.sharegov.cirm.utils.PDFViewReport.java

License:Apache License

public void generateReport(OutputStream out, List<Long> boids) {
    if (DBG)/*from  w ww  .j  a  v  a  2  s .com*/
        System.out.println("Start: PDFgenerateReport: for nrOfBoids: " + boids.size());
    Document doc = null;
    try {
        Date date = new Date();
        setTime(formatDate(date, true, false));
        doc = new Document(PageSize.A4);
        doc.setMargins(9, 9, doc.topMargin(), doc.bottomMargin());
        PdfWriter writer = PdfWriter.getInstance(doc, out);
        writer.setPageEvent(new TableHeader());
        doc.open();
        //addMetaData(doc);
        LegacyEmulator le = new LegacyEmulator();
        int i = 1;
        for (Long boid : boids) {
            ThreadLocalStopwatch.getWatch().time("PDFViewReport loading " + i + " of " + boids.size());
            Json data = le.findServiceCaseOntology(boid).toJSON();
            addContent(doc, data);
            i++;
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        doc.close();
    }
    if (DBG)
        System.out.println("Done: PDFgenerateReport: for nrOfBoids: " + boids.size());
}

From source file:org.sharegov.cirm.utils.PDFViewReport.java

License:Apache License

public void errorReport(OutputStream out) {
    if (DBG)//w  w  w  .j a  v  a2 s .c o  m
        System.out.println("Start: PDF errorReport");
    try {
        Date date = new Date();
        setTime(formatDate(date, true, false));
        Document doc = new Document(PageSize.A4);
        doc.setMargins(9, 9, doc.topMargin(), doc.bottomMargin());
        PdfWriter writer = PdfWriter.getInstance(doc, out);
        TableHeader th = new TableHeader();
        writer.setPageEvent(th);
        doc.open();

        Chapter chapter = new Chapter(new Paragraph(), 1);
        chapter.setNumberDepth(0);
        addSection(chapter).add(new Phrase(" "));
        addSection(chapter).add(new Phrase(" "));
        addSection(chapter).add(new Phrase(genericErrorMsg));
        doc.add(chapter);
        doc.close();
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    if (DBG)
        System.out.println("Done: PDF errorReport");
}

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";
    }//from  w  w  w  .  j a  v a  2 s. c  o m

    try {

        String filename;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        PdfPTable table = new PdfPTable(4);

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

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

        table.setHeaderRows(1);

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

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

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

            total += monthUsageInt;
            totalAllTime += allTimeInt;

        }

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

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

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

        if (stationaryFile.exists()) {

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

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

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

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

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

        }

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

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

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

}

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

License:Open Source License

public void createTasksPdf(Connection sd, OutputStream outputStream, String basePath,
        HttpServletRequest request, HttpServletResponse response, int tgId) {

    try {/*from  w ww.ja  v a  2s  .c  o m*/

        // 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");
        } 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);

        /*
         * Get the tasks for this task group
         */
        String urlprefix = request.getScheme() + "://" + request.getServerName();
        TaskManager tm = new TaskManager(localisation, tz);
        TaskListGeoJson t = tm.getTasks(sd, urlprefix, 0, tgId, 0, false, 0, null, "all", 0, 0, "scheduled",
                "desc");
        PdfWriter writer = null;

        String filename = "tasks.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);
            setFilenameInResponse(filename, response);
        }

        Document document = new Document(PageSize.A4);
        document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
        writer = PdfWriter.getInstance(document, outputStream);

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

        PdfPTable table = new PdfPTable(4);

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

        table.addCell("Form Name");
        table.addCell("Task Name");
        table.addCell("Status");
        table.addCell("Assigned To");

        table.setHeaderRows(1);

        // Add the task data

        table.getDefaultCell().setBackgroundColor(null);
        for (TaskFeature tf : t.features) {
            TaskProperties p = tf.properties;

            table.addCell(p.survey_name);
            table.addCell(p.name);
            table.addCell(p.status);
            table.addCell(p.assignee_name);

        }

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

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

    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception", 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 {//from   w w w  .ja  v a2s . c  om
        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:org.smap.sdal.managers.PDFTableManager.java

License:Open Source License

public void createPdf(Connection sd, OutputStream outputStream, ArrayList<ArrayList<KeyValue>> dArray,
        SurveyViewDefn mfc, ResourceBundle localisation, String tz, boolean landscape, String remoteUser,
        String basePath, String title, String project) {

    User user = null;/*from ww  w.  j  a  va 2  s .c  om*/
    UserManager um = new UserManager(localisation);

    try {

        user = um.getByIdent(sd, remoteUser);

        // 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);

        ArrayList<PdfColumn> cols = getPdfColumnList(mfc, dArray, localisation);
        ArrayList<String> tableHeader = new ArrayList<String>();
        for (PdfColumn col : cols) {
            tableHeader.add(col.displayName);
        }
        /*
         * Create a PDF without the stationary
         */
        PdfWriter writer = null;

        /*
         * 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
        Document document = null;
        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(title, project, user, basePath, tableHeader, marginLeft,
                marginRight, marginTop_2, marginBottom_2));

        document.open();
        document.add(new Chunk("")); // Ensure there is something in the page so at least a blank document will be created
        processResults(parser, document, dArray, cols, basePath);
        document.close();

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

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

    }

}