Example usage for com.itextpdf.text Font NORMAL

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

Introduction

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

Prototype

int NORMAL

To view the source code for com.itextpdf.text Font NORMAL.

Click Source Link

Document

this is a possible style.

Usage

From source file:org.fossa.rolp.util.PdfStreamSource.java

License:Open Source License

public PdfStreamSource(FossaApplication app, LebData lebData, LebCreator lebCreator)
        throws DocumentException, IOException, PdfFormatierungsException {
    this.lebData = lebData;
    this.lebCreator = lebCreator;
    BaseFont fontNormal = BaseFont.createFont(
            app.getContext().getBaseDirectory() + Config.getRelativeNormalFontPath(), BaseFont.CP1252,
            BaseFont.EMBEDDED);//w  w w .j  ava2s.c om
    BaseFont fontBold = BaseFont.createFont(
            app.getContext().getBaseDirectory() + Config.getRelativeBoldFontPath(), BaseFont.CP1252,
            BaseFont.EMBEDDED);
    BaseFont fontThin = BaseFont.createFont(
            app.getContext().getBaseDirectory() + Config.getRelativeThinFontPath(), BaseFont.CP1252,
            BaseFont.EMBEDDED);

    lernentwicklungsberichtUeberschriftFont = new Font(fontThin, 22, Font.NORMAL);
    standardTextFont = new Font(fontNormal, KlassenstufenUtils.getLebFontSize(lebData.getKlassenname()),
            Font.NORMAL);
    standardTextBoldFont = new Font(fontBold, KlassenstufenUtils.getLebFontSize(lebData.getKlassenname()),
            Font.NORMAL);
    headerFont = new Font(fontNormal, 12, Font.NORMAL);
    footerFont = new Font(fontNormal, 10, Font.NORMAL);
    fusszeilenFont = new Font(fontNormal, 8, Font.NORMAL);
    zeilenabstandsfaktor = KlassenstufenUtils.getLebZeilenabstandAsFactor(lebData.getKlassenname());
    document = null;
    try {
        document = new Document(PageSize.A4, 100, 90, topMargin, bottomMargin);
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        LebPageHelper event = new LebPageHelper(lebData,
                Image.getInstance(app.getContext().getBaseDirectory() + Config.getRelativeLogoPath()),
                fusszeilenFont);
        writer.setPageEvent(event);
        document.open();
        addContent(writer);
        addFooter(lebData, writer);
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:org.ganttproject.impex.htmlpdf.itext.ThemeImpl.java

License:GNU General Public License

private Font getSansRegular(float size) {
    return myFontCache.getFont(getFontName(), getCharset(), Font.NORMAL, size);
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ? iTextAsian.jar//w  ww .  j a  v a  2s  .c  om
 * itext 5.5.9 ???
 *
 * @return
 */
@Deprecated
private static Font getChineseFont() {
    Font fontChinese = null;
    try {
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        fontChinese = new Font(bfChinese, 12, Font.NORMAL);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    return fontChinese;
}

From source file:org.inspira.condominio.pdf.DocumentoEgresos.java

public void exportarPdf(String destino) throws IOException, DocumentException {
    File file = new File(destino);
    file.getParentFile().mkdirs();//from  w  w  w  . j av a  2s  .c  o  m
    PdfWriter.getInstance(documento, new FileOutputStream(file));
    documento.open();
    documento.add(new Paragraph(
            "Periodo: ".concat(
                    DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(new Date())),
            F_NORMAL));
    documento.add(new Paragraph(admin, F_NORMAL));
    Paragraph heading = new Paragraph("Gastos ".concat(tipoDeGasto),
            new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD, new BaseColor(0x000000)));
    heading.setSpacingBefore(16f);
    heading.setSpacingAfter(16f);
    Paragraph heading2 = new Paragraph("Autoriz",
            new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, new BaseColor(0x000000)));
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    Paragraph heading3 = new Paragraph("Vo. Bo.",
            new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, new BaseColor(0x000000)));
    PdfPCell cell1 = new PdfPCell(heading2);
    cell1.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
    cell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
    cell1.setColspan(1);
    cell1.setFixedHeight(20f);
    cell1.setBorder(Rectangle.NO_BORDER);
    PdfPCell cell2 = new PdfPCell(heading3);
    cell2.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
    cell2.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
    cell2.setColspan(1);
    cell2.setFixedHeight(20f);
    cell2.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell1);
    table.addCell(cell2);
    table.setSpacingBefore(16f);
    table.setSpacingAfter(32f);

    documento.add(heading);
    agregarTablaEgresos(egresos);
    documento.add(table);
    agregarZonaVistoBueno();
    documento.close();
}

