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

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

Introduction

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

Prototype

public void endText() 

Source Link

Document

Ends the writing of text and makes the current font invalid.

Usage

From source file:org.kuali.ole.module.purap.pdf.PurapPdf.java

License:Educational Community License

/**
 * Overrides the method in PdfPageEventHelper from itext to write the headerTable, compose the footer and show the
 * footer./*from   ww w.  ja va 2  s  .c  om*/
 *
 * @param writer   The PdfWriter for this document.
 * @param document The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
    LOG.debug("onEndPage() started.");
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // write the headerTable
    headerTable.setTotalWidth(document.right() - document.left());
    headerTable.writeSelectedRows(0, -1, document.left(), document.getPageSize().height() - 10, cb);
    // compose the footer
    String text = "Page " + writer.getPageNumber() + " of ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    // show the footer
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
}

From source file:org.mapfish.print.map.renderers.vector.LabelRenderer.java

License:Open Source License

static void applyStyle(RenderingContext context, PdfContentByte dc, PJsonObject style, Geometry geometry,
        AffineTransform affineTransform) {
    /*/*from  ww w.  j  av  a2s.c o  m*/
     * See Feature/Vector.js for more information about labels
     */
    String label = style.optString("label");

    if (label != null && label.length() > 0) {
        /*
         * Valid values for horizontal alignment: "l"=left, "c"=center,
         * "r"=right. Valid values for vertical alignment: "t"=top,
         * "m"=middle, "b"=bottom.
         */
        String labelAlign = style.optString("labelAlign", "cm");
        float labelXOffset = style.optFloat("labelXOffset", (float) 0.0);
        float labelYOffset = style.optFloat("labelYOffset", (float) 0.0);
        String fontColor = style.optString("fontColor", "#000000");
        /* Supported itext fonts: COURIER, HELVETICA, TIMES_ROMAN */
        String fontFamily = style.optString("fontFamily", "HELVETICA");
        if (!"COURIER".equalsIgnoreCase(fontFamily) || !"HELVETICA".equalsIgnoreCase(fontFamily)
                || !"TIMES_ROMAN".equalsIgnoreCase(fontFamily)) {

            LOGGER.info("Font: '" + fontFamily + "' not supported, supported fonts are 'HELVETICA', "
                    + "'COURIER', 'TIMES_ROMAN', defaults to 'HELVETICA'");
            fontFamily = "HELVETICA";
        }
        String fontSize = style.optString("fontSize", "12");
        String fontWeight = style.optString("fontWeight", "normal");
        Coordinate center = geometry.getCentroid().getCoordinate();
        center = GeometriesRenderer.transformCoordinate(center, affineTransform);
        float f = context.getStyleFactor();
        BaseFont bf = PDFUtils.getBaseFont(fontFamily, fontSize, fontWeight);
        float fontHeight = (float) Double.parseDouble(fontSize.toLowerCase().replaceAll("px", "")) * f;
        dc.setFontAndSize(bf, fontHeight);
        dc.setColorFill(ColorWrapper.convertColor(fontColor));
        dc.beginText();
        dc.setTextMatrix((float) center.x + labelXOffset * f, (float) center.y + labelYOffset * f);
        dc.showTextAligned(PDFUtils.getHorizontalAlignment(labelAlign), label,
                (float) center.x + labelXOffset * f,
                (float) center.y + labelYOffset * f - PDFUtils.getVerticalOffset(labelAlign, fontHeight), 0);
        dc.endText();
    }
}

From source file:org.mapfish.print.map.renderers.vector.PointRenderer.java

License:Open Source License

