Example usage for com.lowagie.text.pdf PdfWriter close

List of usage examples for com.lowagie.text.pdf PdfWriter close

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter close.

Prototype

public void close() 

Source Link

Document

Signals that the Document was closed and that no other Elements will be added.

Usage

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;

    try {// w w w  .j ava 2  s  .com
        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:org.pdfsam.console.business.pdf.handlers.interfaces.AbstractCmdExecutor.java

License:Open Source License

/**
 * Close the @lonk {@link PdfWriter} if not null.
 * /*from ww  w .j  a v a2s . co m*/
 * @param pdfWriter
 */
protected void closePdfWriter(PdfWriter pdfWriter) {
    if (pdfWriter != null) {
        pdfWriter.close();
        pdfWriter = null;
    }
}

From source file:org.vfny.geoserver.wms.responses.map.pdf.PDFMapProducer.java

License:Open Source License

/**
 * Writes the image to the client./* w ww. j ava  2s  .  c o  m*/
 * 
 * @param out
 *            The output stream to write to.
 */
public void writeTo(OutputStream out) throws ServiceException, java.io.IOException {
    final int width = mapContext.getMapWidth();
    final int height = mapContext.getMapHeight();

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("setting up " + width + "x" + height + " image");
    }

    try {
        // step 1: creation of a document-object
        // width of document-object is width*72 inches
        // height of document-object is height*72 inches
        com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(width, height);

        Document document = new Document(pageSize);
        document.setMargins(0, 0, 0, 0);

        // step 2: creation of the writer
        PdfWriter writer = PdfWriter.getInstance(document, out);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it

        // we create a fontMapper and read all the fonts in the font
        // directory
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();

        // we create a template and a Graphics2D object that corresponds
        // with it
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper);

        // we set graphics options
        if (!mapContext.isTransparent()) {
            graphic.setColor(mapContext.getBgColor());
            graphic.fillRect(0, 0, width, height);
        } else {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine("setting to transparent");
            }

            int type = AlphaComposite.SRC;
            graphic.setComposite(AlphaComposite.getInstance(type));

            Color c = new Color(mapContext.getBgColor().getRed(), mapContext.getBgColor().getGreen(),
                    mapContext.getBgColor().getBlue(), 0);
            graphic.setBackground(mapContext.getBgColor());
            graphic.setColor(c);
            graphic.fillRect(0, 0, width, height);

            type = AlphaComposite.SRC_OVER;
            graphic.setComposite(AlphaComposite.getInstance(type));
        }

        Rectangle paintArea = new Rectangle(width, height);

        renderer = new StreamingRenderer();
        renderer.setContext(mapContext);
        // TODO: expose the generalization distance as a param
        // ((StreamingRenderer) renderer).setGeneralizationDistance(0);

        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        renderer.setJava2DHints(hints);

        // we already do everything that the optimized data loading does...
        // if we set it to true then it does it all twice...
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true));
        rendererParams.put("renderingBuffer", new Integer(mapContext.getBuffer()));
        // we need the renderer to draw everything on the batik provided graphics object
        rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE);
        if (!DefaultWebMapService.isLineWidthOptimizationEnabled()) {
            rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, false);
        }
        renderer.setRendererHints(rendererParams);

        Envelope dataArea = mapContext.getAreaOfInterest();
        AffineTransform at = RendererUtilities.worldToScreenTransform(dataArea, paintArea);

        if (this.abortRequested) {
            graphic.dispose();
            // step 5: we close the document
            document.close();

            return;
        }

        // enforce no more than x rendering errors
        int maxErrors = wms.getMaxRenderingErrors();
        MaxErrorEnforcer errorChecker = new MaxErrorEnforcer(renderer, maxErrors);

        // Add a render listener that ignores well known rendering exceptions and reports back non
        // ignorable ones
        final RenderExceptionStrategy nonIgnorableExceptionListener;
        nonIgnorableExceptionListener = new RenderExceptionStrategy(renderer);
        renderer.addRenderListener(nonIgnorableExceptionListener);

        // enforce max memory usage
        int maxMemory = wms.getMaxRequestMemory() * KB;
        PDFMaxSizeEnforcer memoryChecker = new PDFMaxSizeEnforcer(renderer, graphic, maxMemory);

        // render the map
        renderer.paint(graphic, paintArea, at);

        // render the watermark
        MapDecorationLayout.Block watermark = DefaultRasterMapProducer
                .getWatermark(this.mapContext.getRequest().getWMS().getServiceInfo());

        if (watermark != null) {
            MapDecorationLayout layout = new MapDecorationLayout();
            layout.paint(graphic, paintArea, this.mapContext);
        }

        //check if a non ignorable error occurred
        if (nonIgnorableExceptionListener.exceptionOccurred()) {
            Exception renderError = nonIgnorableExceptionListener.getException();
            throw new WmsException("Rendering process failed", "internalError", renderError);
        }

        // check if too many errors occurred
        if (errorChecker.exceedsMaxErrors()) {
            throw new WmsException("More than " + maxErrors + " rendering errors occurred, bailing out",
                    "internalError", errorChecker.getLastException());
        }

        // check we did not use too much memory
        if (memoryChecker.exceedsMaxSize()) {
            long kbMax = maxMemory / KB;
            throw new WmsException(
                    "Rendering request used more memory than the maximum allowed:" + kbMax + "KB");
        }

        graphic.dispose();
        cb.addTemplate(tp, 0, 0);

        // step 5: we close the document
        document.close();
        writer.flush();
        writer.close();
    } catch (DocumentException t) {
        throw new WmsException("Error setting up the PDF", "internalError", t);
    }
}

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