From source file:org.inspira.condominio.pdf.DocumentoEstadoDeCuenta.java

private void bakeContent(String path, String imgResString) throws IOException, DocumentException {
    File outFile = new File(path);
    outFile.getParentFile().mkdirs();/*from w  ww. ja v  a2s.  c  om*/
    PdfWriter.getInstance(documento, new FileOutputStream(outFile));
    documento.open();
    documento.add(new Paragraph(
            "Ciudad de Mxico, "
                    + DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()).format(new Date()),
            new Font(FontFamily.HELVETICA, 18, Font.NORMAL, new BaseColor(0x000000))));
    Paragraph intro = new Paragraph(new Phrase("Comprobante de estado de cuenta", F_NORMAL));
    intro.setAlignment(Paragraph.ALIGN_RIGHT);
    intro.setSpacingBefore(10f);
    documento.add(intro);
    Image image = Image.getInstance(imgResString);
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(image.getScaledWidth());
    table.setLockedWidth(true);
    PdfPCell cell = new PdfPCell();
    cell.setBorder(0);
    //cell.setCellEvent(new ImageBackgroundEvent(image));
    cell.setFixedHeight(image.getScaledHeight());
    table.addCell(cell);
    documento.add(table);
    Paragraph p1 = new Paragraph("Estado de cuenta: ".concat(idEdoCta), F_NORMAL);
    p1.setSpacingBefore(5f);
    p1.setSpacingAfter(25f);
    p1.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(p1);
    documento.add(new Paragraph("Pagos", F_NORMAL));
    agregaTablaDePagos();
    Paragraph pNotas = new Paragraph("Notas: ".concat(notas), F_NORMAL);
    pNotas.setSpacingAfter(12f);
    pNotas.setSpacingAfter(2f);
    documento.add(pNotas);
    Paragraph pAdeudos = new Paragraph("Adeudos", F_NORMAL);
    pAdeudos.setSpacingBefore(25f);
    documento.add(pAdeudos);
    agregaTablaDeAdeudos();
    documento.add(new Paragraph(
            "Recuerde que puede consultar su estado de pagos y adeudos desde la aplicacin mvil o directamente con su administrador.",
            F_NORMAL));
    Paragraph hechoPor = new Paragraph("Elabor:", F_NORMAL);
    hechoPor.setSpacingBefore(30f);
    hechoPor.setSpacingAfter(15f);
    documento.add(hechoPor);
    Paragraph nombreDelAdmin = new Paragraph(admin, F_NORMAL);
    nombreDelAdmin.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(nombreDelAdmin);
    Paragraph nombreDeCondominio = new Paragraph(condominio, F_NORMAL);
    nombreDeCondominio.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(nombreDeCondominio);
}

From source file:org.jaqpot.core.service.data.ReportService.java

