Example usage for com.lowagie.text.pdf PdfContentByte addTemplate

List of usage examples for com.lowagie.text.pdf PdfContentByte addTemplate

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte addTemplate.

Prototype

public void addTemplate(PdfTemplate template, float a, float b, float c, float d, float e, float f) 

Source Link

Document

Adds a template to this content.

Usage

From source file:org.kuali.kra.printing.service.impl.PrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList//from   www  .  j  a v a  2s .  c  o m
 *            List containing the PDF data bytes
 * @param bookmarksList
 *            List of bookmarks corresponding to the PDF bytes.
 * @return
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark());  //  add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.mapfish.print.PDFCustomBlocks.java

License:Open Source License

private void addBackground(PdfWriter writer, Document document, PdfContentByte dc) {
    if (backgroundPdf != null) {
        try {//from   w ww  .j av  a 2  s.co  m
            PdfImportedPage page = backgroundPdfs.get(backgroundPdf);
            if (page == null) {
                PdfReader reader = new PdfReader(backgroundPdf);
                page = writer.getImportedPage(reader, 1);
                backgroundPdfs.put(backgroundPdf, page);
            }
            final Rectangle pageSize = document.getPageSize();
            final boolean rotate = (page.getWidth() < page.getHeight())
                    ^ (pageSize.getWidth() < pageSize.getHeight());
            if (rotate) {
                dc.addTemplate(page, 0, -1, 1, 0, 0, pageSize.getHeight());
            } else {
                dc.addTemplate(page, 0, 0);
            }
        } catch (IOException e) {
            addError(e);
        }
    }
}

From source file:org.oscarehr.phr.web.PHRUserManagementAction.java

License:Open Source License

public ByteArrayOutputStream generateUserRegistrationLetter(String demographicNo, String username,
        String password) throws Exception {
    log.debug("Demographic " + demographicNo + " username " + username + " password " + password);
    DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao");
    Demographic demographic = demographicDao.getDemographic(demographicNo);

    final String PAGESIZE = "printPageSize";
    Document document = new Document();

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter writer = null;/*from w  ww  . java2s .  c om*/

    try {
        writer = PdfWriter.getInstance(document, baosPDF);

        String title = "TITLE";
        String template = "MyOscarLetterHead.pdf";

        Properties printCfg = getCfgProp();

        String[] cfgVal = null;
        StringBuilder tempName = null;

        // get the print prop values

        Properties props = new Properties();
        props.setProperty("letterDate", UtilDateUtilities.getToday("yyyy-MM-dd"));
        props.setProperty("name", demographic.getFirstName() + " " + demographic.getLastName());
        props.setProperty("dearname", demographic.getFirstName() + " " + demographic.getLastName());
        props.setProperty("address", demographic.getAddress());
        props.setProperty("city", demographic.getCity() + ", " + demographic.getProvince());
        props.setProperty("postalCode", demographic.getPostal());
        props.setProperty("credHeading", "MyOscar User Account Details");
        props.setProperty("username", "Username: " + username);
        props.setProperty("password", "Password: " + password);
        //Temporary - the intro will change to be dynamic
        props.setProperty("intro",
                "We are pleased to provide you with a log in and password for your new MyOSCAR Personal Health Record. This account will allow you to connect electronically with our clinic. Please take a few minutes to review the accompanying literature for further information.We look forward to you benefiting from this service.");

        document.addTitle(title);
        document.addSubject("");
        document.addKeywords("pdf, itext");
        document.addCreator("OSCAR");
        document.addAuthor("");
        document.addHeader("Expires", "0");

        Rectangle pageSize = PageSize.LETTER;

        document.setPageSize(pageSize);
        document.open();

        // create a reader for a certain document
        String propFilename = oscar.OscarProperties.getInstance().getProperty("pdfFORMDIR", "") + "/"
                + template;
        PdfReader reader = null;
        try {
            reader = new PdfReader(propFilename);
            log.debug("Found template at " + propFilename);
        } catch (Exception dex) {
            log.debug("change path to inside oscar from :" + propFilename);
            reader = new PdfReader("/oscar/form/prop/" + template);
            log.debug("Found template at /oscar/form/prop/" + template);
        }

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // retrieve the size of the first page
        Rectangle pSize = reader.getPageSize(1);
        float width = pSize.getWidth();
        float height = pSize.getHeight();
        log.debug("Width :" + width + " Height: " + height);

        PdfContentByte cb = writer.getDirectContent();
        ColumnText ct = new ColumnText(cb);
        int fontFlags = 0;

        document.newPage();
        PdfImportedPage page1 = writer.getImportedPage(reader, 1);
        cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);

        BaseFont bf; // = normFont;
        String encoding;

        cb.setRGBColorStroke(0, 0, 255);

        String[] fontType;
        for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) {
            tempName = new StringBuilder(e.nextElement().toString());
            cfgVal = printCfg.getProperty(tempName.toString()).split(" *, *");

            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
                    fontFlags = Font.NORMAL;
            } else {
                fontFlags = Font.NORMAL;
                fontType = new String[] { cfgVal[4].trim() };
            }

            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;
            }

            bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED);

            // 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, props.getProperty(tempName.toString(), ""), font));
                ct.go();
                continue;
            }

            // draw line directly
            if (tempName.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()));
                // stroke the lines
                cb.stroke();
                // write text directly

            } else if (tempName.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()) : props.getProperty(tempName.toString(), "")),
                        Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

                cb.endText();
            } else if (tempName.toString().equals("forms_promotext")) {
                if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
                    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)),
                            OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"),
                            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 ? ((props.getProperty(tempName.toString(), "").equals("") ? ""
                                : cfgVal[6].trim())) : props.getProperty(tempName.toString(), "")),
                        Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

                cb.endText();
            }
        }

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } finally {
        if (document != null)
            document.close();
        if (writer != null)
            writer.close();
    }
    return baosPDF;
}

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

