Example usage for com.itextpdf.text Font Font

List of usage examples for com.itextpdf.text Font Font

Introduction

In this page you can find the example usage for com.itextpdf.text Font Font.

Prototype


public Font(final FontFamily family, final float size, final int style) 

Source Link

Document

Constructs a Font.

Usage

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

    /*//from  ww w.  j  a va  2s .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 w w w .j a  va 2  s.  c om
 * @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//  ww w  .j  a v  a 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.oscarehr.fax.util.PdfCoverPageCreator.java

License:Open Source License

public byte[] createCoverPage() {

    Document document = new Document();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    try {//from  w w  w.j a  v  a  2  s  .c o m

        PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
        document.open();

        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(95);

        PdfPCell cell = new PdfPCell(table);
        cell.setBorder(0);
        cell.setPadding(3);
        cell.setColspan(1);
        table.addCell(cell);

        ClinicDAO clinicDao = SpringUtils.getBean(ClinicDAO.class);
        Clinic clinic = clinicDao.getClinic();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        Font headerFont = new Font(bf, 28, Font.BOLD);
        Font infoFont = new Font(bf, 12, Font.NORMAL);

        if (clinic != null) {

            cell = new PdfPCell(new Phrase(
                    String.format("%s\n %s, %s, %s %s", clinic.getClinicName(), clinic.getClinicAddress(),
                            clinic.getClinicCity(), clinic.getClinicProvince(), clinic.getClinicPostal()),
                    headerFont));
        } else {

            cell = new PdfPCell(new Phrase("OSCAR", headerFont));

        }

        cell.setPaddingTop(100);
        cell.setPaddingLeft(25);
        cell.setPaddingBottom(25);
        cell.setBorderWidthBottom(1);
        table.addCell(cell);

        PdfPTable infoTable = new PdfPTable(1);
        cell = new PdfPCell(new Phrase(note, infoFont));
        cell.setPaddingTop(25);
        cell.setPaddingLeft(25);
        infoTable.addCell(cell);
        table.addCell(infoTable);

        document.add(table);

    } catch (DocumentException e) {

        MiscUtils.getLogger().error("PDF COVER PAGE ERROR", e);
        return new byte[] {};

    } catch (IOException e) {

        MiscUtils.getLogger().error("PDF COVER PAGE ERROR", e);
        return new byte[] {};

    } finally {
        document.close();
    }

    return os.toByteArray();
}

From source file:org.patientview.radar.service.impl.PdfDocumentDataBuilder.java

License:Open Source License

private PdfPCell createHeadingCell(String text) {
    PdfPCell cell = createBaseCell(text, new Font(BASE_FONT, BASE_FONT_SIZE, Font.BOLD));
    cell.setBackgroundColor(new BaseColor(0xDE, 0xDE, 0xDE));
    return cell;/*from  ww  w .j a  v a  2s .  c  o  m*/
}

From source file:org.rro.inventory.service.InventoryServices.java

License:Apache License

public void printLabel(ByteArrayOutputStream fos) throws UserException {

    long lastLabelId = 0L;
    PDFLabels pl = null;/*w w  w  .  jav  a  2s.c o  m*/
    try {

        List<Item> items = inventoryRepository.findAllItems(em, "MASFILIO",
                Arrays.asList(new SingularAttribute[] { Label_.code, Item_.code }));

        if (items != null) {

            for (Item item : items) {
                if (lastLabelId != item.getType().getLabel().getId().longValue()) {
                    if (pl != null) {
                        //TODO multitracciatooooooooooooooooo
                    }
                    //                  pl = new PDFLabels(item.getType().getLabel().getMmHeigth().floatValue()/10, 
                    //                                   item.getType().getLabel().getMmWidth().floatValue()/10, .1f, .5f, .5f, fos);
                    pl.setAlignment(Element.ALIGN_CENTER, Element.ALIGN_CENTER); //sets the defalut alignment properties for the cells
                    pl.setFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));
                    lastLabelId = item.getType().getLabel().getId().longValue();
                }

            }

            String text = "Test codiceeee:";
            DecimalFormat df = new DecimalFormat("ABCD5678");

            for (int r = 0; r < 60; r++) {
                pl.append39(text, df.format(r));
            }

            pl.finnish();

            fos.flush();
            fos.close();

            System.out.println("TERMINATO");

        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new FatalException(e.getMessage(), e);
    }
}

From source file:org.sistemafinanciero.rest.impl.CuentaBancariaRESTService.java

License:Apache License

