Example usage for com.lowagie.text.pdf BaseFont createFont

List of usage examples for com.lowagie.text.pdf BaseFont createFont

Introduction

In this page you can find the example usage for com.lowagie.text.pdf BaseFont createFont.

Prototype

public static BaseFont createFont(String name, String encoding, boolean embedded)
        throws DocumentException, IOException 

Source Link

Document

Creates a new font.

Usage

From source file:org.xhtmlrenderer.pdf.ITextFontResolver.java

License:Open Source License

private static BaseFont createFont(String name, String encoding, boolean embedded)
        throws DocumentException, IOException {
    return BaseFont.createFont(name, encoding, embedded);
}

From source file:oscar.eform.util.EFormPDFServlet.java

License:Open Source License

private void writeContent(Properties printCfg, Properties props, Properties measurements, float height,
        PdfContentByte cb) throws Exception {
    for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) {
        StringBuilder temp = new StringBuilder(e.nextElement().toString());
        String[] cfgVal = printCfg.getProperty(temp.toString()).split(" *, *");

        String[] fontType = null;
        int fontFlags = 0;
        if (cfgVal[4].indexOf(";") > -1) {
            fontType = cfgVal[4].split(";");
            if (fontType[1].trim().equals("italic"))
                fontFlags = Font.ITALIC;
            else if (fontType[1].trim().equals("bold"))
                fontFlags = Font.BOLD;
            else if (fontType[1].trim().equals("bolditalic"))
                fontFlags = Font.BOLDITALIC;
            else//ww  w .  j  ava 2s .c o  m
                fontFlags = Font.NORMAL;
        } else {
            fontFlags = Font.NORMAL;
            fontType = new String[] { cfgVal[4].trim() };
        }

        String encoding = null;
        if (fontType[0].trim().equals("BaseFont.HELVETICA")) {
            fontType[0] = BaseFont.HELVETICA;
            encoding = BaseFont.CP1252; //latin1 encoding
        } else if (fontType[0].trim().equals("BaseFont.HELVETICA_OBLIQUE")) {
            fontType[0] = BaseFont.HELVETICA_OBLIQUE;
            encoding = BaseFont.CP1252;
        } else if (fontType[0].trim().equals("BaseFont.ZAPFDINGBATS")) {
            fontType[0] = BaseFont.ZAPFDINGBATS;
            encoding = BaseFont.ZAPFDINGBATS;
        } else {
            fontType[0] = BaseFont.COURIER;
            encoding = BaseFont.CP1252;
        }

        BaseFont bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED);
        String propValue = props.getProperty(temp.toString());
        //if not in regular config then check measurements
        if (propValue == null) {
            propValue = measurements.getProperty(temp.toString(), "");
        }

        ColumnText ct = new ColumnText(cb);
        // write in a rectangle area
        if (cfgVal.length >= 9) {
            Font font = new Font(bf, Integer.parseInt(cfgVal[5].trim()), fontFlags);
            ct.setSimpleColumn(Integer.parseInt(cfgVal[1].trim()),
                    (height - Integer.parseInt(cfgVal[2].trim())), Integer.parseInt(cfgVal[7].trim()),
                    (height - Integer.parseInt(cfgVal[8].trim())), Integer.parseInt(cfgVal[9].trim()),
                    (cfgVal[0].trim().equals("left") ? Element.ALIGN_LEFT
                            : (cfgVal[0].trim().equals("right") ? Element.ALIGN_RIGHT : Element.ALIGN_CENTER)));

            ct.setText(new Phrase(12, propValue, font));
            ct.go();
            continue;
        }

        // draw line directly
        if (temp.toString().startsWith("__$line")) {
            cb.setRGBColorStrokeF(0f, 0f, 0f);
            cb.setLineWidth(Float.parseFloat(cfgVal[4].trim()));
            cb.moveTo(Float.parseFloat(cfgVal[0].trim()), Float.parseFloat(cfgVal[1].trim()));
            cb.lineTo(Float.parseFloat(cfgVal[2].trim()), Float.parseFloat(cfgVal[3].trim()));
            cb.stroke();

        } else if (temp.toString().startsWith("__")) {
            cb.beginText();
            cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
            cb.showTextAligned(
                    (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                            : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                    : PdfContentByte.ALIGN_CENTER)),
                    (cfgVal.length >= 7 ? (cfgVal[6].trim()) : propValue), Integer.parseInt(cfgVal[1].trim()),
                    (height - Integer.parseInt(cfgVal[2].trim())), 0);
            cb.endText();
        } else { // write prop text
            cb.beginText();
            cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
            cb.showTextAligned(
                    (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                            : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                    : PdfContentByte.ALIGN_CENTER)),
                    (cfgVal.length >= 7 ? ((propValue.equals("") ? "" : cfgVal[6].trim())) : propValue),
                    Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

            cb.endText();
        }
    }
}