License:Open Source License

/**
 * the form txt file has lines in the form:
 *
 * For Checkboxes:/* www .j av  a2s  .  c o m*/
 * ie.  ohip : left, 76, 193, 0, BaseFont.ZAPFDINGBATS, 8, \u2713
 * requestParamName : alignment, Xcoord, Ycoord, 0, font, fontSize, textToPrint[if empty, prints the value of the request param]
 * NOTE: the Xcoord and Ycoord refer to the bottom-left corner of the element
 *
 * For single-line text:
 * ie. patientCity  : left, 242, 261, 0, BaseFont.HELVETICA, 12
 * See checkbox explanation
 *
 * For multi-line text (textarea)
 * ie.  aci : left, 20, 308, 0, BaseFont.HELVETICA, 8, _, 238, 222, 10
 * requestParamName : alignment, bottomLeftXcoord, bottomLeftYcoord, 0, font, fontSize, _, topRightXcoord, topRightYcoord, spacingBtwnLines
 *
 *NOTE: When working on these forms in linux, it helps to load the PDF file into gimp, switch to pt. coordinate system and use the mouse to find the coordinates.
 *Prepare to be bored!
 *
 *
 * @throws Exception 
 */
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx,
        int multiple) throws Exception {

    // added by vic, hsfo
    if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title")))
        return generateHsfoRxPDF(req);

    String suffix = (multiple > 0) ? String.valueOf(multiple) : "";

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baosPDF);

        String title = req.getParameter("__title" + suffix) != null ? req.getParameter("__title" + suffix)
                : "Unknown";
        String template = req.getParameter("__template" + suffix) != null
                ? req.getParameter("__template" + suffix) + ".pdf"
                : "";

        int numPages = 1;
        String pages = req.getParameter("__numPages" + suffix);
        if (pages != null) {
            numPages = Integer.parseInt(pages);
        }

        //load config files
        Properties[] printCfg = loadPrintCfg(req, suffix);
        Properties[][] graphicCfg = loadGraphicCfg(req, suffix, numPages);
        int cfgFileNo = printCfg == null ? 0 : printCfg.length;

        Properties props = new Properties();
        getPrintPropValues(props, req, suffix);

        Properties measurements = new Properties();

        //initialise measurement collections = a list of pages sections measurements
        List<List<List<String>>> xMeasurementValues = new ArrayList<List<List<String>>>();
        List<List<List<String>>> yMeasurementValues = new ArrayList<List<List<String>>>();
        for (int idx = 0; idx < numPages; ++idx) {
            MiscUtils.getLogger().debug("Adding page " + idx);
            xMeasurementValues.add(new ArrayList<List<String>>());
            yMeasurementValues.add(new ArrayList<List<String>>());
        }

        saveMeasurementValues(measurements, props, req, numPages, xMeasurementValues, yMeasurementValues);
        addDocumentProps(document, title, props);

        // create a reader for a certain document
        String propFilename = OscarProperties.getInstance().getProperty("eform_image", "") + "/" + template;
        PdfReader reader = null;

        try {
            reader = new PdfReader(propFilename);
            log.debug("Found template at " + propFilename);
        } catch (Exception dex) {
            log.warn("Cannot find template at : " + propFilename);
        }

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // retrieve the size of the first page
        Rectangle pSize = reader.getPageSize(1);
        float height = pSize.getHeight();

        PdfContentByte cb = writer.getDirectContent();
        int i = 0;

        while (i < n) {
            document.newPage();

            i++;
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);

            cb.setRGBColorStroke(0, 0, 255);
            // LEFT/CENTER/RIGHT, X, Y,

            if (i <= cfgFileNo) {
                writeContent(printCfg[i - 1], props, measurements, height, cb);
            } //end if there are print properties

            //graphic
            Properties[] tempPropertiesArray;
            if (i <= graphicCfg.length) {
                tempPropertiesArray = graphicCfg[i - 1];
                MiscUtils.getLogger().debug("Plotting page " + i);
            } else {
                tempPropertiesArray = null;
                MiscUtils.getLogger().debug("Skipped Plotting page " + i);
            }

            //if there are properties to plot
            if (tempPropertiesArray != null) {
                MiscUtils.getLogger().debug("TEMP PROP LENGTH " + tempPropertiesArray.length);
                for (int k = 0; k < tempPropertiesArray.length; k++) {

                    //initialise with measurement values which are mapped to config file by form get graphic function
                    List<String> xDate, yHeight;
                    if (xMeasurementValues.get(i - 1).size() > k && yMeasurementValues.get(i - 1).size() > k) {
                        xDate = new ArrayList<String>(xMeasurementValues.get(i - 1).get(k));
                        yHeight = new ArrayList<String>(yMeasurementValues.get(i - 1).get(k));
                    } else {
                        xDate = new ArrayList<String>();
                        yHeight = new ArrayList<String>();
                    }
                    plotProperties(tempPropertiesArray[k], props, xDate, yHeight, height, cb, (k % 2 == 0));
                }
            } //end: if there are properties to plot
        }
    } finally {
        if (document.isOpen())
            document.close();
        if (writer != null)
            writer.close();
    }
    return baosPDF;
}