@Override
public Response getEstadoCuentaPdf(BigInteger idCuentaBancaria, Long desde, Long hasta) {
    Date dateDesde = (desde != null ? new Date(desde) : null);
    Date dateHasta = (desde != null ? new Date(hasta) : null);

    //dando formato a las fechas
    SimpleDateFormat fechaformato = new SimpleDateFormat("dd/MM/yyyy");
    String fechaDesde = fechaformato.format(dateDesde);
    String fechaHasta = fechaformato.format(dateHasta);

    Set<Titular> titulares = cuentaBancariaServiceNT.getTitulares(idCuentaBancaria, true);
    List<String> emails = new ArrayList<String>();
    for (Titular titular : titulares) {
        PersonaNatural personaNatural = titular.getPersonaNatural();
        String email = personaNatural.getEmail();
        if (email != null)
            emails.add(email);/*from www . j a  va 2s  .  co  m*/
    }
    CuentaBancariaView cuentaBancariaView = cuentaBancariaServiceNT.findById(idCuentaBancaria);
    List<EstadocuentaBancariaView> list = cuentaBancariaServiceNT.getEstadoCuenta(idCuentaBancaria, dateDesde,
            dateHasta);

    /**obteniendo la moneda y dando formato**/
    Moneda moneda = monedaServiceNT.findById(cuentaBancariaView.getIdMoneda());
    NumberFormat df1 = NumberFormat.getCurrencyInstance();
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setCurrencySymbol("");
    dfs.setGroupingSeparator(',');
    dfs.setMonetaryDecimalSeparator('.');
    ((DecimalFormat) df1).setDecimalFormatSymbols(dfs);

    /**PDF**/
    ByteArrayOutputStream outputStream = null;
    outputStream = new ByteArrayOutputStream();

    Document document = new Document();
    try {
        PdfWriter.getInstance(document, outputStream);
        document.open();

        document.addTitle("Estado de Cuenta");
        document.addSubject("Estado de Cuenta");
        document.addKeywords("email");
        document.addAuthor("Cooperativa de Ahorro y Crdito Caja Ventura");
        document.addCreator("Cooperativa de Ahorro y Crdito Caja Ventura");

        Paragraph saltoDeLinea = new Paragraph();
        document.add(saltoDeLinea);
    } catch (DocumentException e1) {
        e1.printStackTrace();
    }

    /******************* TITULO ******************/
    try {
        //Image img = Image.getInstance("/images/logo_coop_contrato.png");
        Image img = Image.getInstance("//usr//share//jboss//archivos//logoCartilla//logo_coop_contrato.png");
        img.setAlignment(Image.LEFT | Image.UNDERLYING);
        document.add(img);

        Paragraph parrafoPrincipal = new Paragraph();
        parrafoPrincipal.setSpacingAfter(30);
        //parrafoPrincipal.setSpacingBefore(50);
        parrafoPrincipal.setAlignment(Element.ALIGN_CENTER);
        parrafoPrincipal.setIndentationLeft(100);
        parrafoPrincipal.setIndentationRight(50);

        Paragraph parrafoSecundario = new Paragraph();
        parrafoSecundario.setSpacingAfter(20);
        parrafoSecundario.setSpacingBefore(-20);
        parrafoSecundario.setAlignment(Element.ALIGN_LEFT);
        parrafoSecundario.setIndentationLeft(160);
        parrafoSecundario.setIndentationRight(10);

        Chunk titulo = new Chunk("ESTADO DE CUENTA");
        Font fuenteTitulo = new Font(FontFamily.UNDEFINED, 13, Font.BOLD);
        titulo.setFont(fuenteTitulo);
        parrafoPrincipal.add(titulo);

        Font fuenteDatosCliente = new Font(FontFamily.UNDEFINED, 10);
        Date fechaSistema = new Date();
        SimpleDateFormat formatFecha = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        String fechaActual = formatFecha.format(fechaSistema);

        if (cuentaBancariaView.getTipoPersona() == TipoPersona.NATURAL) {
            Chunk clientePNNombres = new Chunk("CLIENTE       : " + cuentaBancariaView.getSocio() + "\n");
            Chunk clientePNDni = new Chunk(cuentaBancariaView.getTipoDocumento() + "                : "
                    + cuentaBancariaView.getNumeroDocumento() + "\n");
            //Chunk clientePNTitulares = new Chunk("TITULAR(ES): " + cuentaBancariaView.getTitulares() + "\n");
            Chunk clientePNFecha = new Chunk("FECHA          : " + fechaActual + "\n\n");

            Chunk tipoCuentaPN = new Chunk("CUENTA " + cuentaBancariaView.getTipoCuenta() + " N "
                    + cuentaBancariaView.getNumeroCuenta() + "\n");
            Chunk tipoMonedaPN;

            if (cuentaBancariaView.getIdMoneda().compareTo(BigInteger.ZERO) == 0) {
                tipoMonedaPN = new Chunk("MONEDA: " + "DOLARES AMERICANOS" + "\n");
            } else if (cuentaBancariaView.getIdMoneda().compareTo(BigInteger.ONE) == 0) {
                tipoMonedaPN = new Chunk("MONEDA: " + "NUEVOS SOLES" + "\n");
            } else {
                tipoMonedaPN = new Chunk("MONEDA: " + "EUROS" + "\n");
            }

            Chunk fechaEstadoCuenta = new Chunk("ESTADO DE CUENTA DEL " + fechaDesde + " AL " + fechaHasta);
            //obteniedo titulares
            /*String tPN = cuentaBancariaView.getTitulares();
            String[] arrayTitulares = tPN.split(",");
            Chunk clientePNTitulares = new Chunk("Titular(es):");
            for (int i = 0; i < arrayTitulares.length; i++) {
               String string = arrayTitulares[i];
            }*/

            clientePNNombres.setFont(fuenteDatosCliente);
            clientePNDni.setFont(fuenteDatosCliente);
            //clientePNTitulares.setFont(fuenteDatosCliente);
            clientePNFecha.setFont(fuenteDatosCliente);
            tipoCuentaPN.setFont(fuenteDatosCliente);
            tipoMonedaPN.setFont(fuenteDatosCliente);
            fechaEstadoCuenta.setFont(fuenteDatosCliente);

            parrafoSecundario.add(clientePNNombres);
            parrafoSecundario.add(clientePNDni);
            //parrafoSecundario.add(clientePNTitulares);
            parrafoSecundario.add(clientePNFecha);
            parrafoSecundario.add(tipoCuentaPN);
            parrafoSecundario.add(tipoMonedaPN);
            parrafoSecundario.add(fechaEstadoCuenta);

        } else {
            Chunk clientePJNombre = new Chunk("CLIENTE       : " + cuentaBancariaView.getSocio() + "\n");
            Chunk clientePJRuc = new Chunk(cuentaBancariaView.getTipoDocumento() + "               : "
                    + cuentaBancariaView.getNumeroDocumento() + "\n");
            //Chunk clientePJTitulares = new Chunk("TITULAR(ES): " + cuentaBancariaView.getTitulares() + "\n");
            Chunk clientePJFecha = new Chunk("FECHA          : " + fechaActual + "\n\n");

            Chunk tipoCuentaPJ = new Chunk("CUENTA " + cuentaBancariaView.getTipoCuenta() + " N "
                    + cuentaBancariaView.getNumeroCuenta() + "\n");
            Chunk tipoMonedaPJ;

            if (cuentaBancariaView.getIdMoneda().compareTo(BigInteger.ZERO) == 0) {
                tipoMonedaPJ = new Chunk("MONEDA: " + "DOLARES AMERICANOS" + "\n");
            } else if (cuentaBancariaView.getIdMoneda().compareTo(BigInteger.ONE) == 0) {
                tipoMonedaPJ = new Chunk("MONEDA: " + "NUEVOS SOLES" + "\n");
            } else {
                tipoMonedaPJ = new Chunk("MONEDA: " + "EUROS" + "\n");
            }

            Chunk fechaEstadoCuenta = new Chunk("ESTADO DE CUENTA DEL " + fechaDesde + " AL " + fechaHasta);
            //obteniedo titulares
            /*String tPN = cuentaBancariaView.getTitulares();
            String[] arrayTitulares = tPN.split(",");
            Chunk clientePNTitulares = new Chunk("Titular(es):");
            for (int i = 0; i < arrayTitulares.length; i++) {
               String string = arrayTitulares[i];
            }*/

            clientePJNombre.setFont(fuenteDatosCliente);
            clientePJRuc.setFont(fuenteDatosCliente);
            //clientePJTitulares.setFont(fuenteDatosCliente);
            clientePJFecha.setFont(fuenteDatosCliente);
            tipoCuentaPJ.setFont(fuenteDatosCliente);
            tipoMonedaPJ.setFont(fuenteDatosCliente);
            fechaEstadoCuenta.setFont(fuenteDatosCliente);

            parrafoSecundario.add(clientePJNombre);
            parrafoSecundario.add(clientePJRuc);
            //parrafoSecundario.add(clientePJTitulares);
            parrafoSecundario.add(clientePJFecha);
            parrafoSecundario.add(tipoCuentaPJ);
            parrafoSecundario.add(tipoMonedaPJ);
            parrafoSecundario.add(fechaEstadoCuenta);

        }

        document.add(parrafoPrincipal);
        document.add(parrafoSecundario);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Font fontTableCabecera = new Font(FontFamily.UNDEFINED, 9, Font.BOLD);
    Font fontTableCuerpo = new Font(FontFamily.UNDEFINED, 9, Font.NORMAL);

    float[] columnWidths = { 5f, 4f, 2.8f, 10f, 3.5f, 4f, 2.8f };
    PdfPTable table = new PdfPTable(columnWidths);
    table.setWidthPercentage(100);

    PdfPCell cellFechaHoraCabecera = new PdfPCell(new Paragraph("FECHA Y HORA", fontTableCabecera));
    PdfPCell cellTransaccionCabecera = new PdfPCell(new Paragraph("TIPO TRANS.", fontTableCabecera));
    PdfPCell cellOperacionCabecera = new PdfPCell(new Paragraph("NUM. OP.", fontTableCabecera));
    PdfPCell cellReferenciaCabecera = new PdfPCell(new Paragraph("REFERENCIA", fontTableCabecera));
    PdfPCell cellMontoCabecera = new PdfPCell(new Paragraph("MONTO", fontTableCabecera));
    PdfPCell cellSaldoDisponibleCabecera = new PdfPCell(new Paragraph("DISPONIBLE", fontTableCabecera));
    PdfPCell cellEstado = new PdfPCell(new Paragraph("ESTADO", fontTableCabecera));

    table.addCell(cellFechaHoraCabecera);
    table.addCell(cellTransaccionCabecera);
    table.addCell(cellOperacionCabecera);
    table.addCell(cellReferenciaCabecera);
    table.addCell(cellMontoCabecera);
    table.addCell(cellSaldoDisponibleCabecera);
    table.addCell(cellEstado);

    for (EstadocuentaBancariaView estadocuentaBancariaView : list) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        String fecHoraFormat = sdf.format(estadocuentaBancariaView.getHora());

        PdfPCell cellFechaHora = new PdfPCell(new Paragraph(fecHoraFormat, fontTableCuerpo));
        table.addCell(cellFechaHora);
        PdfPCell cellTipoTrasaccion = new PdfPCell(
                new Paragraph(estadocuentaBancariaView.getTipoTransaccionTransferencia(), fontTableCuerpo));
        table.addCell(cellTipoTrasaccion);
        PdfPCell cellNumOperacion = new PdfPCell(
                new Paragraph(estadocuentaBancariaView.getNumeroOperacion().toString(), fontTableCuerpo));
        table.addCell(cellNumOperacion);
        PdfPCell cellReferencia = new PdfPCell(
                new Paragraph(estadocuentaBancariaView.getReferencia(), fontTableCuerpo));
        table.addCell(cellReferencia);
        PdfPCell cellMonto = new PdfPCell(
                new Paragraph(df1.format(estadocuentaBancariaView.getMonto()), fontTableCuerpo));
        table.addCell(cellMonto);
        PdfPCell cellSaldoDisponible = new PdfPCell(
                new Paragraph(df1.format(estadocuentaBancariaView.getSaldoDisponible()), fontTableCuerpo));
        table.addCell(cellSaldoDisponible);
        if (estadocuentaBancariaView.getEstado()) {
            PdfPCell cellEstadoActivo = new PdfPCell(new Paragraph("Activo", fontTableCuerpo));
            table.addCell(cellEstadoActivo);
        } else {
            PdfPCell cellEstadoExtornado = new PdfPCell(new Paragraph("Extornado", fontTableCuerpo));
            table.addCell(cellEstadoExtornado);
        }
    }

    Paragraph saldoDisponible = new Paragraph();
    saldoDisponible.setAlignment(Element.ALIGN_CENTER);
    Chunk textoSaldoDisponible = new Chunk(
            "SALDO DISPONIBLE: " + moneda.getSimbolo() + df1.format(cuentaBancariaView.getSaldo()),
            fontTableCabecera);
    textoSaldoDisponible.setFont(fontTableCabecera);
    saldoDisponible.add(textoSaldoDisponible);

    try {
        document.add(table);
        document.add(saldoDisponible);
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    document.close();

    return Response.ok(outputStream.toByteArray()).type("application/pdf").build();
}

From source file:PDF.PDFTrackGenerator.java

License:Open Source License

/**
 * Metda generateTrackPDFA4 sli na samotn vygenerovanie PDF dokumentu trasy na formt A4.
 * @param lineWeight - hrbka ?iary trasy na mape
 * @param color - farba ?iary trasy na mape
 * @param width - rka mapy/* w  ww  .  j av a 2s .com*/
 * @param height - vka mapy
 * @param scale - klovacia kontanta mapy (n x rozlenie mapy)
 * @param startDate - dtum a ?as prvho bodu trasy
 * @param endDate - dtum a ?as poslednho bodu trasy
 * @param activity - aktivita trasy
 * @param user - pouvate (majite) trasy
 */
public void generateTrackPDFA4(int lineWeight, String color, int width, int height, int scale, String startDate,
        String endDate, String activity, String user) {
    try {
        Document doc = new Document();
        PdfWriter.getInstance(doc, new FileOutputStream(path + fileName + ".pdf"));
        doc.open();

        Font nadpisFont = new Font(Font.FontFamily.HELVETICA, 25, Font.BOLD);

        Font detailyFont = new Font(Font.FontFamily.HELVETICA, 9, Font.NORMAL);

        Paragraph nadpisPar = new Paragraph();

        nadpisPar.setAlignment(Element.ALIGN_CENTER);

        Phrase nadpis = new Phrase(fileName, nadpisFont);

        nadpisPar.add(nadpis);

        nadpisPar.add("");

        doc.add(nadpisPar);
        doc.add(Chunk.NEWLINE);

        PdfPTable tabulka = new PdfPTable(2);
        tabulka.setWidthPercentage(100);
        float[] columnWidth = { 6f, 4f };
        tabulka.setWidths(columnWidth);

        StaticMapResolver res = new StaticMapResolver(loader);

        String mapUrl = res.getStaticMapTrackURLWithMultimedia(lineWeight, color, width, height, scale);

        Image img = Image.getInstance(new URL(mapUrl));
        //img.scalePercent(50);
        PdfPCell riadokSObr = new PdfPCell(img, true);
        riadokSObr.setBorder(Rectangle.NO_BORDER);
        riadokSObr.setPaddingBottom(10f);
        PdfPCell riadokSText = new PdfPCell(new Phrase("Description: " + loader.getTrackDescription()
                + "\n\n\nTrack activity: " + activity.substring(4) + "\n\n\nStart place: "
                + loader.getStartAddress() + "\n\n\nEnd Place: " + loader.getEndAddress()
                + "\n\n\nTrack length: " + loader.getLength() + " km\n\n\nMin elevation: "
                + loader.getMinElevation() + " m\n\n\nMax elevation: " + loader.getMaxElevation()
                + " m\n\n\nHeight difference: " + loader.getHeightDiff() + " m\n\n\nStart: " + startDate
                + "\n\n\nEnd: " + endDate + "\n\n\nDuration: " + loader.getDuration(), detailyFont));
        riadokSText.setBorder(Rectangle.NO_BORDER);
        riadokSText.setPaddingLeft(20f);
        riadokSText.setPaddingTop(5f);
        riadokSText.setPaddingBottom(10f);
        tabulka.addCell(riadokSObr);
        tabulka.addCell(riadokSText);

        doc.add(tabulka);
        //doc.add(new Phrase("\n", detailyFont));

        PdfPTable obrTabulka = new PdfPTable(3);
        obrTabulka.setWidthPercentage(100);

        ArrayList<String> goodFiles = new ArrayList<String>();
        for (int i = 0; i < loader.getMultimediaFiles().size(); i++) {
            if (!loader.getMultimediaFiles().get(i).getPath().startsWith("YTB")) {
                String extension = loader.getMultimediaFiles().get(i).getPath().substring(
                        loader.getMultimediaFiles().get(i).getPath().lastIndexOf("."),
                        loader.getMultimediaFiles().get(i).getPath().length());
                String newPath = loader.getMultimediaFiles().get(i).getPath().substring(0,
                        loader.getMultimediaFiles().get(i).getPath().lastIndexOf(".")) + "_THUMB" + extension;
                goodFiles.add(newPath);
            }
        }

        if (!goodFiles.isEmpty()) {
            int freeCount = 9;
            if (goodFiles.size() <= 9) {
                for (int i = 0; i < goodFiles.size(); i++) {
                    Image tempImg = Image.getInstance(goodFiles.get(i));
                    tempImg.scalePercent(10f);
                    PdfPCell tempCell = new PdfPCell(tempImg, true);
                    tempCell.setPadding(3f);
                    //tempCell.setPaddingTop(5f);
                    tempCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    tempCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tempCell.setFixedHeight(130f);
                    tempCell.setBackgroundColor(BaseColor.BLACK);
                    tempCell.setBorderColor(BaseColor.WHITE);
                    tempCell.setBorderWidth(4f);
                    //tempCell.setBorder(Rectangle.NO_BORDER);
                    obrTabulka.addCell(tempCell);
                }
                for (int i = 0; i < 9 - goodFiles.size(); i++) {
                    PdfPCell tempCell = new PdfPCell();
                    tempCell.setBorder(Rectangle.NO_BORDER);
                    obrTabulka.addCell(tempCell);
                }
            } else if (goodFiles.size() <= 18) {
                for (int i = 0; i < 9; i++) {
                    Image tempImg = Image.getInstance(goodFiles.get(i));
                    tempImg.scalePercent(10f);
                    PdfPCell tempCell = new PdfPCell(tempImg, true);
                    tempCell.setPadding(3f);
                    //tempCell.setPaddingTop(5f);
                    tempCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    tempCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tempCell.setFixedHeight(130f);
                    tempCell.setBackgroundColor(BaseColor.BLACK);
                    tempCell.setBorderColor(BaseColor.WHITE);
                    tempCell.setBorderWidth(4f);
                    //tempCell.setBorder(Rectangle.NO_BORDER);
                    obrTabulka.addCell(tempCell);
                }
            } else {
                for (int i = 0; i < (goodFiles.size() % 9); i++) {
                    goodFiles.remove(goodFiles.size() - 1 - i);
                }

                int counting = (goodFiles.size() / 9);

                for (int i = 0; i < goodFiles.size(); i = i + counting) {
                    Image tempImg = Image.getInstance(goodFiles.get(i));
                    tempImg.scalePercent(10f);
                    PdfPCell tempCell = new PdfPCell(tempImg, true);
                    tempCell.setPadding(3f);
                    //tempCell.setPaddingTop(5f);
                    tempCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    tempCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    tempCell.setFixedHeight(130f);
                    tempCell.setBackgroundColor(BaseColor.BLACK);
                    tempCell.setBorderColor(BaseColor.WHITE);
                    tempCell.setBorderWidth(4f);
                    //tempCell.setBorder(Rectangle.NO_BORDER);
                    obrTabulka.addCell(tempCell);
                    freeCount--;
                }
                for (int i = 0; i < freeCount; i++) {
                    PdfPCell tempCell = new PdfPCell();
                    tempCell.setBorder(Rectangle.NO_BORDER);
                    obrTabulka.addCell(tempCell);
                }
            }
        }

        doc.add(obrTabulka);

        Font lastFont = new Font(Font.FontFamily.HELVETICA, 7, Font.ITALIC);
        Phrase lastText = new Phrase("This PDF document was generated by gTrax app for user " + user, lastFont);
        doc.add(lastText);

        doc.close();
    } catch (Exception ex) {
        FileLogger.getInstance()
                .createNewLog("ERROR: Cannot CREATE PDF for track " + fileName + " for user " + user + " !!!");
        System.out.println("pruser");
    }

}

From source file:pkg412project.ReportPDF.java

public static void main(String args[])
        throws ClassNotFoundException, SQLException, DocumentException, FileNotFoundException {
    try {//from  w  ww.  j av  a 2 s.c o  m
        //Class.forName("oracle.jdbc.OracleDriver");
        int rowno = 0;
        String url = "jdbc:oracle:thin:@acaddb2.asu.edu:1521:orcl";
        String username = "sbmohan1";
        String password = "sbmohan1";

        Connection conn = DriverManager.getConnection(url, username, password);
        Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        ResultSet rs = stmt.executeQuery("SELECT * FROM SBMOHAN1.ORDERTABLE");
        ResultSetMetaData rsmd = rs.getMetaData();
        int colno = rsmd.getColumnCount();
        while (rs.next()) {
            rowno++;
        }
        rs.first();
        Document d = new Document();
        PdfWriter.getInstance(d, new FileOutputStream("report.pdf"));
        Font font1 = new Font(Font.FontFamily.HELVETICA, 25, Font.BOLD);
        Font font2 = new Font(Font.FontFamily.TIMES_ROMAN, 27);
        Font font3 = new Font(Font.FontFamily.COURIER, 12, Font.BOLD);
        float[] columnWidths = { 4f, 4f, 16f, 16f, 4f, 4f, 4f, 4f };
        PdfPTable ptable = new PdfPTable(colno);
        ptable.setWidths(columnWidths);
        d.open();
        Paragraph title = new Paragraph("Order Report", font1);
        title.setAlignment(Element.ALIGN_CENTER);
        d.add(title);
        Paragraph date = new Paragraph("December 10th, 2015", font2);
        date.setAlignment(Element.ALIGN_CENTER);
        d.add(date);
        //d.add(new Paragraph("Order Report"));

        //d.add(new Paragraph("Date: December 10th, 2015"));
        d.add(Chunk.NEWLINE);
        //d.add(Chunk.NEWLINE);
        ptable.addCell(new Paragraph("OrderID", font3));
        ptable.addCell(new Paragraph("NumItems", font3));
        ptable.addCell(new Paragraph("ItemsOrdered", font3));
        ptable.addCell(new Paragraph("OrderStatus", font3));
        ptable.addCell(new Paragraph("TotalPrice", font3));
        ptable.addCell(new Paragraph("PaymentID", font3));
        ptable.addCell(new Paragraph("TableID", font3));
        ptable.addCell(new Paragraph("ChefID", font3));

        //insertCell(ptable, "OrderID", Element.ALIGN_LEFT, 1, bfBold12);
        for (int i = 0; i < rowno; i++) {
            ptable.addCell("" + rs.getString(1));
            ptable.addCell("" + rs.getString(2));
            ptable.addCell("" + rs.getString(3));
            ptable.addCell("" + rs.getString(4));
            ptable.addCell("" + rs.getString(5));
            ptable.addCell("" + rs.getString(6));
            ptable.addCell("" + rs.getString(7));
            ptable.addCell("" + rs.getString(8));
            rs.next();
        }

        d.add(ptable);
        d.close();

    } catch (SQLException ex) {
        System.out.println(ex.toString());
    }
}

From source file:presentation.frmReportForm.java

private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerateActionPerformed
    Date dateNow = new Date();
    SimpleDateFormat df = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss");

    System.out.println(dtcMonthChooser.getMonth());
    System.out.println(dtcYearChooser.getYear());

    if (radInMonth.isSelected()) {
        List<Transfer> transferList = new ArrayList<>();

        transferList = empObj.searchRecordByMonth(dtcMonthChooser.getMonth() + 1, dtcYearChooser.getYear());

        Document document = new Document();
        try {/*w  w  w.  j  ava2s. c  o  m*/
            Font fontTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);

            String fileName = "../EMPtranfermanagement/Report" + " " + df.format(dateNow) + ".pdf";
            PdfWriter.getInstance(document, new FileOutputStream(fileName));

            document.open();

            Image imageLogo = Image
                    .getInstance(this.getClass().getResource("/images/onlinelogomaker-afterscale2.png"));
            imageLogo.setAbsolutePosition(20, 750f);
            document.add(imageLogo);

            Paragraph titlePara = new Paragraph("EMP Transfer Application", fontTitle);
            titlePara.setAlignment(Element.ALIGN_CENTER);
            titlePara.setSpacingAfter(5);
            document.add(titlePara);

            Paragraph creditPara = new Paragraph("Created by Ly Thanh Hai + Nguyen Khanh",
                    FontFactory.getFont(FontFactory.HELVETICA, 10, Font.ITALIC));
            creditPara.setAlignment(Element.ALIGN_CENTER);
            creditPara.setSpacingAfter(10);
            document.add(creditPara);

            Paragraph slashPara = new Paragraph(
                    "Transfer records at " + (dtcMonthChooser.getMonth() + 1) + "/" + dtcYearChooser.getYear(),
                    FontFactory.getFont(FontFactory.HELVETICA, 15, Font.BOLD));
            slashPara.setSpacingAfter(40);
            slashPara.setAlignment(Element.ALIGN_CENTER);
            document.add(slashPara);

            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);

            Font font = new Font(FontFamily.HELVETICA, 15, Font.BOLD);
            Paragraph paragraphCellHeading = new Paragraph("Report", font);

            PdfPCell cellHeading = new PdfPCell(paragraphCellHeading);
            BaseColor myColor = WebColors.getRGBColor("#41a5c2");
            cellHeading.setColspan(5);
            cellHeading.setBackgroundColor(myColor);
            cellHeading.setFixedHeight(30.3f);
            cellHeading.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellHeading);

            Font fBody = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.BLACK);

            PdfPCell cellTitle1 = new PdfPCell(new Phrase("Transfer ID", fBody));
            cellTitle1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle1);
            PdfPCell cellTitle2 = new PdfPCell(new Phrase("Emp ID", fBody));
            cellTitle2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle2);
            PdfPCell cellTitle3 = new PdfPCell(new Phrase("From Project", fBody));
            cellTitle3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle3.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle3);
            PdfPCell cellTitle4 = new PdfPCell(new Phrase("To Project", fBody));
            cellTitle4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle4.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle4);
            PdfPCell cellTitleStatus = new PdfPCell(new Phrase("Status", fBody));
            cellTitleStatus.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitleStatus.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitleStatus);

            int cellColorCheck = 1;
            for (Transfer e : transferList) {
                PdfPCell cellBody1 = new PdfPCell(new Phrase(e.getId()));
                PdfPCell cellBody2 = new PdfPCell(new Phrase(e.getEmployeeId()));
                PdfPCell cellBody3 = new PdfPCell(new Phrase(e.getFromProjectId()));
                PdfPCell cellBody4 = new PdfPCell(new Phrase(e.getToProjectId()));
                PdfPCell cellBody5 = new PdfPCell(new Phrase(e.getStatus()));
                if (cellColorCheck % 2 == 1) {
                    cellBody1.setBackgroundColor(BaseColor.ORANGE);
                    cellBody2.setBackgroundColor(BaseColor.ORANGE);
                    cellBody3.setBackgroundColor(BaseColor.ORANGE);
                    cellBody4.setBackgroundColor(BaseColor.ORANGE);
                    cellBody5.setBackgroundColor(BaseColor.ORANGE);
                }
                table.addCell(cellBody1);
                table.addCell(cellBody2);
                table.addCell(cellBody3);
                table.addCell(cellBody4);
                table.addCell(cellBody5);
                cellColorCheck++;
            }

            document.add(table);

            JOptionPane.showMessageDialog(this, "Report saved");

            if (Desktop.isDesktopSupported()) {
                File reportFile = new File(fileName);
                Desktop.getDesktop().open(reportFile);
                ;
            }

            document.close();
        } catch (DocumentException | FileNotFoundException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    if (radInDateRange.isSelected()) {
        try {
            List<Transfer> transferList = new ArrayList<>();

            java.sql.Date fromDateSql = formatDateForSearching(dtcFromDate.getDate());
            java.sql.Date toDateSql = formatDateForSearching(dtcToDate.getDate());
            transferList = empObj.searchRecordByDate(fromDateSql, toDateSql);

            Document document = new Document();
            try {
                Font fontTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);

                String fileName = "../EMPtranfermanagement/Report" + " " + df.format(dateNow) + ".pdf";
                PdfWriter.getInstance(document, new FileOutputStream(fileName));

                document.open();

                Image imageLogo = Image
                        .getInstance(this.getClass().getResource("/images/onlinelogomaker-afterscale2.png"));
                imageLogo.setAbsolutePosition(20, 750f);
                document.add(imageLogo);

                Paragraph titlePara = new Paragraph("EMP Transfer Application", fontTitle);
                titlePara.setAlignment(Element.ALIGN_CENTER);
                titlePara.setSpacingAfter(5);
                document.add(titlePara);

                Paragraph creditPara = new Paragraph("Created by Ly Thanh Hai + Nguyen Khanh",
                        FontFactory.getFont(FontFactory.HELVETICA, 10, Font.ITALIC));
                creditPara.setAlignment(Element.ALIGN_CENTER);
                creditPara.setSpacingAfter(10);
                document.add(creditPara);

                SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
                String fromDate = df2.format(dtcFromDate.getDate());
                String toDate = df2.format(dtcToDate.getDate());

                Paragraph slashPara = new Paragraph("Transfer records from " + fromDate + " to " + toDate,
                        FontFactory.getFont(FontFactory.HELVETICA, 15, Font.BOLD));
                slashPara.setSpacingAfter(40);
                slashPara.setAlignment(Element.ALIGN_CENTER);
                document.add(slashPara);

                PdfPTable table = new PdfPTable(5);
                table.setWidthPercentage(100);

                Font font = new Font(FontFamily.HELVETICA, 15, Font.BOLD);
                Paragraph paragraphCellHeading = new Paragraph("Report", font);

                PdfPCell cellHeading = new PdfPCell(paragraphCellHeading);
                BaseColor myColor = WebColors.getRGBColor("#41a5c2");
                cellHeading.setColspan(5);
                cellHeading.setBackgroundColor(myColor);
                cellHeading.setFixedHeight(30.3f);
                cellHeading.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellHeading);

                Font fBody = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.BLACK);

                PdfPCell cellTitle1 = new PdfPCell(new Phrase("Transfer ID", fBody));
                cellTitle1.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitle1.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitle1);
                PdfPCell cellTitle2 = new PdfPCell(new Phrase("Emp ID", fBody));
                cellTitle2.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitle2.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitle2);
                PdfPCell cellTitle3 = new PdfPCell(new Phrase("From Project", fBody));
                cellTitle3.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitle3.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitle3);
                PdfPCell cellTitle4 = new PdfPCell(new Phrase("To Project", fBody));
                cellTitle4.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitle4.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitle4);
                PdfPCell cellTitleStatus = new PdfPCell(new Phrase("Status", fBody));
                cellTitleStatus.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitleStatus.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitleStatus);

                int cellColorCheck = 1;
                for (Transfer e : transferList) {
                    PdfPCell cellBody1 = new PdfPCell(new Phrase(e.getId()));
                    PdfPCell cellBody2 = new PdfPCell(new Phrase(e.getEmployeeId()));
                    PdfPCell cellBody3 = new PdfPCell(new Phrase(e.getFromProjectId()));
                    PdfPCell cellBody4 = new PdfPCell(new Phrase(e.getToProjectId()));
                    PdfPCell cellBody5 = new PdfPCell(new Phrase(e.getStatus()));
                    if (cellColorCheck % 2 == 1) {
                        cellBody1.setBackgroundColor(BaseColor.ORANGE);
                        cellBody2.setBackgroundColor(BaseColor.ORANGE);
                        cellBody3.setBackgroundColor(BaseColor.ORANGE);
                        cellBody4.setBackgroundColor(BaseColor.ORANGE);
                        cellBody5.setBackgroundColor(BaseColor.ORANGE);
                    }
                    table.addCell(cellBody1);
                    table.addCell(cellBody2);
                    table.addCell(cellBody3);
                    table.addCell(cellBody4);
                    table.addCell(cellBody5);
                    cellColorCheck++;
                }

                document.add(table);
                JOptionPane.showMessageDialog(this, "Report saved");

                if (Desktop.isDesktopSupported()) {
                    File reportFile = new File(fileName);
                    Desktop.getDesktop().open(reportFile);
                    ;
                }

                document.close();
            } catch (DocumentException | FileNotFoundException ex) {
                Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ParseException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    if (radInProject.isSelected()) {
        String fromProjectId = (String) cbxFromProject.getSelectedItem();
        String toProjectId = (String) cbxToProject.getSelectedItem();
        List<Transfer> transferList = new ArrayList<>();
        String andOr = "";
        if (cbxAndOr.getSelectedItem().equals("And")) {
            andOr = "and";
            transferList = empObj.searchRecordByFromAndToProject(fromProjectId, toProjectId, andOr);
        } else {
            andOr = "or";
            transferList = empObj.searchRecordByFromAndToProject(fromProjectId, toProjectId, andOr);
        }

        Document document = new Document();
        try {
            Font fontTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);

            String fileName = "../EMPtranfermanagement/Report" + " " + df.format(dateNow) + ".pdf";
            PdfWriter.getInstance(document, new FileOutputStream(fileName));

            document.open();

            Image imageLogo = Image
                    .getInstance(this.getClass().getResource("/images/onlinelogomaker-afterscale2.png"));
            imageLogo.setAbsolutePosition(20, 750f);
            document.add(imageLogo);

            Paragraph titlePara = new Paragraph("EMP Transfer Application", fontTitle);
            titlePara.setAlignment(Element.ALIGN_CENTER);
            titlePara.setSpacingAfter(5);
            document.add(titlePara);

            Paragraph creditPara = new Paragraph("Created by Ly Thanh Hai + Nguyen Khanh",
                    FontFactory.getFont(FontFactory.HELVETICA, 10, Font.ITALIC));
            creditPara.setAlignment(Element.ALIGN_CENTER);
            creditPara.setSpacingAfter(10);
            document.add(creditPara);

            Paragraph slashPara = new Paragraph(
                    "Transfer records from Project ID " + fromProjectId + " " + andOr + " " + toProjectId,
                    FontFactory.getFont(FontFactory.HELVETICA, 15, Font.BOLD));
            slashPara.setSpacingAfter(40);
            slashPara.setAlignment(Element.ALIGN_CENTER);
            document.add(slashPara);

            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);

            Font font = new Font(FontFamily.HELVETICA, 15, Font.BOLD);
            Paragraph paragraphCellHeading = new Paragraph("Report", font);

            PdfPCell cellHeading = new PdfPCell(paragraphCellHeading);
            BaseColor myColor = WebColors.getRGBColor("#41a5c2");
            cellHeading.setColspan(5);
            cellHeading.setBackgroundColor(myColor);
            cellHeading.setFixedHeight(30.3f);
            cellHeading.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellHeading);

            Font fBody = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.BLACK);

            PdfPCell cellTitle1 = new PdfPCell(new Phrase("Transfer ID", fBody));
            cellTitle1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle1);
            PdfPCell cellTitle2 = new PdfPCell(new Phrase("Emp ID", fBody));
            cellTitle2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle2);
            PdfPCell cellTitle3 = new PdfPCell(new Phrase("From Project", fBody));
            cellTitle3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle3.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle3);
            PdfPCell cellTitle4 = new PdfPCell(new Phrase("To Project", fBody));
            cellTitle4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle4.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle4);
            PdfPCell cellTitleStatus = new PdfPCell(new Phrase("Status", fBody));
            cellTitleStatus.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitleStatus.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitleStatus);

            int cellColorCheck = 1;
            for (Transfer e : transferList) {
                PdfPCell cellBody1 = new PdfPCell(new Phrase(e.getId()));
                PdfPCell cellBody2 = new PdfPCell(new Phrase(e.getEmployeeId()));
                PdfPCell cellBody3 = new PdfPCell(new Phrase(e.getFromProjectId()));
                PdfPCell cellBody4 = new PdfPCell(new Phrase(e.getToProjectId()));
                PdfPCell cellBody5 = new PdfPCell(new Phrase(e.getStatus()));
                if (cellColorCheck % 2 == 1) {
                    cellBody1.setBackgroundColor(BaseColor.ORANGE);
                    cellBody2.setBackgroundColor(BaseColor.ORANGE);
                    cellBody3.setBackgroundColor(BaseColor.ORANGE);
                    cellBody4.setBackgroundColor(BaseColor.ORANGE);
                    cellBody5.setBackgroundColor(BaseColor.ORANGE);
                }
                table.addCell(cellBody1);
                table.addCell(cellBody2);
                table.addCell(cellBody3);
                table.addCell(cellBody4);
                table.addCell(cellBody5);
                cellColorCheck++;
            }

            document.add(table);
            JOptionPane.showMessageDialog(this, "Report saved");

            if (Desktop.isDesktopSupported()) {
                File reportFile = new File(fileName);
                Desktop.getDesktop().open(reportFile);
                ;
            }

            document.close();
        } catch (DocumentException | FileNotFoundException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (radAllRecord.isSelected()) {
        List<Transfer> transferList = new ArrayList<>();
        transferList = empObj.searchAllRecord();

        Document document = new Document();
        try {
            Font fontTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);

            String fileName = "../EMPtranfermanagement/Report" + " " + df.format(dateNow) + ".pdf";
            PdfWriter.getInstance(document, new FileOutputStream(fileName));

            document.open();

            Image imageLogo = Image
                    .getInstance(this.getClass().getResource("/images/onlinelogomaker-afterscale2.png"));
            imageLogo.setAbsolutePosition(20, 750f);
            document.add(imageLogo);

            Paragraph titlePara = new Paragraph("EMP Transfer Application", fontTitle);
            titlePara.setAlignment(Element.ALIGN_CENTER);
            titlePara.setSpacingAfter(5);
            document.add(titlePara);

            Paragraph creditPara = new Paragraph("Created by Ly Thanh Hai + Nguyen Khanh",
                    FontFactory.getFont(FontFactory.HELVETICA, 10, Font.ITALIC));
            creditPara.setAlignment(Element.ALIGN_CENTER);
            creditPara.setSpacingAfter(10);
            document.add(creditPara);

            Paragraph slashPara = new Paragraph("All transfer records",
                    FontFactory.getFont(FontFactory.HELVETICA, 15, Font.BOLD));
            slashPara.setSpacingAfter(40);
            slashPara.setAlignment(Element.ALIGN_CENTER);
            document.add(slashPara);

            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);

            Font font = new Font(FontFamily.HELVETICA, 15, Font.BOLD);
            Paragraph paragraphCellHeading = new Paragraph("Report", font);

            PdfPCell cellHeading = new PdfPCell(paragraphCellHeading);
            BaseColor myColor = WebColors.getRGBColor("#41a5c2");
            cellHeading.setColspan(5);
            cellHeading.setBackgroundColor(myColor);
            cellHeading.setFixedHeight(30.3f);
            cellHeading.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellHeading);

            Font fBody = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.BLACK);

            PdfPCell cellTitle1 = new PdfPCell(new Phrase("Transfer ID", fBody));
            cellTitle1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle1);
            PdfPCell cellTitle2 = new PdfPCell(new Phrase("Emp ID", fBody));
            cellTitle2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle2);
            PdfPCell cellTitle3 = new PdfPCell(new Phrase("From Project", fBody));
            cellTitle3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle3.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle3);
            PdfPCell cellTitle4 = new PdfPCell(new Phrase("To Project", fBody));
            cellTitle4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle4.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle4);
            PdfPCell cellTitleStatus = new PdfPCell(new Phrase("Status", fBody));
            cellTitleStatus.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitleStatus.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitleStatus);

            int cellColorCheck = 1;
            for (Transfer e : transferList) {
                PdfPCell cellBody1 = new PdfPCell(new Phrase(e.getId()));
                PdfPCell cellBody2 = new PdfPCell(new Phrase(e.getEmployeeId()));
                PdfPCell cellBody3 = new PdfPCell(new Phrase(e.getFromProjectId()));
                PdfPCell cellBody4 = new PdfPCell(new Phrase(e.getToProjectId()));
                PdfPCell cellBody5 = new PdfPCell(new Phrase(e.getStatus()));
                if (cellColorCheck % 2 == 1) {
                    cellBody1.setBackgroundColor(BaseColor.ORANGE);
                    cellBody2.setBackgroundColor(BaseColor.ORANGE);
                    cellBody3.setBackgroundColor(BaseColor.ORANGE);
                    cellBody4.setBackgroundColor(BaseColor.ORANGE);
                    cellBody5.setBackgroundColor(BaseColor.ORANGE);
                }
                table.addCell(cellBody1);
                table.addCell(cellBody2);
                table.addCell(cellBody3);
                table.addCell(cellBody4);
                table.addCell(cellBody5);
                cellColorCheck++;
            }

            document.add(table);
            JOptionPane.showMessageDialog(this, "Report saved");

            if (Desktop.isDesktopSupported()) {
                File reportFile = new File(fileName);
                Desktop.getDesktop().open(reportFile);
                ;
            }

            document.close();
        } catch (DocumentException | FileNotFoundException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}