public void report2PDF(Report report, OutputStream os) {

    Document document = new Document();
    document.setPageSize(PageSize.A4);//  w w  w .  jav a 2 s  . c  om
    document.setMargins(50, 45, 80, 40);
    document.setMarginMirroring(false);

    try {
        PdfWriter writer = PdfWriter.getInstance(document, os);
        TableHeader event = new TableHeader();
        writer.setPageEvent(event);

    } catch (DocumentException ex) {
        throw new InternalServerErrorException(ex);
    }

    document.open();

    /** setup fonts for pdf */
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 9, Font.ITALIC);
    Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC);
    Font paragraphFontBold = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
    Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
    Font tableFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);

    /** print link to jaqpot*/
    Chunk chunk = new Chunk(
            "This report has been automatically created by the JaqpotQuatro report service. Click here to navigate to our official webpage",
            ffont);
    chunk.setAnchor("http://www.jaqpot.org");

    Paragraph paragraph = new Paragraph(chunk);
    paragraph.add(Chunk.NEWLINE);

    Chapter chapter = new Chapter(paragraph, 1);
    chapter.setNumberDepth(0);

    /** get title */
    String title = null;
    if (report.getMeta() != null && report.getMeta().getTitles() != null
            && !report.getMeta().getTitles().isEmpty())
        title = report.getMeta().getTitles().iterator().next();

    /** print title aligned centered in page */
    if (title == null)
        title = "Report";
    chunk = new Chunk(title, chapterFont);
    paragraph = new Paragraph(chunk);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.add(Chunk.NEWLINE);
    paragraph.add(Chunk.NEWLINE);

    chapter.add(paragraph);

    /** report Description */
    if (report.getMeta() != null && report.getMeta().getDescriptions() != null
            && !report.getMeta().getDescriptions().isEmpty()
            && !report.getMeta().getDescriptions().toString().equalsIgnoreCase("null")) {
        paragraph = new Paragraph();
        paragraph.add(new Chunk("Description: ", paragraphFontBold));
        paragraph.add(new Chunk(report.getMeta().getDescriptions().toString().replaceAll(":http", ": http"),
                paragraphFont));
        chapter.add(paragraph);
        chapter.add(Chunk.NEWLINE);
    }

    /** report model, algorithm and/or dataset id */
    if (report.getMeta() != null && report.getMeta().getHasSources() != null
            && !report.getMeta().getHasSources().isEmpty() && !report.getMeta().getDescriptions().isEmpty()
            && !report.getMeta().getDescriptions().toString().equalsIgnoreCase("null")) {
        Iterator<String> sources = report.getMeta().getHasSources().iterator();
        sources.forEachRemaining(o -> {
            if (o != null) {
                String[] source = o.split("/");
                if (source[source.length - 2].trim().equals("model")
                        || source[source.length - 2].trim().equals("algorithm")
                        || source[source.length - 2].trim().equals("dataset")) {
                    Paragraph paragraph1 = new Paragraph();
                    paragraph1.add(new Chunk(source[source.length - 2].substring(0, 1).toUpperCase()
                            + source[source.length - 2].substring(1) + ": ", paragraphFontBold));
                    paragraph1.add(new Chunk(source[source.length - 1], paragraphFont));
                    chapter.add(paragraph1);
                    chapter.add(Chunk.NEWLINE);
                }
            }
        });
    }

    /** report single calculations */
    report.getSingleCalculations().forEach((key, value) -> {
        Paragraph paragraph1 = new Paragraph();
        paragraph1 = new Paragraph();
        paragraph1.add(new Chunk(key + ": ", paragraphFontBold));
        paragraph1.add(new Chunk(value.toString().trim().replaceAll(" +", " "), paragraphFont));
        chapter.add(paragraph1);
        chapter.add(Chunk.NEWLINE);
    });

    /** report date of completion */
    if (report.getMeta() != null && report.getMeta().getDate() != null) {
        Paragraph paragraph1 = new Paragraph();
        paragraph1.add(new Chunk("Procedure completed on: ", paragraphFontBold));
        paragraph1.add(new Chunk(report.getMeta().getDate().toString(), paragraphFont));
        chapter.add(paragraph1);
        chapter.add(Chunk.NEWLINE);
    }

    try {
        document.add(chapter);
    } catch (DocumentException ex) {
        throw new InternalServerErrorException(ex);
    }

    Integer chapterNumber = 0;

    /** report all_data */
    for (Entry<String, ArrayCalculation> entry : report.getArrayCalculations().entrySet()) {
        String label = entry.getKey();
        ArrayCalculation ac = entry.getValue();
        PdfPTable table = new PdfPTable(ac.getColNames().size() + 1);
        for (Entry<String, List<Object>> row : ac.getValues().entrySet()) {

            try {
                XMLWorkerHelper.getInstance().parseXHtml(w -> {
                    if (w instanceof WritableElement) {
                        List<Element> elements = ((WritableElement) w).elements();
                        for (Element element : elements) {
                            PdfPCell pdfCell = new PdfPCell();
                            pdfCell.addElement(element);
                            table.addCell(pdfCell);
                        }
                    }
                }, new StringReader(row.getKey()));
            } catch (IOException e) {
                e.printStackTrace();
            }

            for (Object o : row.getValue()) {
                table.addCell(o.toString());
            }
            table.completeRow();
        }
        try {
            Chunk tableChunk = new Chunk(label, tableFont);
            Chapter tableChapter = new Chapter(new Paragraph(tableChunk), ++chapterNumber);
            tableChapter.add(Chunk.NEWLINE);
            tableChapter.add(table);
            document.newPage();
            document.add(tableChapter);
        } catch (DocumentException ex) {
            throw new InternalServerErrorException(ex);
        }
    }

    /** report plots */
    for (Entry<String, String> entry : report.getFigures().entrySet()) {
        try {
            byte[] valueDecoded = Base64.decodeBase64(entry.getValue());
            Image l = Image.getInstance(valueDecoded);
            document.newPage();
            //image starts at the half's half of pdf page
            l.setAbsolutePosition(0, (document.getPageSize().getHeight() / 2 / 2));
            l.scaleToFit(document.getPageSize());

            Chunk tableChunk = new Chunk(entry.getKey(), tableFont);
            Chapter tableChapter = new Chapter(new Paragraph(tableChunk), ++chapterNumber);
            tableChapter.add(l);
            document.add(tableChapter);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
    document.close();
}

From source file:org.jfree.chart.swt.ChartPdf.java

License:Open Source License

public static void saveChartAsPDF(File file, JFreeChart chart, int width, int height)
        throws DocumentException, FileNotFoundException, IOException {
    if (chart != null) {
        boolean success = false;
        String old = null;//  w  w w.  j  a va2  s  .  c  o m
        File oldFile = null;
        boolean append = file.exists();
        if (append) {
            old = file.getAbsolutePath() + ".old"; //$NON-NLS-1$
            oldFile = new File(old);
            oldFile.delete();
            file.renameTo(oldFile);
        }
        try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
            // convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(width, height);
            if (append) {
                PdfReader reader = new PdfReader(old);
                PdfStamper stamper = new PdfStamper(reader, out);
                try {
                    int n = reader.getNumberOfPages() + 1;
                    stamper.insertPage(n, pagesize);
                    PdfContentByte overContent = stamper.getOverContent(n);
                    writeChart(chart, width, height, overContent);
                    ColumnText ct = new ColumnText(overContent);
                    ct.setSimpleColumn(width - 50, 50, width - 12, height, 150, Element.ALIGN_RIGHT);
                    Paragraph paragraph = new Paragraph(String.valueOf(n),
                            new Font(FontFamily.HELVETICA, 9, Font.NORMAL, BaseColor.DARK_GRAY));
                    paragraph.setAlignment(Element.ALIGN_RIGHT);
                    ct.addElement(paragraph);
                    ct.go();
                    success = true;
                } finally {
                    stamper.close();
                    reader.close();
                    oldFile.delete();
                }
            } else {
                Document document = new Document(pagesize, 50, 50, 50, 50);
                document.addCreationDate();
                document.addCreator(Constants.APPLICATION_NAME);
                document.addAuthor(System.getProperty("user.name")); //$NON-NLS-1$
                try {
                    PdfWriter writer = PdfWriter.getInstance(document, out);
                    document.open();
                    writeChart(chart, width, height, writer.getDirectContent());
                    success = true;
                } finally {
                    document.close();
                }
            }
        }
        if (!success) {
            file.delete();
            if (oldFile != null)
                oldFile.renameTo(file);
        }
    }
}

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 w  w w . j a  v a2s .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  ww  .  j av a  2  s.c o 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 w  ww .j a va2  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");
}