License:Open Source License

/**
 * the form txt file has lines in the form:
 *
 * For Checkboxes:/*  w  w  w  .j av a  2s. c om*/
 * 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;
}

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());
    }//www.  ja v  a 2s.c o  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:pentaho.kettle.step.plugs.pdfout.PDFOutputGenerate.java

License:Apache License

public void generatePDF(String OutputFileName) throws IOException {

    if (Const.isWindows()) {
        if (OutputFileName.startsWith("file:///"))
            OutputFileName = OutputFileName.substring(8);
        OutputFileName = OutputFileName.replace("\\", "\\\\");
    }//  w w w . jav a2s  . com

    Document document = new Document();

    PdfWriter writer;
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(OutputFileName));

        document.open();

        document.add(new Paragraph("Hello Rishu Here !!"));

        /*
         * Setting up File Attributes - Document Description
         */
        document.addAuthor("Rishu Shrivastava");
        document.addCreationDate();
        document.addCreator("Rishu");
        document.addTitle("Set Attribute Example");
        document.addSubject("An example to show how attributes can be added to pdf files.");

        document.close();
        writer.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:permit.InvoicePdf.java

License:Open Source License

void writePages(HttpServletResponse res, Invoice invoice) {
    ////from   w w  w .  ja v a2 s  . c  om
    // paper size legal (A4) 8.5 x 11
    // page 1-inch = 72 points
    //
    String fileName = "row_invoice_" + invoice.getInvoice_num() + ".pdf";
    Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
    Document document = new Document(pageSize, 36, 36, 18, 18);
    ServletOutputStream out = null;
    Font fnt = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL);
    Font fntb = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fnts = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL);
    Font fntbs = new Font(Font.TIMES_ROMAN, 8, Font.BOLD);
    String spacer = "   ";
    PdfPTable header = getHeader();
    Company company = invoice.getCompany();
    Contact contact = null;
    if (invoice.hasContact()) {
        contact = invoice.getContact();
    }
    List<Page> pages = invoice.getPages();

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        String str = "";
        document.open();
        document.add(header);
        //
        // title
        float[] width = { 100f }; // one cell
        PdfPTable table = new PdfPTable(width);
        table.setWidthPercentage(100.0f);
        PdfPCell cell = new PdfPCell(new Phrase("INVOICE", fntb));
        //         
        cell.setBorder(Rectangle.BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        document.add(table);
        //
        // we need these later
        Paragraph pp = new Paragraph();
        Chunk ch = new Chunk(" ", fntb);
        Phrase phrase = new Phrase();
        //
        float[] widths = { 35f, 30f, 35f }; // percentages
        table = new PdfPTable(widths);
        table.setWidthPercentage(100.0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        // first row
        float[] widthOne = { 100f };
        PdfPTable leftTable = new PdfPTable(widthOne);
        leftTable.setWidthPercentage(35.0f);
        leftTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        if (company != null) {
            ch = new Chunk("Company\n", fntb);
            phrase = new Phrase();
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            phrase = new Phrase();
            ch = new Chunk(company.getName() + "\n", fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
        }
        if (contact != null) {
            phrase = new Phrase();
            ch = new Chunk(contact.getFullName(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            phrase = new Phrase();
            ch = new Chunk(contact.getAddress(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            ch = new Chunk(contact.getCityStateZip(), fnt);
            phrase = new Phrase();
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
        }
        table.addCell(leftTable);
        //
        // middle cell
        //
        cell = new PdfPCell(new Phrase(spacer, fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        float[] widths2 = { 50f, 50f }; // percentages
        PdfPTable rightTable = new PdfPTable(widths2);
        rightTable.setWidthPercentage(35.0f);
        rightTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        ch = new Chunk("Invoice No.", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(invoice.getInvoice_num(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Status", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(invoice.getStatus(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Invoice Date", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(invoice.getDate(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("From ", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        ch = new Chunk(invoice.getStart_date(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("To ", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        ch = new Chunk(invoice.getEnd_date(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        table.addCell(rightTable);
        //
        //
        document.add(table);
        //
        phrase = new Phrase(new Chunk(spacer, fnt));
        document.add(phrase);
        //
        int jj = 0;
        if (pages != null) {
            for (Page page : pages) {
                jj++;
                // float[] widthOne = {100f};
                PdfPTable borderTable = new PdfPTable(widthOne);
                borderTable.setWidthPercentage(100.0f);
                borderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                float[] widthTwo = { 50f, 50f };
                PdfPTable titleTable = new PdfPTable(widthTwo);
                titleTable.setWidthPercentage(75.0f);
                titleTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                phrase = new Phrase("Invoice No. ", fntb);
                ch = new Chunk(invoice.getInvoice_num(), fnt);
                phrase.add(ch);
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
                cell.setBorder(Rectangle.NO_BORDER);
                titleTable.addCell(cell);
                //
                phrase = new Phrase(page.getPage_num(), fnt);
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                cell.setBorder(Rectangle.NO_BORDER);
                titleTable.addCell(cell);
                //
                borderTable.addCell(titleTable);
                float[] width4 = { 25f, 40f, 25f, 10f };
                PdfPTable contTable = new PdfPTable(width4);
                cell = new PdfPCell(new Phrase("Excavation Permit Number", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Project", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Date Issued", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Permit Fee", fntb));
                contTable.addCell(cell);
                List<Permit> permits = page.getPermits();
                if (permits != null) {
                    for (Permit permit : permits) {
                        cell = new PdfPCell(new Phrase(permit.getPermit_num(), fnt));
                        contTable.addCell(cell);
                        phrase = new Phrase(permit.getProject() + "\n", fnt);
                        List<Excavation> cuts = permit.getExcavations();
                        if (cuts != null) {
                            for (Excavation one : cuts) {
                                ch = new Chunk(one.getAddress() + " (" + one.getCut_type() + ")", fnt);
                                phrase.add(ch);
                            }
                        }
                        cell = new PdfPCell(phrase);
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase(permit.getDate(), fnt));
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase("$" + permit.getFee(), fnt));
                        cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase(spacer, fnt));
                        //
                        // space line
                        cell.setColspan(4);
                        contTable.addCell(cell);
                    }
                }
                if (page.getNeededLines() > 0) { // first page 
                    for (int j = 0; j < page.getNeededLines(); j++) {
                        cell = new PdfPCell(new Phrase(spacer, fnt));
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                    }
                }
                if (jj == pages.size()) {
                    cell = new PdfPCell(new Phrase("Total Invoice Amount\n" + invoice.getTotal(), fntb));
                    cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                    cell.setColspan(4);
                    contTable.addCell(cell);
                }
                borderTable.addCell(contTable);
                cell = new PdfPCell(new Phrase(
                        "Payment due upon receipt. Please Make check payable to 'City of Bloomington'. Thank You.",
                        fnt));

                cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
                cell.setBorder(Rectangle.NO_BORDER);
                borderTable.addCell(cell);
                borderTable.addCell(titleTable); // invoice and date
                document.add(borderTable);
                if (jj < pages.size()) {
                    document.newPage();
                }
            }
        }
        //
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        //
        // if you want for users to download, uncomment the following line
        //
        // res.setHeader("Content-Disposition","attachment; filename="+fileName);         
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        logger.error(ex);
    }

}

From source file:permit.PermitPdf.java

License:Open Source License

void writePage(HttpServletResponse res, Permit permit) {
    ///*from  w  w w.  j ava  2 s.  c  o m*/
    // paper size legal (A4) 8.5 x 11
    // page 1-inch = 72 points
    //
    String fileName = "row_permit_" + permit.getId() + ".pdf";
    Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
    Document document = new Document(pageSize, 36, 36, 18, 18);
    ServletOutputStream out = null;
    Font fnt = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL);
    Font fntb = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fnts = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL);
    Font fntbs = new Font(Font.TIMES_ROMAN, 8, Font.BOLD);
    String spacer = "   ";
    PdfPTable header = getHeader();
    Bond bond = permit.getBond();
    Invoice invoice = permit.getInvoice();
    if (bond == null)
        bond = new Bond();
    if (invoice == null)
        invoice = new Invoice();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        String str = "";
        document.open();
        document.add(header);
        //
        // title
        float[] width = { 100f }; // one cell
        PdfPTable table = new PdfPTable(width);
        table.setWidthPercentage(100.0f);
        PdfPCell cell = new PdfPCell(new Phrase("Right Of Way Excavation Permit", fntb));
        //         
        cell.setBorder(Rectangle.BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        document.add(table);
        //
        // we need these later
        Paragraph pp = new Paragraph();
        Chunk ch = new Chunk(" ", fntb);
        Phrase phrase = new Phrase();
        //
        float[] widths = { 14f, 20f, 17f, 18f, 13f, 20f }; // percentages
        table = new PdfPTable(widths);
        table.setWidthPercentage(100.0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        // first row
        cell = new PdfPCell(new Phrase("Company", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getCompany().getName(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Status", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getStatus(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Permit", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getPermit_num(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        // 2nd row
        //
        cell = new PdfPCell(new Phrase("Responsible", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getContact().getFullName(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Inspector", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getReviewer().getFullName(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Date Issued", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getDate(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        // 3rd row
        cell = new PdfPCell(new Phrase("Project", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getProject(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Permit Fee", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("$" + permit.getFee(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Start Date", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getStart_date(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        // 4th row
        cell = new PdfPCell(new Phrase("Bond Amount", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("$" + bond.getAmount(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Expiration Date", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(bond.getExpire_date(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Invoice", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(invoice.getStatus(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        document.add(table);
        //
        phrase = new Phrase(new Chunk(spacer, fnt));
        document.add(phrase);
        //
        float[] widths2 = { 25f, 15f, 15f, 25f, 10f, 10f };
        table = new PdfPTable(widths2);
        table.setWidthPercentage(100.0f);
        cell = new PdfPCell(new Phrase("Address", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Cut Type", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Utility", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Description", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Width", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Length", fntb));
        table.addCell(cell);
        List<Excavation> list = permit.getExcavations();
        if (list != null && list.size() > 0) {
            for (Excavation one : list) {
                cell = new PdfPCell(new Phrase(one.getAddress().getAddress(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getCut_type(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getUtility_type().getName(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getCut_description(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getWidth(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getLength(), fnt));
                table.addCell(cell);
            }
        }
        document.add(table);
        //
        pp = new Paragraph();
        pp.setIndentationLeft(12);
        pp.setAlignment(Element.ALIGN_LEFT);
        pp.setLeading(0f, 1f);
        ch = new Chunk("\nSpecial Provisions\n", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        ch = new Chunk(permit.getNotes() + "\n", fnt);
        phrase.add(ch);
        pp.add(phrase);
        document.add(pp);
        //
        pp = new Paragraph();
        pp.setIndentationLeft(12);
        pp.setAlignment(Element.ALIGN_LEFT);
        ch = new Chunk("Standards Conditions of Approval\n", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        pp.add(phrase);
        document.add(pp);
        //
        pp = new Paragraph();
        pp.setIndentationLeft(12);
        pp.setAlignment(Element.ALIGN_LEFT);
        pp.setLeading(0f, 1f);
        ch = new Chunk("1 - " + conditions[0] + "\n", fntbs);
        phrase = new Phrase();
        phrase.add(ch);
        pp.add(phrase);
        document.add(pp);
        //
        int jj = 1;
        for (int j = 1; j < conditions.length; j++) {
            jj = j + 1;
            pp = new Paragraph();
            pp.setLeading(0f, 1f);
            pp.setIndentationLeft(12);
            pp.setAlignment(Element.ALIGN_LEFT);
            ch = new Chunk(jj + " - " + conditions[j] + "\n", fnts);
            phrase = new Phrase();
            phrase.add(ch);
            pp.add(phrase);
            document.add(pp);
        }

        pp = new Paragraph();
        pp.setIndentationLeft(20);
        pp.setAlignment(Element.ALIGN_RIGHT);
        ch = new Chunk("\n\n___________________\n", fnt);
        phrase = new Phrase();
        phrase.add(ch);
        pp.add(phrase);
        ch = new Chunk(permit.getReviewer().getFullName(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        pp.add(phrase);
        document.add(pp);
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        logger.error(ex);
    }

}

From source file:permit.ReceiptPdf.java

License:Open Source License

void writePages(HttpServletResponse res, Receipt receipt) {
    ///*from   ww w  .  j a va  2 s  .c o  m*/
    // paper size legal (A4) 8.5 x 11
    // page 1-inch = 72 points
    //
    Invoice invoice = receipt.getInvoice();
    String fileName = "row_receipt_" + receipt.getId() + ".pdf";
    Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
    Document document = new Document(pageSize, 36, 36, 18, 18);
    ServletOutputStream out = null;
    Font fnt = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL);
    Font fntb = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fnts = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL);
    Font fntbs = new Font(Font.TIMES_ROMAN, 8, Font.BOLD);
    String spacer = "   ";
    PdfPTable header = getHeader();
    Company company = invoice.getCompany();
    Contact contact = null;
    if (invoice.hasContact()) {
        contact = invoice.getContact();
    }
    List<Page> pages = invoice.getPages();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        String str = "";
        document.open();
        document.add(header);
        //
        // title
        float[] width = { 100f }; // one cell
        PdfPTable table = new PdfPTable(width);
        table.setWidthPercentage(100.0f);
        PdfPCell cell = new PdfPCell(new Phrase("RECEIPT", fntb));
        //         
        cell.setBorder(Rectangle.BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        document.add(table);
        //
        // we need these later
        Paragraph pp = new Paragraph();
        Chunk ch = new Chunk(" ", fntb);
        Phrase phrase = new Phrase();
        //
        float[] widths = { 35f, 30f, 35f }; // percentages
        table = new PdfPTable(widths);
        table.setWidthPercentage(100.0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        // first row
        float[] widthOne = { 100f };
        PdfPTable leftTable = new PdfPTable(widthOne);
        leftTable.setWidthPercentage(35.0f);
        leftTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        if (company != null) {
            ch = new Chunk("Company\n", fntb);
            phrase = new Phrase();
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            phrase = new Phrase();
            ch = new Chunk(company.getName() + "\n", fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
        }
        if (contact != null) {
            phrase = new Phrase();
            ch = new Chunk(contact.getFullName(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            phrase = new Phrase();
            ch = new Chunk(contact.getAddress(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            ch = new Chunk(contact.getCityStateZip(), fnt);
            phrase = new Phrase();
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
        }
        table.addCell(leftTable);
        //
        // middle cell
        //
        cell = new PdfPCell(new Phrase(spacer, fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        float[] widths2 = { 50f, 50f }; // percentages
        PdfPTable rightTable = new PdfPTable(widths2);
        rightTable.setWidthPercentage(35.0f);
        rightTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        ch = new Chunk("Receipt No.", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(receipt.getId(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Invoice No.", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(invoice.getInvoice_num(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Receipt Date", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(receipt.getDate(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Amount Paid $", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("$" + receipt.getAmount_paid(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Payment Method ", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk(receipt.getPayment_type(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        table.addCell(rightTable);
        //
        document.add(table);
        //
        phrase = new Phrase(new Chunk(spacer, fnt));
        document.add(phrase);
        //
        int jj = 0;
        if (pages != null) {
            for (Page page : pages) {
                jj++;
                PdfPTable borderTable = new PdfPTable(widthOne);
                borderTable.setWidthPercentage(100.0f);
                borderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                float[] widthTwo = { 50f, 50f };
                PdfPTable titleTable = new PdfPTable(widthTwo);
                titleTable.setWidthPercentage(75.0f);
                titleTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                phrase = new Phrase("Receipt Number ", fntb);
                ch = new Chunk(receipt.getId(), fnt);
                phrase.add(ch);
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
                cell.setBorder(Rectangle.NO_BORDER);
                titleTable.addCell(cell);
                //
                phrase = new Phrase(page.getPage_num(), fnt);
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                cell.setBorder(Rectangle.NO_BORDER);
                titleTable.addCell(cell);
                //
                borderTable.addCell(titleTable);
                float[] width4 = { 25f, 40f, 25f, 10f };
                PdfPTable contTable = new PdfPTable(width4);
                cell = new PdfPCell(new Phrase("Excavation Permit Number", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Project", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Date Issued", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Permit Fee", fntb));
                contTable.addCell(cell);
                List<Permit> permits = page.getPermits();
                if (permits != null) {
                    for (Permit permit : permits) {
                        cell = new PdfPCell(new Phrase(permit.getPermit_num(), fnt));
                        contTable.addCell(cell);
                        phrase = new Phrase(permit.getProject() + "\n", fnt);
                        List<Excavation> cuts = permit.getExcavations();
                        if (cuts != null) {
                            for (Excavation one : cuts) {
                                ch = new Chunk(one.getAddress() + " (" + one.getCut_type() + ")", fnt);
                                phrase.add(ch);
                            }
                        }
                        cell = new PdfPCell(phrase);
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase(permit.getDate(), fnt));
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase("$" + permit.getFee(), fnt));
                        cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase(spacer, fnt));
                        //
                        // space line
                        //
                        cell.setColspan(4);
                        contTable.addCell(cell);
                    }
                }
                if (page.getNeededLines() > 0) { // first page 
                    for (int j = 0; j < page.getNeededLines(); j++) {
                        cell = new PdfPCell(new Phrase(spacer, fnt));
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                    }
                }
                if (jj == pages.size()) {
                    cell = new PdfPCell(new Phrase("Total Invoice Amount\n" + invoice.getTotal(), fntb));
                    cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                    cell.setColspan(4);
                    contTable.addCell(cell);
                }
                borderTable.addCell(contTable);
                cell = new PdfPCell(new Phrase("Thank You.", fnt));

                cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
                cell.setBorder(Rectangle.NO_BORDER);
                borderTable.addCell(cell);
                borderTable.addCell(titleTable); // receipt and date
                document.add(borderTable);
                if (jj < pages.size()) {
                    document.newPage();
                }
            }
        }
        //
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        // res.setHeader("Content-Disposition","attachment; filename="+fileName);         
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        logger.error(ex);
    }

}

From source file:radpharmadose.RadPharmaDoseMainWindow.java

private void btn_export_as_pdfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_export_as_pdfActionPerformed

    String pdf_filename = "MedicalRaport_" + ExamenID + ".pdf";
    Document document = new Document();
    try {//from  ww w  .  jav a2 s  .  c  o  m
        PdfWriter writer = PdfWriter.getInstance(document, new java.io.FileOutputStream(pdf_filename));
        document.open();
        document.add(new Paragraph(container.getText()));
        document.close();
        writer.close();
        javax.swing.JOptionPane.showMessageDialog(null, "The PDF file was successfuly created!");

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}