Example usage for com.lowagie.text.pdf PdfGState setFillOpacity

List of usage examples for com.lowagie.text.pdf PdfGState setFillOpacity

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfGState setFillOpacity.

Prototype

public void setFillOpacity(float n) 

Source Link

Document

Sets the current stroking alpha constant, specifying the constant shape or constant opacity value to be used for nonstroking operations in the transparent imaging model.

Usage

From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * This method is for setting the properties of watermark Text.
 *///from   w ww.  j av a 2  s .c o m
private void decoratePdfWatermarkText(PdfContentByte pdfContentByte, Rectangle rectangle,
        WatermarkBean watermarkBean) {
    float x, y, x1, y1, angle;
    final float OPACITY = 0.3f;
    PdfGState pdfGState = new PdfGState();
    pdfGState.setFillOpacity(OPACITY);
    int pageWidth = (int) rectangle.getWidth();
    int pageHeight = (int) rectangle.getHeight();
    try {
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) {
            pdfContentByte.beginText();
            pdfContentByte.setGState(pdfGState);
            Color fillColor = watermarkBean.getFont().getColor() == null
                    ? WatermarkConstants.DEFAULT_WATERMARK_COLOR
                    : watermarkBean.getFont().getColor();
            pdfContentByte.setColorFill(fillColor);

            if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_FOOTER)) {

                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getPositionFont().getSize());
                if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(),
                            (rectangle.getLeft(rectangle.getBorderWidthLeft())
                                    + rectangle.getRight(rectangle.getBorderWidthRight())) / 2,
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(),
                            rectangle.getRight(rectangle.getBorderWidthRight()),
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(),
                            rectangle.getLeft(rectangle.getBorderWidthLeft()),
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                }
            } else if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_HEADER)) {
                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getPositionFont().getSize());
                if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(),
                            (rectangle.getLeft(rectangle.getBorderWidthLeft())
                                    + rectangle.getRight(rectangle.getBorderWidthRight())) / 2,
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(),
                            rectangle.getRight(rectangle.getBorderWidthRight()),
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(),
                            rectangle.getLeft(rectangle.getBorderWidthLeft()),
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                }
            } else {
                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getFont().getSize());
                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.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * This method is for setting the properties of watermark Image.
 * /*from w  w w. jav a 2 s .  c  o m*/
 * @param pdfContentByte
 * @param pageWidth
 * @param pageHeight
 * @param watermarkBean
 */
private void decoratePdfWatermarkImage(PdfContentByte pdfContentByte, int pageWidth, int pageHeight,
        WatermarkBean watermarkBean) {
    PdfGState pdfGState = new PdfGState();
    final float OPACITY = 0.3f;
    float absPosX;
    float absPosY;
    try {
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) {
            Image watermarkImage = Image.getInstance(watermarkBean.getFileImage());
            if (watermarkImage != null) {
                pdfGState.setFillOpacity(OPACITY);
                pdfContentByte.setGState(pdfGState);
                float height = watermarkImage.getPlainHeight();
                float width = watermarkImage.getPlainWidth();
                int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight));
                int pivotPoint = (diagonal - (int) width) / 2;
                float angle = (float) Math.atan((float) pageHeight / pageWidth);
                absPosX = (float) (pivotPoint * pageWidth) / diagonal;
                absPosY = (float) (pivotPoint * pageHeight) / diagonal;
                watermarkImage.setAbsolutePosition(absPosX, absPosY);
                if ((pageWidth / 2) < width) {
                    watermarkImage.scaleToFit(pageWidth / 2, pageHeight / 2);
                } else {
                    watermarkImage.scaleToFit(width, height);
                }
                pdfContentByte.addImage(watermarkImage);
            }

        }

    } catch (BadElementException badElementException) {

        LOG.error("WatermarkDecoratorImpl  Error found: " + badElementException.getMessage());
    } catch (DocumentException documentException) {

        LOG.error("WatermarkDecoratorImpl Error found: " + documentException.getMessage());
    }

}

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

License:Open Source License