From source file:oscar.form.pdfservlet.FrmCustomedPDFServlet.java

License:Open Source License

protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx)
        throws DocumentException {
    logger.debug("***in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***");
    // added by vic, hsfo
    Enumeration<String> em = req.getParameterNames();
    while (em.hasMoreElements()) {
        logger.debug("para=" + em.nextElement());
    }/*  w w  w  . ja va2 s.  co m*/
    em = req.getAttributeNames();
    while (em.hasMoreElements())
        logger.debug("attr: " + em.nextElement());

    if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) {
        return generateHsfoRxPDF(req);
    }
    String newline = System.getProperty("line.separator");

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter writer = null;
    String method = req.getParameter("__method");
    String origPrintDate = null;
    String numPrint = null;
    if (method != null && method.equalsIgnoreCase("rePrint")) {
        origPrintDate = req.getParameter("origPrintDate");
        numPrint = req.getParameter("numPrints");
    }

    logger.debug("method in generatePDFDocumentBytes " + method);
    String clinicName;
    String clinicTel;
    String clinicFax;
    // check if satellite clinic is used
    String useSatelliteClinic = req.getParameter("useSC");
    logger.debug(useSatelliteClinic);
    if (useSatelliteClinic != null && useSatelliteClinic.equalsIgnoreCase("true")) {
        String scAddress = req.getParameter("scAddress");
        logger.debug("clinic detail" + "=" + scAddress);
        HashMap<String, String> hm = parseSCAddress(scAddress);
        clinicName = hm.get("clinicName");
        clinicTel = hm.get("clinicTel");
        clinicFax = hm.get("clinicFax");
    } else {
        // parameters need to be passed to header and footer
        clinicName = req.getParameter("clinicName");
        logger.debug("clinicName" + "=" + clinicName);
        clinicTel = req.getParameter("clinicPhone");
        clinicFax = req.getParameter("clinicFax");
    }
    String patientPhone = req.getParameter("patientPhone");
    String patientCityPostal = req.getParameter("patientCityPostal");
    String patientAddress = req.getParameter("patientAddress");
    String patientName = req.getParameter("patientName");
    String sigDoctorName = req.getParameter("sigDoctorName");
    String rxDate = req.getParameter("rxDate");
    String rx = req.getParameter("rx");
    String patientDOB = req.getParameter("patientDOB");
    String showPatientDOB = req.getParameter("showPatientDOB");
    String imgFile = req.getParameter("imgFile");
    String patientHIN = req.getParameter("patientHIN");
    String patientChartNo = req.getParameter("patientChartNo");
    String pracNo = req.getParameter("pracNo");
    Locale locale = req.getLocale();

    boolean isShowDemoDOB = false;
    if (showPatientDOB != null && showPatientDOB.equalsIgnoreCase("true")) {
        isShowDemoDOB = true;
    }
    if (!isShowDemoDOB)
        patientDOB = "";
    if (rx == null) {
        rx = "";
    }

    String additNotes = req.getParameter("additNotes");
    String[] rxA = rx.split(newline);
    List<String> listRx = new ArrayList<String>();
    String listElem = "";
    // parse rx and put into a list of rx;
    for (String s : rxA) {

        if (s.equals("") || s.equals(newline) || s.length() == 1) {
            listRx.add(listElem);
            listElem = "";
        } else {
            listElem = listElem + s;
            listElem += newline;
        }

    }

    // get the print prop values
    Properties props = new Properties();
    StringBuilder temp = new StringBuilder();
    for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) {
        temp = new StringBuilder(e.nextElement().toString());
        props.setProperty(temp.toString(), req.getParameter(temp.toString()));
    }

    for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) {
        temp = new StringBuilder(e.nextElement().toString());
        props.setProperty(temp.toString(), req.getAttribute(temp.toString()).toString());
    }
    Document document = new Document();

    try {
        String title = req.getParameter("__title") != null ? req.getParameter("__title") : "Unknown";

        // specify the page of the picture using __graphicPage, it may be used multiple times to specify multiple pages
        // however the same graphic will be applied to all pages
        // ie. __graphicPage=2&__graphicPage=3
        String[] cfgGraphicFile = req.getParameterValues("__cfgGraphicFile");
        int cfgGraphicFileNo = cfgGraphicFile == null ? 0 : cfgGraphicFile.length;
        if (cfgGraphicFile != null) {
            // for (String s : cfgGraphicFile) {
            // p("cfgGraphicFile", s);
            // }
        }

        String[] graphicPage = req.getParameterValues("__graphicPage");
        ArrayList<String> graphicPageArray = new ArrayList<String>();
        if (graphicPage != null) {
            // for (String s : graphicPage) {
            // p("graphicPage", s);
            // }
            graphicPageArray = new ArrayList<String>(Arrays.asList(graphicPage));
        }

        // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA
        // and FLSE
        // the following shows a temp way to get a print page size
        Rectangle pageSize = PageSize.LETTER;
        String pageSizeParameter = req.getParameter("rxPageSize");
        if (pageSizeParameter != null) {
            if ("PageSize.HALFLETTER".equals(pageSizeParameter)) {
                pageSize = PageSize.HALFLETTER;
            } else if ("PageSize.A6".equals(pageSizeParameter)) {
                pageSize = PageSize.A6;
            } else if ("PageSize.A4".equals(pageSizeParameter)) {
                pageSize = PageSize.A4;
            }
        }
        /*
         * if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A6; } else if
         * ("PageSize.A4".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A4; }
         */
        // p("size of page ", props.getProperty(PAGESIZE));

        document.setPageSize(pageSize);
        // 285=left margin+width of box, 5f is space for looking nice
        document.setMargins(15, pageSize.getWidth() - 285f + 5f, 170, 60);// left, right, top , bottom

        writer = PdfWriter.getInstance(document, baosPDF);
        writer.setPageEvent(new EndPage(clinicName, clinicTel, clinicFax, patientPhone, patientCityPostal,
                patientAddress, patientName, patientDOB, sigDoctorName, rxDate, origPrintDate, numPrint,
                imgFile, patientHIN, patientChartNo, pracNo, locale));
        document.addTitle(title);
        document.addSubject("");
        document.addKeywords("pdf, itext");
        document.addCreator("OSCAR");
        document.addAuthor("");
        document.addHeader("Expires", "0");

        document.open();
        document.newPage();

        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf; // = normFont;

        cb.setRGBColorStroke(0, 0, 255);
        // render prescriptions
        for (String rxStr : listRx) {
            bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(new Phrase(rxStr, new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(5f);
            document.add(p);
        }
        // render additional notes
        if (additNotes != null && !additNotes.equals("")) {
            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(new Phrase(additNotes, new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(10f);
            document.add(p);
        }
        // render optometristEyeParam
        if (req.getAttribute("optometristEyeParam") != null) {
            bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(
                    new Phrase("Eye " + (String) req.getAttribute("optometristEyeParam"), new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(15f);
            document.add(p);
        }

        // render QrCode
        if (PrescriptionQrCodeUIBean.isPrescriptionQrCodeEnabledForCurrentProvider()) {
            Integer scriptId = Integer.parseInt(req.getParameter("scriptId"));
            byte[] qrCodeImage = PrescriptionQrCodeUIBean.getPrescriptionHl7QrCodeImage(scriptId);
            Image qrCode = Image.getInstance(qrCodeImage);
            document.add(qrCode);
        }

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } catch (Exception e) {
        logger.error("Error", e);
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
    logger.debug("***END in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***");
    return baosPDF;
}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.ConsultationPDFCreator.java

License:Open Source License

/**
 * Prints the consultation request.// w w w.  ja v a2  s .  c om
 * @throws IOException when an error with the output stream occurs
 * @throws DocumentException when an error in document construction occurs
 */
public void printPdf() throws IOException, DocumentException {

    // Create the document we are going to write to
    document = new Document();
    PdfWriter.getInstance(document, os);

    document.setPageSize(PageSize.LETTER);
    document.addTitle(getResource("msgConsReq"));
    document.addCreator("OSCAR");
    document.open();

    // Create the fonts that we are going to use
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    headerFont = new Font(bf, 14, Font.BOLD);
    infoFont = new Font(bf, 12, Font.NORMAL);
    font = new Font(bf, 9, Font.NORMAL);
    boldFont = new Font(bf, 10, Font.BOLD);
    bigBoldFont = new Font(bf, 12, Font.BOLD);

    createConsultationRequest();

    document.close();
}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.EctConsultationFormRequestPrintPdf.java

License:Open Source License

public void printPdf() throws IOException, DocumentException {

    EctConsultationFormRequestUtil reqForm = new EctConsultationFormRequestUtil();
    reqForm.estRequestFromId((String) request.getAttribute("reqId"));

    //make sure we have data to print
    if (reqForm == null)
        throw new DocumentException();

    // init req form info
    reqForm.specAddr = request.getParameter("address");
    if (reqForm.specAddr == null) {
        reqForm.specAddr = new String();
    }/*from  w w w.jav a  2  s . c om*/
    reqForm.specPhone = request.getParameter("phone");
    if (reqForm.specPhone == null) {
        reqForm.specPhone = "";
    }
    reqForm.specFax = request.getParameter("fax");
    if (reqForm.specFax == null) {
        reqForm.specFax = "";
    }

    //Create new file to save form to
    String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    String fileName = path + "ConsultationRequestForm-" + UtilDateUtilities.getToday("yyyy-MM-dd.hh.mm.ss")
            + ".pdf";
    FileOutputStream out = new FileOutputStream(fileName);

    //Create the document we are going to write to
    document = new Document();
    writer = PdfWriter.getInstance(document, out);

    //Use the template located at '/oscar/oscarEncounter/oscarConsultationRequest/props'
    reader = new PdfReader("/oscar/oscarEncounter/oscarConsultationRequest/props/consultationFormRequest.pdf");
    Rectangle pSize = reader.getPageSize(1);
    width = pSize.getWidth();
    height = pSize.getHeight();
    document.setPageSize(pSize);

    document.addTitle("Consultation Form Request");
    document.addCreator("OSCAR");
    document.open();

    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

    cb = writer.getDirectContent();
    ct = new ColumnText(cb);
    cb.setColorStroke(new Color(0, 0, 0));

    // start writing the pdf document
    PdfImportedPage page1 = writer.getImportedPage(reader, 1);
    cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);
    addFooter();
    setAppointmentInfo(reqForm);

    // add the dynamically positioned text elements
    float dynamicHeight = 0;
    dynamicHeight = addDynamicPositionedText("Reason For Consultation: ", reqForm.reasonForConsultation,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Pertinent Clinical Information: ", reqForm.clinicalInformation,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Significant Concurrent Problems: ", reqForm.concurrentProblems,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Current Medications: ", reqForm.currentMedications, dynamicHeight,
            reqForm);
    dynamicHeight = addDynamicPositionedText("Allergies: ", reqForm.allergies, dynamicHeight, reqForm);

    document.close();
    reader.close();
    writer.close();
    out.close();

    // combine the recently created pdf with any pdfs that were added to the consultation request form
    combinePDFs(fileName);

}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.EctConsultationFormRequestPrintPdf.java

License:Open Source License

private void addFooter() throws DocumentException, IOException {
    cb.beginText();//from   ww  w  . j a v a  2  s  . c  o  m
    cb.setFontAndSize(bf, FONTSIZE);
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "-" + PAGENUM + "-", width / 2, 30, 0);
    cb.endText();

    // add promotext if it is enabled
    if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
        cb.beginText();
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 6);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), width / 2, 19, 0);
        cb.endText();
    }
}

