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

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

Introduction

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

Prototype

public void showTextAligned(int alignment, String text, float x, float y, float rotation) 

Source Link

Document

Shows text right, left or center aligned with rotation.

Usage

From source file:org.kuali.kfs.sys.PdfFormFillerUtil.java

License:Open Source License

/**
 * This Method creates a custom watermark on the File.
 *
 * @param templateStream/* ww  w  . j  a  v  a  2  s  . com*/
 * @param watermarkText
 * @return
 * @throws IOException
 * @throws DocumentException
 */
public static byte[] createWatermarkOnFile(byte[] templateStream, String watermarkText)
        throws IOException, DocumentException {
    // Create a PDF reader for the template
    PdfReader pdfReader = new PdfReader(templateStream);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    // Create a PDF writer
    PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
    int n = pdfReader.getNumberOfPages();
    int i = 1;
    PdfContentByte over;
    BaseFont bf;
    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
        PdfGState gstate = new PdfGState();
        gstate.setFillOpacity(0.5f);
        while (i <= n) {
            // Watermark under the existing page
            Rectangle pageSize = pdfReader.getPageSizeWithRotation(i);
            over = pdfStamper.getOverContent(i);
            over.beginText();
            over.setFontAndSize(bf, 200);
            over.setGState(gstate);
            over.setColorFill(Color.LIGHT_GRAY);
            over.showTextAligned(Element.ALIGN_CENTER, watermarkText, (pageSize.width() / 2),
                    (pageSize.height() / 2), 45);
            over.endText();
            i++;
        }
        pdfStamper.close();
    } catch (DocumentException ex) {
        throw new IOException("iText error creating watermark on PDF", ex);
    } catch (IOException ex) {
        throw new IOException("IO error creating watermark on PDF", ex);
    }
    return outputStream.toByteArray();
}

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

License:Educational Community License

/**
 * This method is for setting the properties of watermark Text.
 * /*w  ww.  j  av a2s.c om*/
 * @param pdfContentByte
 * @param pageWidth
 * @param pageHeight
 * @param watermarkBean
 */
private void decoratePdfWatermarkText(PdfContentByte pdfContentByte, int pageWidth, int pageHeight,
        WatermarkBean watermarkBean) {
    float x, y, x1, y1, angle;
    try {
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) {
            pdfContentByte.beginText();
            pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                    watermarkBean.getFont().getSize());
            Color fillColor = watermarkBean.getFont().getColor() == null
                    ? WatermarkConstants.DEFAULT_WATERMARK_COLOR
                    : watermarkBean.getFont().getColor();
            pdfContentByte.setColorFill(fillColor);
            int textWidth = (int) pdfContentByte.getEffectiveStringWidth(watermarkBean.getText(), false);
            int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight));
            int pivotPoint = (diagonal - textWidth) / 2;

            angle = (float) Math.atan((float) pageHeight / pageWidth);

            x = (float) (pivotPoint * pageWidth) / diagonal;
            y = (float) (pivotPoint * pageHeight) / diagonal;

            x1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.sin(angle));
            y1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.cos(angle));

            pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), x + x1, y - y1,
                    (float) Math.toDegrees(angle));
            pdfContentByte.endText();
        }

    } catch (Exception exception) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + exception.getMessage());
    }

}

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

License:Educational Community License

/**
 * Overrides the method in PdfPageEventHelper from itext to include our watermark text to indicate that
 * this is a Test document and include the environment, if the environment is not a production environment.
 *
 * @param writer   The PdfWriter for this document.
 * @param document The document.//from w ww. ja va  2 s  .  com
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onStartPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onStartPage(PdfWriter writer, Document document) {
    if (!KRADUtils.isProductionEnvironment()) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        String watermarkText = "Test document (" + environment + ")";
        cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2,
                document.getPageSize().height() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
    if (GlobalVariables.getUserSession() != null
            && GlobalVariables.getUserSession().retrieveObject("isPreview") != null) {
        GlobalVariables.getUserSession().removeObject("isPreview");
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        String watermarkText = "DRAFT";
        cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2,
                document.getPageSize().height() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
}

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) {
    /*// w  w w . j  a  v  a  2s .  c  om
     * 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  a  va2s .  c o 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).
 *//*w w w. j a  v a2  s  . c  o  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 .j  a v  a  2s . c om*/

    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.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 {/*from w  w w  .j  av a2  s .c om*/
        // 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  ww w  .j  av a 2s  . c  om

    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
 * //  ww  w. ja  v  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();
}