/**
 * This Method creates a custom watermark on the File.
 *
 * @param templateStream//from w  w w  .  j av  a 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.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw engine.getExceptionUtil().createApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    // image//  www . j a v  a2s  .  com
    Image img = null;
    if (image != null) {
        // TODO lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext,image,false,false,true,null);
        // TODO img=Image.getInstance(ri.getBufferedImage(),null,false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = copyFrom instanceof String
                    ? engine.getResourceUtil().toResourceExisting(pageContext, (String) copyFrom)
                    : engine.getCastUtil().toResource(copyFrom);
            barr = PDFUtil.toBytes(res);
        } catch (PageException ee) {
            barr = engine.getCastUtil().toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!Util.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw engine.getExceptionUtil()
                    .createApplicationException("attribute [position] has an invalid value [" + position + "],"
                            + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!Util.isEmpty(strX))
            x = engine.getCastUtil().toIntValue(strX);
        if (!Util.isEmpty(strY))
            y = engine.getCastUtil().toIntValue(strY);

    }

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {

        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            // print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            // gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, 1, 1);//from   w w w .j a  v  a 2s . c o  m

    Image img = Image.getInstance(bi, null, false);
    img.setAbsolutePosition(1, 1);

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {
        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(0);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.mapfish.print.map.readers.ImageMapReader.java

License:Open Source License

public void render(final Transformer transformer, ParallelMapTileLoader parallelMapTileLoader, String srs,
        boolean first) {
    LOGGER.debug(baseUrl);/*  w w  w  .  j  a v a2s .  c  o m*/

    parallelMapTileLoader.addTileToLoad(new MapTileTask() {
        public Image image;

        public void readTile() throws DocumentException {
            image = PDFUtils.createImage(context, extentMaxX - extentMinX, extentMaxY - extentMinY, baseUrl, 0);
            image.setAbsolutePosition(extentMinX, extentMinY);
        }

        public void renderOnPdf(PdfContentByte dc) throws DocumentException {
            //add the image using a geo->paper transformer
            final AffineTransform geoTransform = transformer.getGeoTransform(false);
            dc.transform(geoTransform);
            if (opacity < 1.0) {
                PdfGState gs = new PdfGState();
                gs.setFillOpacity(opacity);
                gs.setStrokeOpacity(opacity);
                dc.setGState(gs);
            }
            dc.addImage(image);
        }
    });
}

From source file:org.mapfish.print.map.renderers.BitmapMapRenderer.java

License:Open Source License

public void render(Transformer transformer, List<URI> uris, PdfContentByte dc, RenderingContext context,
        float opacity, int nbTilesHorizontal, float offsetX, float offsetY, long bitmapTileW, long bitmapTileH)
        throws IOException {
    dc.saveState();//w w w.ja  v a2s  .  c o  m
    try {
        final AffineTransform bitmapTransformer = transformer.getBitmapTransform();
        dc.transform(bitmapTransformer);
        final double rotation = transformer.getRotation();

        for (int i = 0; i < uris.size(); i++) {
            URI uri = uris.get(i);
            if (uri == null) {
                continue;
            }

            final int line = i / nbTilesHorizontal;
            final int col = i % nbTilesHorizontal;
            final float posX = 0 - offsetX + col * bitmapTileW;
            final float posY = 0 - offsetY + line * bitmapTileH;

            if (rotation != 0.0
                    && !isTileVisible(posX, posY, bitmapTileW, bitmapTileH, bitmapTransformer, transformer)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Not needed: " + uri);
                }
                continue;
            }

            LOGGER.debug(uri);
            final Image map = PDFUtils.getImage(context, uri, bitmapTileW, bitmapTileH);
            map.setAbsolutePosition(posX, posY);

            if (opacity < 1.0) {
                PdfGState gs = new PdfGState();
                gs.setFillOpacity(opacity);
                gs.setStrokeOpacity(opacity);
                dc.setGState(gs);
            }
            dc.addImage(map);
        }
    } catch (DocumentException e) {
        context.addError(e);
    } finally {
        dc.restoreState();
    }
}

From source file:org.mapfish.print.map.renderers.BitmapTileRenderer.java

License:Open Source License