From source file:oscar.oscarLab.ca.all.pageUtil.LabPDFCreator.java

License:Open Source License

public void printPdf() throws IOException, DocumentException {

    // check that we have data to print
    if (handler == null)
        throw new DocumentException();

    //response.setContentType("application/pdf");  //octet-stream
    //response.setHeader("Content-Disposition", "attachment; filename=\""+handler.getPatientName().replaceAll("\\s", "_")+"_LabReport.pdf\"");

    //Create the document we are going to write to
    document = new Document();
    //PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    PdfWriter writer = PdfWriter.getInstance(document, os);

    //Set page event, function onEndPage will execute each time a page is finished being created
    writer.setPageEvent(this);

    document.setPageSize(PageSize.LETTER);
    document.addTitle("Title of the Document");
    document.addCreator("OSCAR");
    document.open();/*  w w w  .jav  a 2  s  .  c  om*/

    //Create the fonts that we are going to use
    bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, 9, Font.NORMAL);
    boldFont = new Font(bf, 10, Font.BOLD);
    redFont = new Font(bf, 9, Font.NORMAL, Color.RED);

    // add the header table containing the patient and lab info to the document
    createInfoTable();

    // add the tests and test info for each header
    ArrayList<String> headers = handler.getHeaders();
    for (int i = 0; i < headers.size(); i++)
        addLabCategory(headers.get(i));

    // add end of report table
    PdfPTable table = new PdfPTable(1);
    table.setWidthPercentage(100);
    PdfPCell cell = new PdfPCell();
    cell.setBorder(0);
    cell.setPhrase(new Phrase("  "));
    table.addCell(cell);
    cell.setBorder(15);
    cell.setBackgroundColor(new Color(210, 212, 255));
    cell.setPhrase(new Phrase("END OF REPORT", boldFont));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);
    document.add(table);

    document.close();

    os.flush();
}

