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

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

Introduction

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

Prototype

public void setColorFill(Color color) 

Source Link

Document

Sets the fill color.

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// www . j  a va 2 s.c om
 * @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.
 * //ww w .  ja  va 2s .co m
 * @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.mapfish.print.map.MapChunkDrawer.java

License:Open Source License

public void renderImpl(Rectangle rectangle, PdfContentByte dc) {
    final PJsonObject parent = context.getGlobalParams();
    PJsonArray layers = parent.getJSONArray("layers");
    String srs = parent.getString("srs");

    if (!context.getConfig().isScalePresent(transformer.getScale())) {
        throw new InvalidJsonValueException(params, "scale", transformer.getScale());
    }/*from   ww w  .  j  a  v a  2s .  com*/

    Transformer mainTransformer = null;
    if (!Double.isNaN(overviewMap)) {
        //manage the overview map
        mainTransformer = context.getLayout().getMainPage().getMap().createTransformer(context, params);
        transformer.zoom(mainTransformer, (float) (1.0 / overviewMap));
        transformer.setRotation(0); //overview always north up!
        context.setStyleFactor((float) (transformer.getPaperW() / mainTransformer.getPaperW() / overviewMap));
        layers = parent.optJSONArray("overviewLayers", layers);
    }

    transformer.setMapPos(rectangle.getLeft(), rectangle.getBottom());
    if (rectangle.getWidth() < transformer.getPaperW() - 0.2) {
        throw new RuntimeException("The map width on the paper is wrong");
    }
    if (rectangle.getHeight() < transformer.getPaperH() - 0.2) {
        throw new RuntimeException("The map height on the paper is wrong (" + rectangle.getHeight() + "!="
                + transformer.getPaperH() + ")");
    }

    //create the readers/renderers
    List<MapReader> readers = new ArrayList<MapReader>(layers.size());
    for (int i = 0; i < layers.size(); ++i) {
        PJsonObject layer = layers.getJSONObject(i);
        if (mainTransformer == null || layer.optBool("overview", true)) {
            final String type = layer.getString("type");
            MapReader.create(readers, type, context, layer);
        }
    }

    //check if we cannot merge a few queries
    for (int i = 1; i < readers.size();) {
        MapReader reader1 = readers.get(i - 1);
        MapReader reader2 = readers.get(i);
        if (reader1.testMerge(reader2)) {
            readers.remove(i);
        } else {
            ++i;
        }

    }

    //draw some background
    if (backgroundColor != null) {
        dc.saveState();
        try {
            dc.setColorFill(backgroundColor);
            dc.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(),
                    rectangle.getHeight());
            dc.fill();
        } finally {
            dc.restoreState();
        }
    }

    //Do the rendering.
    //
    //Since we need to load tiles in parallel from the
    //servers, what follows is not trivial. We don't write directly to the PDF's
    //DirectContent, we always go through the ParallelMapTileLoader that will
    //make sure that everything is added to the PDF in the correct order.
    //
    //All uses of the DirectContent (dc) or the PDFWriter is forbiden outside
    //of renderOnPdf methods and when they are used, one must take a lock on
    //context.getPdfLock(). That is done for you when renderOnPdf is called, but not done
    //in the readTile method. That's why PDFUtils.getImage needs to do it when
    //creating the template.
    //
    //If you don't follow those rules, you risk to have random inconsistency
    //in your PDF files and/or infinite loops in iText.
    ParallelMapTileLoader parallelMapTileLoader = new ParallelMapTileLoader(context, dc);
    dc.saveState();
    try {
        final PdfLayer mapLayer = new PdfLayer(name, context.getWriter());
        transformer.setClipping(dc);

        //START of the parallel world !!!!!!!!!!!!!!!!!!!!!!!!!!!

        for (int i = 0; i < readers.size(); i++) {
            final MapReader reader = readers.get(i);

            //mark the starting of a new PDF layer
            parallelMapTileLoader.addTileToLoad(new MapTileTask.RenderOnly() {
                public void renderOnPdf(PdfContentByte dc) throws DocumentException {
                    PdfLayer pdfLayer = new PdfLayer(reader.toString(), context.getWriter());
                    mapLayer.addChild(pdfLayer);
                    dc.beginLayer(pdfLayer);
                }
            });

            //render the layer
            reader.render(transformer, parallelMapTileLoader, srs, i == 0);

            //mark the end of the PDF layer
            parallelMapTileLoader.addTileToLoad(new MapTileTask.RenderOnly() {
                public void renderOnPdf(PdfContentByte dc) throws DocumentException {
                    dc.endLayer();
                }
            });
        }
    } finally {
        //wait for all the tiles to be loaded
        parallelMapTileLoader.waitForCompletion();

        //END of the parallel world !!!!!!!!!!!!!!!!!!!!!!!!!!

        dc.restoreState();
    }

    if (mainTransformer != null) {
        //only for key maps: draw the real map extent
        drawMapExtent(dc, mainTransformer);
        context.setStyleFactor(1.0f);
    }
}

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) {
    /*/*  www  . j av a 2  s .  com*/
     * 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 .jav  a2 s  .c  om*/
     * 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.map.renderers.vector.PolygonRenderer.java

License:Open Source License

protected static void applyStyle(RenderingContext context, PdfContentByte dc, PJsonObject style,
        PdfGState state) {//  www.  ja  v  a 2s.com
    if (style == null)
        return;
    LineStringRenderer.applyStyle(context, dc, style, state);

    if (style.optString("fillColor") != null) {
        dc.setColorFill(ColorWrapper.convertColor(style.getString("fillColor")));
    }
    if (style.optString("fillOpacity") != null) {
        state.setFillOpacity(style.getFloat("fillOpacity"));
    }
}

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

License:Open Source License

protected void drawBar(PdfContentByte dc) {
    float subIntervalWidth = intervalWidth / subIntervals;
    for (int i = 0; i < block.getIntervals() * subIntervals; ++i) {
        float pos = i * subIntervalWidth;
        final Color color = i % 2 == 0 ? block.getBarBgColorVal() : block.getColorVal();
        if (color != null) {
            dc.setColorFill(color);
            dc.rectangle(pos, 0, subIntervalWidth, barSize);
            dc.fill();/*  ww w .  j av a 2s  .com*/
        }
    }

    dc.rectangle(0, 0, intervalWidth * block.getIntervals(), barSize);
    dc.stroke();
}

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";
    }/*from   w w  w.j a 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:questions.markedcontent.ObjectData.java

public static void main(String[] args) {
    Document document = new Document(PageSize.A5.rotate());
    try {// w  w  w.j a  v  a  2s . c o m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        writer.setTagged();

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfStructureTreeRoot tree = writer.getStructureTreeRoot();
        PdfStructureElement se = new PdfStructureElement(tree, new PdfName("Figure"));
        PdfStructureElement element = new PdfStructureElement(se, new PdfName("Element"));
        PdfDictionary userproperties = new PdfDictionary();
        userproperties.put(PdfName.O, PdfName.USERPROPERTIES);
        userproperties.put(PdfName.S, new PdfName("Figure"));
        PdfArray properties = new PdfArray();
        PdfDictionary property1 = new PdfDictionary();
        property1.put(PdfName.N, new PdfString("Name1"));
        property1.put(PdfName.V, new PdfString("Value1"));
        properties.add(property1);
        PdfDictionary property2 = new PdfDictionary();
        property2.put(PdfName.N, new PdfString("Name2"));
        property2.put(PdfName.V, new PdfString("Value2"));
        properties.add(property2);
        PdfDictionary property3 = new PdfDictionary();
        property3.put(PdfName.N, new PdfString("Name3"));
        property3.put(PdfName.V, new PdfString("Value3"));
        properties.add(property3);
        userproperties.put(PdfName.P, properties);
        element.put(PdfName.A, userproperties);

        PdfLayer lay1 = new PdfLayer("My object", writer);

        cb.beginMarkedContentSequence(element);
        cb.beginLayer(lay1);
        cb.setColorFill(Color.BLUE);
        cb.rectangle(50, 50, 200, 200);
        cb.fill();
        cb.endLayer();
        cb.endMarkedContentSequence();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    document.close();

}

From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteerBadgePdfView.java

License:Open Source License

/**
 * Adds the Volunteer's name to the Badge.
 *
 * @param content to be added/*  w  ww  .  j  a v a 2 s. com*/
 * @param name concatenated String of forename and surname
 */
private static void addVolunteerName(PdfContentByte content, String name)
        throws DocumentException, IOException {
    content.beginText();
    content.moveText(183, 470);

    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1257, false);
    content.setFontAndSize(bf, 16);
    content.setColorFill(Color.BLACK);
    content.showText(name);
    content.endText();
}