public void render(Transformer transformer, List<URI> uris, ParallelMapTileLoader parallelMapTileLoader,
        final RenderingContext context, final float opacity, int nbTilesHorizontal, float offsetX,
        float offsetY, final long bitmapTileW, final long bitmapTileH) throws IOException {
    final AffineTransform bitmapTransformer = transformer.getBitmapTransform();
    final double rotation = transformer.getRotation();

    for (int i = 0; i < uris.size(); i++) {
        final URI uri = uris.get(i);
        if (uri == null) {
            continue;
        }//  w  w  w . ja v  a  2 s .  c  o  m

        final int line = i / nbTilesHorizontal;
        final int col = i % nbTilesHorizontal;
        final float posX = 0 - offsetX + col * bitmapTileW;
        final float posY = 0 - offsetY + line * bitmapTileH;

        if (rotation != 0.0
                && !isTileVisible(posX, posY, bitmapTileW, bitmapTileH, bitmapTransformer, transformer)) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Not needed: " + uri);
            }
            continue;
        }

        parallelMapTileLoader.addTileToLoad(new MapTileTask() {
            public Image map;

            protected void readTile() throws IOException, DocumentException {
                map = PDFUtils.getImage(context, uri, bitmapTileW, bitmapTileH);
                map.setAbsolutePosition(posX, posY);
            }

            protected void renderOnPdf(PdfContentByte dc) throws DocumentException {
                dc.transform(bitmapTransformer);
                if (opacity < 1.0) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(opacity);
                    gs.setStrokeOpacity(opacity);
                    dc.setGState(gs);
                }
                dc.addImage(map);
            }
        });
    }
}

From source file:org.mapfish.print.map.renderers.PDFMapRenderer.java

License:Open Source License

public void render(Transformer transformer, List<URI> uris, PdfContentByte dc, RenderingContext context,
        float opacity, int nbTilesHorizontal, float offsetX, float offsetY, long bitmapTileW, long bitmapTileH)
        throws IOException {
    if (uris.size() != 1) {
        //tiling not supported in PDF
        throw new InvalidValueException("format", "application/x-pdf");
    }/* w  w w  .ja v a2  s.  co  m*/
    final URI uri = uris.get(0);
    LOGGER.debug(uri);
    PdfReader reader = new PdfReader(uri.toURL());
    PdfImportedPage pdfMap = context.getWriter().getImportedPage(reader, 1);

    if (opacity < 1.0) {
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(opacity);
        gs.setStrokeOpacity(opacity);
        //gs.setBlendMode(PdfGState.BM_SOFTLIGHT);
        pdfMap.setGState(gs);
    }

    dc.saveState();
    try {
        dc.transform(transformer.getPdfTransform());
        dc.addTemplate(pdfMap, 0, 0);
    } finally {
        dc.restoreState();
    }
}

From source file:org.mapfish.print.map.renderers.PDFTileRenderer.java

License:Open Source License

public void render(final Transformer transformer, List<URI> uris, ParallelMapTileLoader parallelMapTileLoader,
        final RenderingContext context, final float opacity, int nbTilesHorizontal, float offsetX,
        float offsetY, long bitmapTileW, long bitmapTileH) throws IOException {
    if (uris.size() != 1) {
        //tiling not supported in PDF
        throw new InvalidValueException("format", "application/x-pdf");
    }/*ww w. ja  v  a 2 s  . c om*/
    final URI uri = uris.get(0);

    parallelMapTileLoader.addTileToLoad(new MapTileTask() {
        public PdfImportedPage pdfMap;

        protected void readTile() throws IOException, DocumentException {
            LOGGER.debug(uri);
            PdfReader reader = new PdfReader(uri.toURL());
            synchronized (context.getPdfLock()) {
                pdfMap = context.getWriter().getImportedPage(reader, 1);

                if (opacity < 1.0) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(opacity);
                    gs.setStrokeOpacity(opacity);
                    //gs.setBlendMode(PdfGState.BM_SOFTLIGHT);
                    pdfMap.setGState(gs);
                }
            }
        }

        protected void renderOnPdf(PdfContentByte dc) throws DocumentException {
            dc.transform(transformer.getPdfTransform());
            dc.addTemplate(pdfMap, 0, 0);
        }
    });
}