protected void renderImpl(RenderingContext context, PdfContentByte dc, PJsonObject style, Point geometry) {
    PdfGState state = new PdfGState();
    final Coordinate coordinate = geometry.getCoordinate();
    float pointRadius = style.optFloat("pointRadius", 4.0f);
    final float f = context.getStyleFactor();

    String graphicName = style.optString("graphicName");
    float width = style.optFloat("graphicWidth", pointRadius * 2.0f);
    float height = style.optFloat("graphicHeight", pointRadius * 2.0f);
    float offsetX = style.optFloat("graphicXOffset", -width / 2.0f);
    float offsetY = style.optFloat("graphicYOffset", -height / 2.0f);
    // See Feature/Vector.js for more information about labels
    String label = style.optString("label");
    String labelAlign = style.optString("labelAlign", "lb");
    /*/*from   w w  w  . j ava 2s  .  co m*/
     * Valid values for horizontal alignment: "l"=left, "c"=center, "r"=right. 
     * Valid values for vertical alignment: "t"=top, "m"=middle, "b"=bottom.
     */
    float labelXOffset = style.optFloat("labelXOffset", (float) 0.0);
    float labelYOffset = style.optFloat("labelYOffset", (float) 0.0);
    String fontColor = style.optString("fontColor", "#000000");
    /* Supported itext fonts: COURIER, HELVETICA, TIMES_ROMAN */
    String fontFamily = style.optString("fontFamily", "HELVETICA");
    String fontSize = style.optString("fontSize", "12");
    String fontWeight = style.optString("fontWeight", "normal");

    if (style.optString("externalGraphic") != null) {
        float opacity = style.optFloat("graphicOpacity", style.optFloat("fillOpacity", 1.0f));
        state.setFillOpacity(opacity);
        state.setStrokeOpacity(opacity);
        dc.setGState(state);
        try {
            Image image = PDFUtils.createImage(context, width * f, height * f,
                    new URI(style.getString("externalGraphic")), 0.0f);
            image.setAbsolutePosition((float) coordinate.x + offsetX * f, (float) coordinate.y + offsetY * f);
            dc.addImage(image);
        } catch (BadElementException e) {
            context.addError(e);
        } catch (URISyntaxException e) {
            context.addError(e);
        } catch (DocumentException e) {
            context.addError(e);
        }

    } else if (graphicName != null && !graphicName.equalsIgnoreCase("circle")) {
        PolygonRenderer.applyStyle(context, dc, style, state);
        float[] symbol = SYMBOLS.get(graphicName);
        if (symbol == null) {
            throw new InvalidValueException("graphicName", graphicName);
        }
        dc.setGState(state);
        dc.moveTo((float) coordinate.x + symbol[0] * width * f + offsetX * f,
                (float) coordinate.y + symbol[1] * height * f + offsetY * f);
        for (int i = 2; i < symbol.length - 2; i += 2) {
            dc.lineTo((float) coordinate.x + symbol[i] * width * f + offsetX * f,
                    (float) coordinate.y + symbol[i + 1] * height * f + offsetY * f);

        }
        dc.closePath();
        dc.fillStroke();

    } else if (label != null && label.length() > 0) {
        BaseFont bf = PDFUtils.getBaseFont(fontFamily, fontSize, fontWeight);
        float fontHeight = (float) Double.parseDouble(fontSize.toLowerCase().replaceAll("px", "")) * f;
        dc.setFontAndSize(bf, fontHeight);
        dc.setColorFill(ColorWrapper.convertColor(fontColor));
        state.setFillOpacity((float) 1.0);
        dc.setGState(state);
        dc.beginText();
        dc.setTextMatrix((float) coordinate.x + labelXOffset * f, (float) coordinate.y + labelYOffset * f);
        dc.setGState(state);
        dc.showTextAligned(PDFUtils.getHorizontalAlignment(labelAlign), label,
                (float) coordinate.x + labelXOffset * f,
                (float) coordinate.y + labelYOffset * f - PDFUtils.getVerticalOffset(labelAlign, fontHeight),
                0);
        dc.endText();
    } else {
        PolygonRenderer.applyStyle(context, dc, style, state);
        dc.setGState(state);

        dc.circle((float) coordinate.x, (float) coordinate.y, pointRadius * f);
        dc.fillStroke();
    }
}

From source file:org.mapfish.print.scalebar.ScalebarDrawer.java

License:Open Source License

/**
 * Draws the labels. The transformation is setup in a manner where the
 * position of the labels is at (label.paperOffset,0).
 *///from  w w  w  . ja v  a2s.  co m
private void drawLabels(PdfContentByte dc) {
    float prevPos = getTotalWidth();

    for (int i = labels.size() - 1; i >= 0; --i) {
        Label label = labels.get(i);
        final float offsetH;
        final float offsetV;
        if (block.getTextDirection().getAngle() == block.getBarDirection().getAngle()) {
            //same direction
            offsetH = -label.width / 2;
            offsetV = -maxLabelHeight;

        } else if (block.getTextDirection().getAngle() == -block.getBarDirection().getAngle()) {
            //opposite direction
            offsetH = label.width / 2;
            offsetV = 0;
        } else if (block.getTextDirection().getAngle() - block.getBarDirection().getAngle() < 0) {
            offsetH = label.width / 2;
            offsetV = -label.height;
        } else {
            offsetH = -label.width / 2;
            offsetV = 0;
        }

        if (label.paperOffset + Math.abs(offsetH) <= prevPos - 1) {
            dc.beginText();
            dc.showTextAligned(PdfContentByte.ALIGN_LEFT, label.label, label.paperOffset + offsetH, offsetV,
                    (float) (block.getBarDirection().getAngle() - block.getTextDirection().getAngle()));
            dc.endText();
            prevPos = label.paperOffset - Math.abs(offsetH);
        } else {
            //the label would be written over the previous one => ignore it
            label.label = null;
        }
    }
}

