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

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

Introduction

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

Prototype

PdfGState

Source Link

Usage

From source file:org.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

private void setFill(Color color) {
    // Color and transparency
    PdfGState state = new PdfGState();
    state.setFillOpacity(color.getAlpha() / 255f);
    state.setBlendMode(PdfGState.BM_NORMAL);
    template.setGState(state);/*ww  w  .  j a  va 2  s  .c  o m*/
    template.setColorFill(color);
}

From source file:org.jaffa.modules.printing.services.FormPrintEngineIText.java

License:Open Source License

/**
 * This will fill in the page with data,
 * m_currentPageData contains the details of the current page being printed
 * @throws FormPrintException Thrown if there is any form processing problems
 *///  w w w  .j ava 2s. c o m
protected void fillPageFields() throws FormPrintException {
    log.debug("fillPageFields: Page=" + getCurrentPage());

    try {
        PdfContentByte cb = m_writer.getDirectContent();
        PageDetailsExtended page = (PageDetailsExtended) getCurrentPageData();

        //                // Test code to throw a barcode on the page...
        //                Barcode39 code39 = new Barcode39();
        //                code39.setCode("CODE39-1234567890");
        //                code39.setStartStopText(false);
        //                code39.setSize(0);
        //                Image image39 = code39.createImageWithBarcode(cb, null, null);
        //                com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(2);
        //                table.setWidthPercentage(100);
        //                table.getDefaultCell().setBorder(com.lowagie.text.Rectangle.NO_BORDER);
        //                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        //                table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        //                table.getDefaultCell().setFixedHeight(70);
        //                table.addCell("CODE 39");
        //                table.addCell(new Phrase(new Chunk(image39, 0, 0)));
        //                m_generatedDoc.add(table);
        //                //--------------------------------------------------

        // Loop through each field to be inserted
        for (Iterator i = page.fieldList.iterator(); i.hasNext();) {
            String fieldname = (String) i.next();

            // Get the properties for displaying this field
            FieldProperties props = (FieldProperties) page.fieldProperties.get(fieldname);

            // Get the data to display
            FormPrintEngine.DomValue data = new FormPrintEngine.DomValue(fieldname, props.sampleData);

            // Caluclate Clipping Region
            float x1 = Math.min(props.x1, props.x2);
            float x2 = Math.max(props.x1, props.x2);
            float y1 = Math.min(props.y1, props.y2);
            float y2 = Math.max(props.y1, props.y2);
            float w = Math.abs(props.x1 - props.x2) + 1;
            float h = Math.abs(props.y1 - props.y2) + 1;

            if (log.isDebugEnabled())
                log.debug("Print Field " + fieldname + "=" + data.getObject() + " @ [(" + x1 + "," + y1 + ")->("
                        + x2 + "," + y2 + ")]");

            // Default the font if not specified
            String font = BaseFont.HELVETICA;
            if (props.fontFace != null)
                font = props.fontFace;

            // Handle Barcodes diffently withing iText, don't just use fonts
            if (font.startsWith("Barcode")) {
                String bcClassName = "com.lowagie.text.pdf." + font;
                Object bcode = null;
                String dataStr = data.getValue();
                if (dataStr != null) {
                    log.debug("Barcode Data String = " + dataStr);
                    // Try and create the correct Barcode Object
                    try {
                        Class bcClass = Class.forName(bcClassName);
                        bcode = bcClass.newInstance();
                    } catch (Exception e) {
                        String err = "Can't Create Barcode Object for barcode type '" + font + "' on field "
                                + fieldname;
                        log.error(err, e);
                    }

                    // Only continue if the barcode object was created
                    if (bcode != null) {

                        // Generate and Print barcode, based on common interface
                        if (bcode instanceof Barcode) {
                            Barcode b = (Barcode) bcode;
                            // Set some default output a barcode
                            b.setCode(dataStr);
                            if (props.fontSize <= 0) {
                                // Hide text if font size is 0, and make the barcode height the size of the box
                                b.setBarHeight(h);
                                b.setFont(null);
                            } else {
                                b.setSize(props.fontSize); // size of text under barcode
                                b.setBarHeight(h - props.fontSize - 5); // Adjust Bar Height to allow for font size
                            }
                            b.setN(2); // Wide Bars

                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);

                            // Print out barcode
                            Image image = ((Barcode) bcode).createImageWithBarcode(cb, null, null);
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);

                        } else

                        // Print PDF417 barcode, not based on common interface
                        if (bcode instanceof BarcodePDF417) {
                            BarcodePDF417 b = (BarcodePDF417) bcode;
                            // Set some default output a barcode
                            b.setText(dataStr);
                            b.setErrorLevel(5);
                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);
                            log.debug("PDF417 Settings\n" + "BitColumns=" + b.getBitColumns() + "\n"
                                    + "CodeColumns=" + b.getCodeColumns() + "\n" + "CodeRows=" + b.getCodeRows()
                                    + "\n" + "ErrorLevel=" + b.getErrorLevel() + "\n" + "YHeight="
                                    + b.getYHeight() + "\n" + "AspectRatio=" + b.getAspectRatio() + "\n"
                                    + "Options=" + b.getOptions() + "\n" + "LenCodewords="
                                    + b.getLenCodewords());

                            // Print out barcode
                            //image = b.getImage();
                            printImage(b.getImage(), cb, x1, y1, x2, y2, props.align, props.fitMethod,
                                    props.rotate);

                        } else {
                            // Error, unknown barcode
                            String err = "Error, No print handler for barcode object "
                                    + bcode.getClass().getName();
                            log.error(err);
                            //throw new EngineProcessingException(err);
                        }
                    }
                } else
                    log.debug("SKIPPED BARCODE : No data for " + fieldname);

                // Handle Images differently within iText, native support for JFreeChart
            } else if ("image".equalsIgnoreCase(font)) {
                try {
                    java.awt.Image image = data.getDomImage();
                    // Add an image to the page
                    if (image != null) {
                        if (fieldname.startsWith("watermark")) {
                            // Add an image-based watermark to the under content layer
                            PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                            if (props.opacity != 1f) {
                                PdfGState gs = new PdfGState();
                                gs.setFillOpacity(props.opacity);
                                contentUnder.setGState(gs);
                            }
                            printImage(image, contentUnder, x1, y1, x2, y2, props.align, props.fitMethod,
                                    props.rotate);
                        } else {
                            // Add an image to main page layer
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        }
                    }
                } catch (IOException e) {
                    // Add Error on page.
                    Phrase text = new Phrase("Image Error", FontFactory
                            .getFont(FontFactory.HELVETICA_BOLDOBLIQUE, 8f, 0, ColorHelper.getColor("red")));
                    ColumnText ct = new ColumnText(cb);
                    ct.setSimpleColumn(text, x1, y1, x2, y2, 8f, Element.ALIGN_LEFT);
                }
            } else if (fieldname.startsWith("watermark")) {
                // Add a text-based watermark
                String text = data.getValue();
                PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                if (props.opacity != 1f) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(props.opacity);
                    contentUnder.setGState(gs);
                }
                // The text aligns (left, center, right) on the pivot point.
                // Default to align left.
                float pivotX = x1;
                float pivotY = y1;
                if (Element.ALIGN_CENTER == props.align) {
                    pivotX = (x1 / 2) + (x2 / 2);
                    pivotY = y1;
                } else if (Element.ALIGN_RIGHT == props.align) {
                    pivotX = x2;
                    pivotY = y1;
                }
                Phrase watermark = new Phrase(text, FontFactory.getFont(props.fontFace, props.fontSize,
                        decodeFontStyle(props.style), ColorHelper.getColor(defaultWatermarkColor)));
                ColumnText.showTextAligned(contentUnder, props.align, watermark, pivotX, pivotY, props.rotate);
            } else {
                // Handle printing of basic Text
                float lineHeight = props.fontSize;
                String str = data.getValue();
                if (str != null) {
                    // Add a bounded column to add text to.
                    Phrase text = new Phrase(str, FontFactory.getFont(props.fontFace, props.fontSize,
                            decodeFontStyle(props.style), ColorHelper.getColor(props.color)));
                    ColumnText ct = new ColumnText(cb);
                    if (props.fitMethod == FIT_METHOD_CLIP)
                        // set up column with height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, x2, y2, lineHeight, props.align);
                    else
                        // set up column without (i.e. large) height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, 1000, 0, lineHeight, props.align);
                    ct.go();
                }
            }

            // Draw outline boxes arround fields
            if (isTemplateMode()) {
                cb.setLineWidth(0.5f);
                cb.setLineDash(4f, 2f);
                cb.setColorStroke(new Color(0xA0, 0xA0, 0xA0));
                cb.moveTo(x1, y1);
                cb.lineTo(x1, y2);
                cb.lineTo(x2, y2);
                cb.lineTo(x2, y1);
                cb.lineTo(x1, y1);
                cb.stroke();
            }
        } // end for-loop
    } catch (DocumentException e) {
        String err = "Error printing data - " + e.getMessage();
        log.error(err, e);
        throw new EngineProcessingException(err);
        //        } catch (IOException e) {
        //            String err = "Error printing data - " + e.getMessage();
        //            log.error(err ,e);
        //            throw new EngineProcessingException(err);
    }

}

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.
 *//*  w  w w  .ja v a  2 s  .co 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.
 * /*  w w  w .  j  av a2  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 Final watermark on the input Stream.
 *
 * @param templateStream//from   www . j  ava  2  s . co  m
 * @param finalmarkText
 * @return
 * @throws IOException
 * @throws DocumentException
 */
public static byte[] createFinalmarkOnFile(byte[] templateStream, String finalmarkText)
        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, BaseFont.WINANSI, BaseFont.EMBEDDED);
        PdfGState gstate = new PdfGState();
        while (i <= n) {
            // Watermark under the existing page
            Rectangle pageSize = pdfReader.getPageSizeWithRotation(i);
            over = pdfStamper.getOverContent(i);
            over.beginText();
            over.setFontAndSize(bf, 8);
            over.setGState(gstate);
            over.setColorFill(Color.BLACK);
            over.showTextAligned(Element.ALIGN_CENTER, finalmarkText, (pageSize.width() / 2),
                    (pageSize.height() - 10), 0);
            over.endText();
            i++;
        }
        pdfStamper.close();
    } catch (DocumentException ex) {
        throw new IOException("iText error creating final watermark on PDF", ex);
    } catch (IOException ex) {
        throw new IOException("IO error creating final watermark on PDF", ex);
    }
    return outputStream.toByteArray();
}

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  www .  ja  v a  2s .  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.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//from w w  w . ja  va 2 s. c  o m
    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   ww w  .j a v  a2 s  .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);/*from www .  j  av  a 2 s .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();/* ww  w.j  a  v a2s .  co 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();
    }
}