From source file:oscar.oscarLab.ca.all.pageUtil.LabPDFCreator.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    try {/*  w  w  w  .ja va  2  s  . c o  m*/

        Rectangle page = document.getPageSize();
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        int pageNum = document.getPageNumber();
        float width = page.getWidth();
        float height = page.getHeight();

        //add patient name header for every page but the first.
        if (pageNum > 1) {
            cb.beginText();
            cb.setFontAndSize(bf, 8);
            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, handler.getPatientName(), 575, height - 30, 0);
            cb.endText();

        }

        //add footer for every page
        cb.beginText();
        cb.setFontAndSize(bf, 8);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "-" + pageNum + "-", width / 2, 30, 0);
        cb.endText();

        // add promotext as footer if it is enabled
        if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
            cb.beginText();
            cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED),
                    6);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                    OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), width / 2, 19, 0);
            cb.endText();
        }

        // throw any exceptions
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:oscar.oscarPrevention.pageUtil.PreventionPrintPdf.java

License:Open Source License

public void printPdf(String[] headerIds, HttpServletRequest request, OutputStream outputStream)
        throws IOException, DocumentException {
    //make sure we have data to print
    //String[] headerIds = request.getParameterValues("printHP");
    if (headerIds == null)
        throw new DocumentException();

    //Create the document we are going to write to
    document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.setPageSize(PageSize.LETTER);
    document.open();//  w w  w  .jav  a2 s  .c om

    //Create the font we are going to print to
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    Font font = new Font(bf, FONTSIZE, Font.NORMAL);
    float leading = font.getCalculatedLeading(LINESPACING);

    //set up document title and header
    String title = "Preventions for " + request.getParameter("nameAge");
    String hin = "HIN: " + request.getParameter("hin");
    String mrp = request.getParameter("mrp");
    if (mrp != null) {
        Properties prop = (Properties) request.getSession().getAttribute("providerBean");
        mrp = "MRP: " + prop.getProperty(mrp, "unknown");
    }

    ClinicData clinicData = new ClinicData();
    clinicData.refreshClinicData();
    String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(),
            clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(),
            clinicData.getClinicPhone(), title, hin, mrp };

    //Header will be printed at top of every page beginning with p2
    Phrase headerPhrase = new Phrase(LEADING, title, font);
    HeaderFooter header = new HeaderFooter(headerPhrase, false);
    header.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setHeader(header);

    //Write title with top and bottom borders on p1
    cb = writer.getDirectContent();
    cb.setColorStroke(new Color(0, 0, 0));
    cb.setLineWidth(0.5f);

    cb.moveTo(document.left(), document.top());
    cb.lineTo(document.right(), document.top());
    cb.stroke();
    cb.setFontAndSize(bf, FONTSIZE);

    upperYcoord = document.top() - (font.getCalculatedLeading(LINESPACING) * 2f);
    cb.beginText();
    for (int idx = 0; idx < clinic.length; ++idx) {
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, clinic[idx], document.right() / 2f, upperYcoord, 0f);
        upperYcoord -= font.getCalculatedLeading(LINESPACING);
    }

    cb.endText();
    cb.moveTo(document.left(), upperYcoord);
    cb.lineTo(document.right(), upperYcoord);
    cb.stroke();

    //get top y-coord for starting to print columns
    upperYcoord = cb.getYTLM() - font.getCalculatedLeading(LINESPACING * 2f);

    int subIdx;
    String preventionHeader, procedureAge, procedureDate;

    //1 - obtain number of lines of incoming prevention data
    numLines = 0;
    for (int idx = 0; idx < headerIds.length; ++idx) {
        ++numLines;
        subIdx = 0;
        while (request.getParameter("preventProcedureAge" + headerIds[idx] + "-" + subIdx) != null) {
            ++subIdx;
            numLines += 3;
        }
        numLines += 2;
    }

    //2 - calculate max num of lines a page can hold and number of pages of data we have
    pageHeight = upperYcoord - document.bottom();
    maxLines = (int) Math.floor(pageHeight / (font.getCalculatedLeading(LINESPACING) + 4d));
    numPages = (int) Math.ceil(numLines / ((double) maxLines * NUMCOLS));

    //3 - Start the column
    ct = new ColumnText(cb);
    ct.setSimpleColumn(document.left(), document.bottom(), document.right() / 2f, upperYcoord);

    linesToBeWritten = linesWritten = 0;
    boolean pageBreak = false;

    curPage = 1;
    totalLinesWritten = 0;

    //add promotext to current page
    addPromoText();

    //if we have > 1 element but less than a page of data, shrink maxLines so we can try to balance text in columns
    if (headerIds.length > 1) {
        if (curPage == numPages) {
            maxLines = numLines / NUMCOLS;
        }
    }

    //now we can start to print the prevention data
    for (int idx = 0; idx < headerIds.length; ++idx) {

        linesToBeWritten = 4; //minimum lines for header and one prevention item
        pageBreak = checkColumnFill(ct, "", font, pageBreak); //if necessary break before we print prevention header

        preventionHeader = request.getParameter("preventionHeader" + headerIds[idx]);
        Phrase procHeader = new Phrase(LEADING, "Prevention " + preventionHeader + "\n", font);
        ct.addText(procHeader);
        subIdx = 0;

        while ((procedureAge = request
                .getParameter("preventProcedureAge" + headerIds[idx] + "-" + subIdx)) != null) {
            procedureDate = request.getParameter("preventProcedureDate" + headerIds[idx] + "-" + subIdx);

            linesToBeWritten = 3;
            pageBreak = checkColumnFill(ct, preventionHeader, font, pageBreak);

            Phrase procedure = new Phrase(LEADING, "     " + procedureAge + "\n", font);
            procedure.add("     " + procedureDate + "\n\n");
            ct.addText(procedure);
            ct.go();
            linesWritten += ct.getLinesWritten();
            totalLinesWritten += ct.getLinesWritten();
            ++subIdx;
        }

    }

    ColumnText.showTextAligned(cb, Phrase.ALIGN_CENTER, new Phrase("-" + curPage + "-"), document.right() / 2f,
            document.bottom() - (document.bottomMargin() / 2f), 0f);

    document.close();
}

From source file:oscar.oscarPrevention.pageUtil.PreventionPrintPdf.java

License:Open Source License

private void addPromoText() throws DocumentException, IOException {
    if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
        cb.beginText();//from   w w w .ja  v a 2  s  . c om
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 6);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), PageSize.LETTER.getWidth() / 2, 5,
                0);
        cb.endText();
    }
}