From source file:org.meveo.admin.action.billing.BillingAccountBean.java

License:Open Source License

public void generatePDF(long invoiceId) {
    Invoice invoice = invoiceService.findById(invoiceId);
    byte[] invoicePdf = invoice.getPdf();
    FacesContext context = FacesContext.getCurrentInstance();
    String invoiceFilename = null;
    BillingRun billingRun = invoice.getBillingRun();
    invoiceFilename = invoice.getInvoiceNumber() + ".pdf";
    if (billingRun != null && billingRun.getStatus() != BillingRunStatusEnum.VALIDATED) {
        invoiceFilename = "unvalidated-invoice.pdf";
    }/*w ww.ja v a  2 s . com*/

    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/pdf"); // fill in
    response.setHeader("Content-disposition", "attachment; filename=" + invoiceFilename);

    try {
        OutputStream os = response.getOutputStream();
        Document document = new Document(PageSize.A4);
        if (billingRun != null && invoice.getBillingRun().getStatus() != BillingRunStatusEnum.VALIDATED) {
            // Add watemark image
            PdfReader reader = new PdfReader(invoicePdf);
            int n = reader.getNumberOfPages();
            PdfStamper stamp = new PdfStamper(reader, os);
            PdfContentByte over = null;
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            int i = 1;
            while (i <= n) {
                over = stamp.getOverContent(i);
                over.setGState(gs);
                over.beginText();
                System.out.println("top=" + document.top() + ",bottom=" + document.bottom());
                over.setTextMatrix(document.top(), document.bottom());
                over.setFontAndSize(bf, 150);
                over.setColorFill(Color.GRAY);
                over.showTextAligned(Element.ALIGN_CENTER, "TEST", document.getPageSize().getWidth() / 2,
                        document.getPageSize().getHeight() / 2, 45);
                over.endText();
                i++;
            }

            stamp.close();
        } else {
            os.write(invoicePdf); // fill in PDF with bytes
        }

        // contentType
        os.flush();
        os.close();
        context.responseComplete();
    } catch (IOException e) {
        log.error("failed to generate PDF ", e);
    } catch (DocumentException e) {
        log.error("error in generation PDF ", e);
    }
}

From source file:org.opentestsystem.delivery.testreg.rest.view.PdfReportPageEventHelper.java

License:Open Source License

@Override
public void onEndPage(final PdfWriter writer, final Document document) {
    PdfContentByte cb = writer.getDirectContent();
    if (document.getPageNumber() == 1) {
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(""),
                (document.right() - document.left()) / 2 + document.leftMargin(), document.top() - 5, 0f);
    }//  w  w  w .j a v  a2  s . c  om
    ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(""), document.left(), document.bottom() - 15,
            0f);

    int pageN = writer.getPageNumber();
    String text = "Page " + pageN + " of ";
    cb.beginText();
    cb.setFontAndSize(helv, 11);
    cb.setTextMatrix(document.right() - document.rightMargin() - 10, document.bottom() - 15);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(template, document.right(), document.bottom() - 15);

}

From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java

License:Open Source License

protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config,
        OutputStream outputStream) {
    final org.dom4j.Document configDocument = readCacheInputAsDOM4J(pipelineContext, "model");// TODO: after all, should we use "config"?
    final org.dom4j.Document instanceDocument = readInputAsDOM4J(pipelineContext, input);

    final Configuration configuration = XPathCache.getGlobalConfiguration();
    final DocumentInfo configDocumentInfo = new DocumentWrapper(configDocument, null, configuration);
    final DocumentInfo instanceDocumentInfo = new DocumentWrapper(instanceDocument, null, configuration);

    try {/*ww w.  j av a  2 s.  co  m*/
        // Get reader
        final String templateHref = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@href", null,
                null, functionLibrary, null, null, null);//TODO: LocationData

        // Create PDF reader
        final PdfReader reader;
        {
            final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(templateHref);
            if (inputName != null) {
                // Read the input
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                readInputAsSAX(pipelineContext, inputName,
                        new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false));

                // Create the reader
                reader = new PdfReader(os.toByteArray());
            } else {
                // Read and create the reader
                reader = new PdfReader(URLFactory.createURL(templateHref));
            }
        }

        // Get total number of pages
        final int pageCount = reader.getNumberOfPages();

        // Get size of first page
        final Rectangle pageSize = reader.getPageSize(1);
        final float width = pageSize.getWidth();
        final float height = pageSize.getHeight();

        final String showGrid = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@show-grid", null,
                null, functionLibrary, null, null, null);//TODO: LocationData

        final PdfStamper stamper = new PdfStamper(reader, outputStream);
        stamper.setFormFlattening(true);

        for (int currentPage = 1; currentPage <= pageCount; currentPage++) {
            final PdfContentByte contentByte = stamper.getOverContent(currentPage);
            // Handle root group
            final GroupContext initialGroupContext = new GroupContext(contentByte, stamper.getAcroFields(),
                    height, currentPage, Collections.singletonList((Item) instanceDocumentInfo), 1, 0, 0,
                    "Courier", 14, 15.9f);
            handleGroup(pipelineContext, initialGroupContext,
                    Dom4jUtils.elements(configDocument.getRootElement()), functionLibrary, reader);

            // Handle preview grid (NOTE: This can be heavy in memory.)
            if ("true".equalsIgnoreCase(showGrid)) {
                final float topPosition = 10f;

                final BaseFont baseFont2 = BaseFont.createFont("Courier", BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                contentByte.beginText();
                {
                    // 20-pixel lines and side legends

                    contentByte.setFontAndSize(baseFont2, (float) 7);

                    for (int w = 0; w <= width; w += 20) {
                        for (int h = 0; h <= height; h += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                    for (int h = 0; h <= height; h += 20) {
                        for (int w = 0; w <= width; w += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }

                    for (int w = 0; w <= width; w += 20) {
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w,
                                height - topPosition, 0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, topPosition,
                                0);
                    }
                    for (int h = 0; h <= height; h += 20) {
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, (float) 5, height - h,
                                0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, width - (float) 5,
                                height - h, 0);
                    }

                    // 10-pixel lines

                    contentByte.setFontAndSize(baseFont2, (float) 3);

                    for (int w = 10; w <= width; w += 10) {
                        for (int h = 0; h <= height; h += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                    for (int h = 10; h <= height; h += 10) {
                        for (int w = 0; w <= width; w += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                }
                contentByte.endText();
            }
        }

        // Close the document
        //            document.close();
        stamper.close();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.oscarehr.casemgmt.service.PageNumberStamper.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();/*from   w  ww .j av  a  2s  .co m*/

    String text = "Page " + writer.getPageNumber() + " of ";

    // height where text starts 
    float textBase = document.bottom() - getBaseOffset();
    float textSize = getFont().getWidthPoint(text, getFontSize());
    float width = document.getPageSize().getWidth();
    float center = width / 2.0f;

    cb.beginText();
    cb.setFontAndSize(getFont(), getFontSize());

    cb.setTextMatrix(document.left(), textBase);
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text, center, textBase, 0);
    cb.endText();
    cb.addTemplate(total, center + (textSize / 2.0f), textBase);

    cb.restoreState();
}

From source file:org.oscarehr.casemgmt.service.PromoTextStamper.java

License:Open Source License

/**
 * Adds promo text, date and current page number to each page
 * //from  w w  w .j  av a 2  s . co  m
 * @param writer
 * @param document
 */
public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    float textBase = document.bottom() - getBaseOffset();
    float width = document.getPageSize().getWidth();
    float center = width / 2.0f;

    cb.beginText();
    cb.setFontAndSize(getFont(), getFontSize());

    cb.setTextMatrix(document.left(), textBase);
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text, center, textBase, 0);
    cb.endText();
    cb.restoreState();
}

From source file:org.oscarehr.common.printing.HtmlToPdfServlet.java

License:Open Source License

private static void printText(PdfContentByte over, String text, float x, float y) {
    over.beginText();// w  ww .j a  v a 2s.c o m
    over.showTextAligned(PdfContentByte.ALIGN_CENTER, text, x, y, 0);
    over.endText();
}