Example usage for com.lowagie.text Image setRotationDegrees

List of usage examples for com.lowagie.text Image setRotationDegrees

Introduction

In this page you can find the example usage for com.lowagie.text Image setRotationDegrees.

Prototype

public void setRotationDegrees(float deg) 

Source Link

Document

Sets the rotation of the image in degrees.

Usage

From source file:bucks.GenerateChecks.java

License:Open Source License

void generate_mb(Document document, int seq, String value, Image image, PdfWriter writer) {
    try {/*from   w w w  .j a  v  a 2 s  .c o m*/
        float[] widths = { 15f, 40f, 45f }; // percentages         
        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(100);
        table.setSpacingAfter(0f);
        table.setSpacingBefore(0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        PdfPCell cell = new PdfPCell(image);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        // cell.setFixedHeight(46f);
        table.addCell(cell);
        Phrase phrase = new Phrase();
        Chunk ch = new Chunk("FARMERS' MARKET BUCKS\n", fntb2);
        phrase.add(ch);
        ch = new Chunk("Parks & Recreation\nBloomington, IN", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Issue Date___________ ", fnt10);
        phrase.add(ch);
        ch = new Chunk("No. " + seq, fnt10);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
        //
        // document.add(table);
        //
        phrase = new Phrase();
        ch = new Chunk("\nThis certificate is good for ", fnt);
        phrase.add(ch);
        ch = new Chunk("$" + value + ".00 ", fntb2);
        phrase.add(ch);
        ch = new Chunk("towards the purchase of ", fnt);
        phrase.add(ch);
        ch = new Chunk("eligible food items ", fntb);
        phrase.add(ch);
        ch = new Chunk("at the Bloomington Community Farmers' Market. ", fnt);
        phrase.add(ch);
        ch = new Chunk("No change allowed. \n", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setFixedHeight(48f);
        cell.setColspan(3);
        table.addCell(cell);

        document.add(table);
        //
        float[] widths2 = { 60f, 25f, 10f, 5f };
        table = new PdfPTable(widths2);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        //table.getDefaultCell().setPadding(0);
        table.setSpacingAfter(0f);
        table.setSpacingBefore(0f);
        //
        phrase = new Phrase();
        ch = new Chunk(
                "Customers shall redeem this certificate at Farmers' Market\nby December 1st of the year issued.",
                fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);

        cell.setColspan(2);
        cell.setFixedHeight(81f);
        table.addCell(cell);
        //
        Barcode barcode = BarcodeFactory.createCode39("" + seq, false);
        // barcode text has problem, so we turned off
        // and decided to add it ourselves.
        barcode.setDrawingText(false);
        // barcode.setFont(new java.awt.Font("Arial", java.awt.Font.PLAIN, 16));
        // barcode.setLabel(""+seq);
        BufferedImage bi = BarcodeImageHandler.getImage(barcode);
        /*
        int width = bi.getWidth();
        int height = bi.getHeight();
        Graphics2D g2 = bi.createGraphics();
        g2.setColor(Color.BLACK);
        g2.drawString(""+seq, 60, 70);
        g2.dispose();
        */
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //
        // added this hack to get rid of underline in the barcode
        // this worked on windows, but the text did not show up on linux
        // that is why we decided to abandon the text all the way
        // and add it ourselves
        /*
        BarcodeImageHandler.writePNG(barcode, baos);
        File bcImg = File.createTempFile("bc-", ".png");
        bcImg.deleteOnExit();
        byte[] imageBytes = baos.toByteArray();
        FileOutputStream fos = new FileOutputStream(bcImg);
        BarcodeImageHandler.writePNG(barcode, fos);
        */
        //
        // old
        ImageIO.write(bi, "png", baos);
        byte[] imageBytes = baos.toByteArray();
        //
        Image barCodeImage = Image.getInstance(imageBytes);

        barCodeImage.setRotationDegrees(90f);
        // barCodeImage.scalePercent(35f);
        barCodeImage.scalePercent(35f, 50f);
        // float widthf = barCodeImage.getWidth();
        // float heightf = barCodeImage.getHeight();

        cell = new PdfPCell(barCodeImage);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(0);
        cell.setLeading(0f, 0f);
        // cell.setFixedHeight(81f);
        table.addCell(cell);
        //
        // the barcode text that we added underneath the barcode
        //
        int textWidth = 53, textHeight = 50;
        BufferedImage bi2 = new BufferedImage(textWidth, textHeight, BufferedImage.TYPE_BYTE_BINARY);
        Graphics2D g = bi2.createGraphics();
        g.setFont(new java.awt.Font("Verdana", java.awt.Font.PLAIN, 10));
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, textWidth, textHeight);
        g.setColor(Color.BLACK);
        g.drawString("" + seq, 5, 10);

        g.dispose();
        baos = new ByteArrayOutputStream();
        ImageIO.write(bi2, "png", baos);
        imageBytes = baos.toByteArray();
        Image barCodeTextImage = Image.getInstance(imageBytes);

        barCodeTextImage.setRotationDegrees(90f);
        cell = new PdfPCell(barCodeTextImage);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(0);
        cell.setLeading(0f, 0f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("\nThis certificate is not refundable and cannot be replaced if lost or stolen.\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setFixedHeight(34f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("\nMust have official stamp to be valid.\n\n", fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setColspan(3);
        table.addCell(cell);
        document.add(table);
        //
        float[] widths4 = { 40f, 60f }; // percentages         
        table = new PdfPTable(widths4);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        table.setSpacingBefore(0f);
        table.setSpacingAfter(0f);
        phrase = new Phrase();
        ch = new Chunk("APPROVED BY THE STATE BOARD OF ACCOUNTS\nFOR THE CITY OF BLOOMINGTON, IN 2007\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);

        cell.setFixedHeight(40f); // 40
        table.addCell(cell);
        phrase = new Phrase();
        ch = new Chunk(
                "VENDERS SHALL REDEEM THIS CERTIFICATE THROUGH BLOOMINGTON'S\nPARKS & REC DEPT. BY DECEMBER 15TH OF THE YEAR ISSUED\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);
        document.add(table);
    } catch (Exception ex) {
        System.err.println(ex);
    }

}

From source file:bucks.GenerateChecks.java

License:Open Source License

void generate_gc(Document document, int seq, String value, Image image, PdfWriter writer) {
    try {//  w  ww . j  a v  a  2 s  . c  om
        float[] widths = { 13f, 54f, 33f }; // percents
        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.setSpacingAfter(0f);
        table.setSpacingBefore(0f);
        PdfPCell cell = new PdfPCell(image);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setFixedHeight(46f);
        table.addCell(cell);
        Phrase phrase = new Phrase();
        Chunk ch = new Chunk("FARMERS' MARKET GIFT CERTIFICATE\n", fntb2);
        phrase.add(ch);
        ch = new Chunk("Parks & Recreation\nBloomington, IN", fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Issue Date__________ ", fnt10);
        phrase.add(ch);
        ch = new Chunk("No. " + seq, fnt10);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("\nThis certificate is good for ", fnt);
        phrase.add(ch);
        ch = new Chunk("$" + value + ".00 ", fntb2);
        phrase.add(ch);
        ch = new Chunk("towards the purchase of ", fnt);
        phrase.add(ch);
        ch = new Chunk("products from ", fnt);
        phrase.add(ch);
        ch = new Chunk("the Bloomington Community Farmers' Market and A Fair of The Arts Vendors. ", fnt);
        phrase.add(ch);
        ch = new Chunk("Change may be given. \n", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setColspan(3);
        cell.setFixedHeight(48f);
        table.addCell(cell);
        document.add(table);
        //
        float[] widths2 = { 60f, 25f, 10f, 5f };
        table = new PdfPTable(widths2);
        table.setWidthPercentage(100);
        table.setSpacingBefore(0f);
        table.setSpacingAfter(0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        //
        phrase = new Phrase();
        ch = new Chunk("Customers shall redeem this certificate at Market\nwithin one year of date issued. ",
                fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setColspan(2);

        cell.setFixedHeight(81f);
        table.addCell(cell);

        Barcode barcode = BarcodeFactory.createCode39("" + seq, true);
        barcode.setDrawingText(false);
        BufferedImage bi = BarcodeImageHandler.getImage(barcode);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //
        ImageIO.write(bi, "png", baos);
        byte[] imageBytes = baos.toByteArray();
        //
        Image barCodeImage = Image.getInstance(imageBytes);

        barCodeImage.setRotationDegrees(90);
        // barCodeImage.scalePercent(35f);
        barCodeImage.scalePercent(35f, 50f);
        cell = new PdfPCell(barCodeImage);
        //
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(0);
        cell.setLeading(0f, 0f);
        table.addCell(cell);
        //
        // adding text underneath the barcode
        //
        int textWidth = 53, textHeight = 50;
        BufferedImage bi2 = new BufferedImage(textWidth, textHeight, BufferedImage.TYPE_BYTE_BINARY);
        Graphics2D g = bi2.createGraphics();
        g.setFont(new java.awt.Font("Verdana", java.awt.Font.PLAIN, 10));
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, textWidth, textHeight);
        g.setColor(Color.BLACK);
        g.drawString("" + seq, 5, 10);

        g.dispose();
        baos = new ByteArrayOutputStream();
        ImageIO.write(bi2, "png", baos);
        imageBytes = baos.toByteArray();
        Image barCodeTextImage = Image.getInstance(imageBytes);

        barCodeTextImage.setRotationDegrees(90f);
        cell = new PdfPCell(barCodeTextImage);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPadding(0);
        cell.setLeading(0f, 0f);
        table.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("\nThis certificate is not refundable and cannot be replaced if lost or stolen.\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setFixedHeight(30f);
        table.addCell(cell);

        phrase = new Phrase();
        ch = new Chunk("\nMust have official stamp to be valid.\n\n", fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setColspan(3);
        table.addCell(cell);
        document.add(table);
        //
        float[] widths3 = { 40f, 60f }; // percentages         
        table = new PdfPTable(widths3);
        table.setWidthPercentage(100);
        table.setSpacingBefore(0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);

        phrase = new Phrase();
        ch = new Chunk("APPROVED BY THE STATE BOARD OF ACCOUNTS\nFOR THE CITY OF BLOOMINGTON, IN 2007\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        // cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setFixedHeight(44f);
        table.addCell(cell);
        phrase = new Phrase();
        ch = new Chunk(
                "VENDERS SHALL REDEEM THIS CERTIFICATE THROUGH BLOOMINGTON'S\nPARKS & REC DEPT. BY DECEMBER 15TH OF THE YEAR RECEIVED\n\n\n",
                fnts);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);

        document.add(table);
        // document.add( Chunk.NEWLINE );
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:com.geek.tutorial.itext.image.Transformation.java

License:Open Source License

public Transformation() throws Exception {

    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("transformation.pdf"));
    document.open();/*ww w  .j ava2s. co  m*/

    Image img = Image.getInstance("square.jpg");
    img.setAbsolutePosition(100, 650); // Code 1

    img.scaleAbsolute(100, 100); // Code 2

    img.setRotationDegrees(40); // Code 3

    document.add(img);
    document.close();

}

From source file:de.intranda.test_ics.ImageHelper.java

License:Apache License

@SuppressWarnings("unused")
private void addPage(File imageFile, PdfWriter pdfWriter, Document pdfDocument, float shrinkRatio,
        float rotationDegree) throws DocumentException, IOException {

    float pointsPerInch = 200.0f;
    Image pageImage = null;
    float pageImageHeight = 0, pageImageWidth = 0;
    boolean lowMemory = (shrinkRatio == 1 ? false : true);

    URL inputImage = imageFile.toURI().toURL();

    pdfWriter.setFullCompression();// w w w .j a v  a  2  s  . c o m
    pdfWriter.setStrictImageSequence(true);
    pdfWriter.setLinearPageMode();

    LOGGER.debug("Out of memory on loading image for pdf generation");
    // ByteArrayOutputStream stream = new ByteArrayOutputStream();
    BufferedImage bitmap = ImageIO.read(imageFile);
    // LOGGER.debug( "Size of temporary image bitmap: Width = " + bitmap.getWidth() + "; Height = " + bitmap.getHeight());
    LOGGER.debug("Reading file " + imageFile.getAbsolutePath());
    pageImage = Image.getInstance(bitmap, null, false);
    bitmap.flush();
    // stream.close();

    pageImage.setRotationDegrees(-rotationDegree);
    LOGGER.debug("Image dimensions: Width = " + pageImage.getWidth() + "; Height = " + pageImage.getHeight());
    pageImageHeight = pageImage.getHeight();
    pageImageWidth = pageImage.getWidth();
    pageImage.setAbsolutePosition(0, 0);
    // Rectangle pageRect = new Rectangle(pageImageWidth/shrinkRatio, pageImageHeight/shrinkRatio);
    com.lowagie.text.Rectangle pageRect = new com.lowagie.text.Rectangle(pageImageWidth, pageImageHeight);
    LOGGER.debug("Creating rectangle: Width = " + pageRect.getWidth() + "; Height = " + pageRect.getHeight());
    pdfDocument.setPageSize(pageRect);

    if (pdfDocument.isOpen()) {
        pdfDocument.newPage();
        pdfWriter.getDirectContent().addImage(pageImage);

    } else {
        pdfDocument.open();
        pdfWriter.getDirectContent().addImage(pageImage);
    }
    pdfWriter.flush();
    System.gc();
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/******************************************************************************************************
 * Adds the all pages.//from w w  w  .ja v  a2  s  .  c o m
 * 
 * @param pagesizemode {@link PdfPageSize}
 * @param writer {@link PdfWriter}
 * @param pdfdoc {@link Document}
 * @return {@link PdfPageLabels}
 * 
 * 
 * @throws ImageInterpreterException the image interpreter exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MalformedURLException the malformed url exception
 * @throws PDFManagerException the PDF manager exception
 * @throws ImageManagerException
 *******************************************************************************************************/
private PdfPageLabels addAllPages(PdfPageSize pagesizemode, PdfWriter writer, Document pdfdoc,
        Watermark myWatermark) throws ImageInterpreterException, IOException, MalformedURLException,
        PDFManagerException, ImageManagerException {

    PdfPageLabels pagelabels = new PdfPageLabels();
    int pageadded = 0;

    // sort the HashMap by the KeySet (pagenumber)
    Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs);

    float scalefactor = 1; // scaling factor of the image
    int page_w = PaperSize.A4.width;
    int page_h = PaperSize.A4.height;
    LOGGER.debug("iterate over " + imageURLs.size() + " pages.");
    for (Integer imageKey : sortedMap.keySet()) {

        Watermark watermark = myWatermark;
        Image pdfImage = null; // PDF-Image
        LOGGER.debug("Writing page " + imageKey);

        boolean errorPage = false; // true if the image does not exists
        URL errorUrl = null; // url of the image that does not exists

        // ------------------------------------------------------------------------------------------------
        // Title page available. Render it in pdftitlepage
        // ------------------------------------------------------------------------------------------------
        if ((pdftitlepages != null) && (pdftitlepages.get(imageKey) != null)) {
            // title page
            PDFTitlePage pdftitlepage = pdftitlepages.get(imageKey);
            // create new PDF page
            try {
                pdfdoc.setPageSize(PageSize.A4);
                pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(),
                        pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin());
                pageadded++;
                pdfdoc.newPage(); // create new page
                // set page name
                pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "-");
            } catch (Exception e1) {
                throw new PDFManagerException("PDFManagerException occured while creating new page in PDF", e1);
            }
            // render title page
            pdftitlepage.render(pdfdoc);
        }

        // ------------------------------------------------------------------------------------------------
        // Process image with imageKey
        // ------------------------------------------------------------------------------------------------
        UrlImage pdfpage = imageURLs.get(imageKey);
        if (pdfpage.getURL() != null) {
            boolean added = false;
            boolean scaled = false;
            URL url = pdfpage.getURL();
            // pdf hack
            if (ContentServerConfiguration.getInstance().getUsePdf()) {
                LOGGER.debug("trying to find original pdf");
                PdfContentByte pdfcb = null;
                PdfReader pdfreader = null;
                PdfImportedPage importpage = null;
                try {
                    String pdfpath = ContentServerConfiguration.getInstance().getRepositoryPathPdf()
                            .replace("file:///", "");
                    LOGGER.debug("looking in " + pdfpath + " for pdf file");
                    String tiffPath = ContentServerConfiguration.getInstance().getRepositoryPathImages()
                            .replace("file:///", "");
                    // String urlString = url.toString();
                    int pageNumber = pdfpage.getPageNumber();
                    // UrlImage copy = new PDFPage(pdfpage);
                    URL pdfurl = new URL(url.toString().replace(tiffPath, pdfpath)
                            .replace(url.toString().substring(url.toString().lastIndexOf(".")), ".pdf"));
                    LOGGER.debug("pdfurl = " + pdfurl);

                    if (new File(pdfurl.toURI()).exists()) {
                        LOGGER.debug("found pdf " + pdfurl.toURI());
                        // copy.setURL(pdfurl);
                        pdfcb = writer.getDirectContent();
                        pdfreader = new PdfReader(pdfurl);
                        importpage = writer.getImportedPage(pdfreader, pageNumber);

                        LOGGER.debug("creating orig pdf page");
                        Rectangle rect = pdfreader.getPageSize(pageNumber);
                        try {
                            pdfdoc.setPageSize(rect);
                            pdfdoc.newPage(); // create new page
                        } catch (Exception e1) {
                            throw new PDFManagerException("Exception occured while creating new page in PDF",
                                    e1);
                        }
                        pageadded++;
                        pdfcb.addTemplate(importpage, 0, 0);
                        added = true;
                        LOGGER.debug("page:" + imageKey + "  url: " + pdfurl.toString());

                    }
                } catch (URISyntaxException e) {
                    LOGGER.debug(e);
                    added = false;
                } finally {
                    if (writer != null) {
                        writer.freeReader(pdfreader);
                        writer.flush();
                    }
                    if (pdfreader != null) {
                        pdfreader.close();
                    }
                }
            }
            if (!added) {
                // image file
                LOGGER.debug("using image to create pdf page");
                // try to get ImageInterpreter from url
                ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost,
                        httpproxyport, httpproxyuser, httpproxypassword);

                try {
                    // check preferred compression type depending on color depth
                    Embedd preferredEmbeddingType = Embedd.ORIGBYTESTREAM;
                    if (myInterpreter.getColordepth() == 1) {
                        // bitonal image
                        preferredEmbeddingType = embeddBitonalImage;
                    } else if ((myInterpreter.getColordepth() > 1)
                            && (myInterpreter.getSamplesperpixel() == 1)) {
                        // greyscale image
                        preferredEmbeddingType = embeddGreyscaleImage;
                    } else {
                        // color image
                        preferredEmbeddingType = embeddColorImage;
                    }

                    // -------------------------------------------------------------------------------------
                    // Try to generate image
                    // -------------------------------------------------------------------------------------
                    pdfImage = generatePdfImageFromInterpreter(myInterpreter, preferredEmbeddingType, errorPage,
                            watermark, errorUrl);

                    // -------------------------------------------------------------------------------------
                    // image couldn't be embedded yet (emergencyCase)
                    // -------------------------------------------------------------------------------------
                    if (pdfImage == null) {
                        LOGGER.warn(
                                "Couldn't use preferred method for embedding the image. Instead had to use JPEG or RenderedImage");

                        // Get Interpreter and rendered Image
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        RenderedImage ri = null;
                        if (preferredEmbeddingType == embeddBitonalImage) {
                            ImageManager sourcemanager = new ImageManager(url);
                            boolean watermarkscale = ContentServerConfiguration.getInstance()
                                    .getScaleWatermark(); // should we scale
                            // the watermark ?
                            ri = sourcemanager.scaleImageByPixel(3000, 0, ImageManager.SCALE_BY_WIDTH, 0, null,
                                    null, watermark, watermarkscale, ImageManager.BOTTOM);
                            myInterpreter = sourcemanager.getMyInterpreter();
                        } else {
                            ri = myInterpreter.getRenderedImage();
                            if (watermark != null) {
                                ri = addwatermark(ri, watermark, 2);
                                myInterpreter.setHeight(
                                        myInterpreter.getHeight() + watermark.getRenderedImage().getHeight());
                            }
                        }

                        // scale rendered image
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        // float scalefactorX = 1;
                        // float scalefactorY = 1;
                        // switch (pagesizemode) {
                        // case ORIGINAL:
                        // scalefactorX = 72f / myInterpreter.getXResolution();
                        // scalefactorY = 72f / myInterpreter.getYResolution();
                        // break;
                        // default:
                        // /*
                        // * check, if the image needs to be scaled, because
                        // * it's bigger than A4 calculate the new scalefactor
                        // */
                        // float page_w_pixel = (float) (page_w *
                        // myInterpreter.getXResolution() / 25.4);
                        // float page_h_pixel = (float) (page_h *
                        // myInterpreter.getYResolution() / 25.4);
                        //
                        // float res_x = myInterpreter.getXResolution();
                        // float res_y = myInterpreter.getYResolution();
                        //
                        // long w = myInterpreter.getWidth(); // get height and
                        // // width
                        // long h = myInterpreter.getHeight();
                        //
                        // if ((w > page_w_pixel) || (h > page_h_pixel)) {
                        // LOGGER.debug("scale image to fit the page");
                        // float scalefactor_w = page_w_pixel / w;
                        // float scalefactor_h = page_h_pixel / h;
                        // if (scalefactor_h < scalefactor_w) {
                        // scalefactor = scalefactor_h;
                        // } else {
                        // scalefactor = scalefactor_w;
                        // }
                        // w = (long) (w * scalefactor);
                        // h = (long) (h * scalefactor);
                        // }
                        // scalefactorX = (72f / res_x) * scalefactor;
                        // scalefactorY = (72f / res_y) * scalefactor;
                        // break;
                        // }
                        // //scalefactorX = 0.2f;
                        // //scalefactorY = 0.2f;
                        // if (preferredEmbeddingType == embeddBitonalImage) {
                        // ImageManager sourcemanager = new ImageManager(url);
                        // ri = sourcemanager.scaleImageByPixel((int)
                        // (scalefactorX*100), (int) (scalefactorY*100),
                        // ImageManager.SCALE_BY_PERCENT, 0, null, null,
                        // watermark, true, ImageManager.BOTTOM);
                        // }else{
                        // ri = ImageManipulator.scaleInterpolationBilinear(ri,
                        // scalefactorX, scalefactorY);
                        // }
                        // myInterpreter.setHeight(ri.getHeight());
                        // myInterpreter.setWidth(ri.getWidth());
                        // scaled = true;

                        // add Watermark
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        // ri = addwatermark(ri, watermark,
                        // ImageManager.BOTTOM);
                        // myInterpreter.setHeight(myInterpreter.getHeight() +
                        // watermark.getRenderedImage().getHeight());

                        // Try to write into pdfImage
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        if (myInterpreter.getColordepth() > 1) {
                            // compress image if greyscale or color
                            ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream();
                            // JpegInterpreter jpint = new JpegInterpreter(ri);
                            // jpint.setXResolution(myInterpreter.getXResolution());
                            // jpint.setYResolution(myInterpreter.getYResolution());
                            // jpint.writeToStream(null, bytesoutputstream);
                            LOGGER.error("WritingJPEGImage");
                            writeJpegFromRenderedImageToStream(bytesoutputstream, ri, null, myInterpreter);
                            byte[] returnbyteArray = bytesoutputstream.toByteArray();
                            if (bytesoutputstream != null) {
                                bytesoutputstream.flush();
                                bytesoutputstream.close();
                            }
                            pdfImage = Image.getInstance(returnbyteArray);
                            returnbyteArray = null;
                        } else {
                            // its bitonal, but can't be embedded directly,
                            // need to go via RenderedImage
                            BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri);
                            pdfImage = Image.getInstance(buffImage, null, false);
                            if (myWatermark != null) {
                                // create Image for Watermark
                                JpegInterpreter jpint = new JpegInterpreter(myWatermark.getRenderedImage());
                                ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream();
                                jpint.setXResolution(myInterpreter.getXResolution());
                                jpint.setYResolution(myInterpreter.getYResolution());
                                jpint.writeToStream(null, bytesoutputstream);
                                byte[] returnbyteArray = bytesoutputstream.toByteArray();
                                jpint.clear();
                                if (bytesoutputstream != null) {
                                    bytesoutputstream.flush();
                                    bytesoutputstream.close();
                                }
                                Image blaImage = Image.getInstance(returnbyteArray);
                                returnbyteArray = null;
                                // set Watermark as Footer at fixed position
                                // (200,200)
                                Chunk c = new Chunk(blaImage, 200, 200);
                                Phrase p = new Phrase(c);
                                HeaderFooter hf = new HeaderFooter(p, false);
                                pdfdoc.setFooter(hf);
                            }
                            // pdfdoc.setPageSize(arg0)
                            // TODO das scheint nicht zu funktionieren... sollte
                            // dieser Code entfernt werden?

                        }
                    } // end of : if (pdfImage == null) {
                } catch (BadElementException e) {
                    throw new PDFManagerException("Can't create a PDFImage from a Buffered Image.", e);
                } catch (ImageManipulatorException e) {
                    LOGGER.warn(e);
                }

                // ---------------------------------------------------------------------------------------------------------
                // place the image on the page
                // ---------------------------------------------------------------------------------------------------------
                if (pagesizemode == PdfPageSize.ORIGINAL) {
                    // calculate the image width and height in points, create
                    // the rectangle in points

                    Rectangle rect = null;
                    if (!scaled) {
                        float image_w_points = (myInterpreter.getWidth() / myInterpreter.getXResolution()) * 72;
                        float image_h_points = ((myInterpreter.getHeight()) / myInterpreter.getYResolution())
                                * 72;
                        rect = new Rectangle(image_w_points, image_h_points);
                    } else {
                        rect = new Rectangle(myInterpreter.getWidth(), myInterpreter.getHeight());
                    }

                    // create the pdf page according to this rectangle
                    LOGGER.debug("creating original page sized PDF page:" + rect.getWidth() + " x "
                            + rect.getHeight());
                    pdfdoc.setPageSize(rect);

                    // create new page to put the content
                    try {
                        pageadded++;
                        pdfdoc.newPage();
                    } catch (Exception e1) {
                        throw new PDFManagerException(
                                "DocumentException occured while creating page " + pageadded + " in PDF", e1);
                    }

                    // scale image and place it on page; scaling the image does
                    // not scale the images bytestream
                    if (!scaled) {
                        pdfImage.scalePercent((72f / myInterpreter.getXResolution() * 100),
                                (72f / myInterpreter.getYResolution() * 100));
                    }
                    pdfImage.setAbsolutePosition(0, 0); // set image to lower
                                                        // left corner

                    boolean result;
                    try {
                        result = pdfdoc.add(pdfImage); // add it to PDF
                        if (!result) {
                            throw new PDFManagerException("Image \"" + url.toString()
                                    + "\" can's be added to PDF! Error during placing image on page");
                        }
                    } catch (DocumentException e) {
                        throw new PDFManagerException("DocumentException occured while adding the image to PDF",
                                e);
                    }
                } else {
                    /*
                     * it is not the original page size PDF will contain only A4 pages
                     */
                    LOGGER.debug("creating A4 pdf page");

                    // create new page to put the content
                    try {
                        pageadded++;
                        pdfdoc.setPageSize(PageSize.A4);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }

                    float page_w_pixel = (float) (page_w * myInterpreter.getXResolution() / 25.4);
                    float page_h_pixel = (float) (page_h * myInterpreter.getYResolution() / 25.4);

                    float res_x = myInterpreter.getXResolution();
                    float res_y = myInterpreter.getYResolution();

                    long w = myInterpreter.getWidth(); // get height and width
                    long h = myInterpreter.getHeight();

                    /*
                     * if the page is landscape, we have to rotate the page; this is only done in PDF, the orig image bytestream is NOT rotated
                     */
                    if (w > h) {
                        LOGGER.debug("rotate image");
                        // must be rotated
                        pdfImage.setRotationDegrees(90);
                        // change width and height
                        long dummy = w;
                        w = h;
                        h = dummy;
                        // change the resolutions x and y
                        float dummy2 = res_x;
                        res_x = res_y;
                        res_y = dummy2;
                    }

                    /*
                     * check, if the image needs to be scaled, because it's bigger than A4 calculate the new scalefactor
                     */
                    if ((w > page_w_pixel) || (h > page_h_pixel)) {
                        LOGGER.debug("scale image to fit the page");
                        float scalefactor_w = page_w_pixel / w;
                        float scalefactor_h = page_h_pixel / h;
                        if (scalefactor_h < scalefactor_w) {
                            scalefactor = scalefactor_h;
                        } else {
                            scalefactor = scalefactor_w;
                        }
                        w = (long) (w * scalefactor);
                        h = (long) (h * scalefactor);
                    }
                    if (!scaled) {
                        pdfImage.scalePercent((72f / res_x * 100) * scalefactor,
                                (72f / res_y * 100) * scalefactor);
                    }

                    // center the image on the page
                    // ---------------------------------------------------------------
                    float y_offset = 0; // y - offset
                    // get image size in cm; height
                    float h_cm = (float) (h / (res_x / 2.54));
                    // float w_cm = (float) (w / (res_y / 2.54)); // and width
                    if ((h_cm + 2) < (page_h / 10)) {
                        y_offset = 2 * 72f / 2.54f;
                    }
                    float freespace_x = ((page_w_pixel - w) / res_x * 72f);
                    float freespace_y = ((page_h_pixel - h) / res_y * 72f) - (y_offset);
                    // set position add image
                    pdfImage.setAbsolutePosition(freespace_x / 2, freespace_y);
                    boolean result;
                    try {
                        result = pdfdoc.add(pdfImage);
                    } catch (DocumentException e) {
                        LOGGER.error(e);
                        throw new PDFManagerException("DocumentException occured while adding the image to PDF",
                                e);
                    }
                    if (!result) {
                        // placing the image in the PDF was not successful
                        throw new PDFManagerException("Image \"" + url.toString()
                                + "\" can's be added to PDF! Error during placing image on page");
                    }

                    // draw box around the image page
                    // ------------------------------------------------------------------------------------------------
                    if (pagesizemode == PdfPageSize.A4BOX) {
                        LOGGER.debug("draw box around the image page");

                        // draw a black frame around the image
                        PdfContentByte pcb = writer.getDirectContent();

                        // calculate upper left corner of the box (measurment is
                        // in points)
                        float left_x = (freespace_x / 2);
                        float left_y = freespace_y;

                        // calculate the lower right corner of the box
                        // (measurement is in points)
                        float image_w_points = (w / res_x) * 72;
                        float image_h_points = (h / res_y) * 72;

                        pcb.setLineWidth(1f);
                        pcb.stroke();
                        pcb.rectangle(left_x, left_y, image_w_points, image_h_points);

                        pcb.stroke();
                    }

                } // end of: if (pagesizemode == PdfPageSize.ORIGINAL) {
                pdfImage = null;
                myInterpreter.clear();
                // writer.freeReader(new PdfReader(pdfpage.getURL()));
            } // end of : if (pdfpage.getURL() != null) {

            // ------------------------------------------------------------------------------------------------
            // it is a page from a PDF file which should be inserted
            // ------------------------------------------------------------------------------------------------
            else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) {

                PdfContentByte pdfcb = writer.getDirectContent();

                PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader();
                PdfImportedPage importpage = writer.getImportedPage(pdfreader, pdfpage.getPageNumber());

                if (pagesizemode == PdfPageSize.ORIGINAL) {
                    LOGGER.debug("creating orig pdf page");
                    Rectangle rect = pdfreader.getPageSize(pdfpage.getPageNumber());
                    try {
                        pdfdoc.setPageSize(rect);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }
                    // add content
                    pageadded++;
                    pdfcb.addTemplate(importpage, 0, 0);

                } else {
                    LOGGER.debug("creating A4 pdf page");
                    try {
                        pdfdoc.setPageSize(PageSize.A4);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }

                    // add content
                    pageadded++;
                    pdfcb.addTemplate(importpage, 0, 0);

                    // draw box
                    // if (pagesizemode == PdfPageSize.A4BOX) {
                    // FIXME: nichts implementiert ?
                    // }
                }

            }
            // handle pagename
            if (imageNames != null) {
                String pagename = imageNames.get(imageKey);

                if (pagename != null) {
                    pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, pagename);
                } else {
                    pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "unnumbered");
                }
            }
            // handle bookmarks and set destinator for bookmarks
            LOGGER.debug("handle bookmark(s) for page");

            PdfDestination destinator = new PdfDestination(PdfDestination.FIT);
            setBookmarksForPage(writer, destinator, imageKey); // the key in the
            writer.flush();
            // mashMap is the pagenumber

        } // end of while iterator over all pages

    }
    return pagelabels;

}

From source file:jm.web.Addons.java

License:GNU General Public License

public static Image setMarcaAgua(String logo, int ancho, int alto) {
    try {//from w w w.j  a  v a 2  s  .  c  o m
        Image imagelogo = Image.getInstance(logo);
        imagelogo.setTransparency(new int[] { 255, 255 });
        imagelogo.setRotationDegrees(57);
        imagelogo.scaleAbsolute(ancho, alto);
        imagelogo.setAbsolutePosition(0, 30);
        return imagelogo;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:lucee.runtime.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 new ApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw new ApplicationException("destination file [" + destination + "] already exists");

    // image//  w w w.j av a2s  . c  o  m
    Image img = null;
    if (image != null) {
        lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext, image, false, false, true,
                null);
        img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = Caster.toResource(pageContext, copyFrom, true);
            barr = IOUtil.toBytes(res);
        } catch (ExpressionException ee) {
            barr = Caster.toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw new ApplicationException("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 (!StringUtil.isEmpty(strX))
            x = Caster.toIntValue(strX);
        if (!StringUtil.isEmpty(strY))
            y = Caster.toIntValue(strY);

    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    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 (!StringUtil.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 {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

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

License:Open Source License

/** Print an iText image */
private void printImage(Image image, PdfContentByte cb, float x1, float y1, float x2, float y2, int alignment,
        int fitMethod, float rotate) throws DocumentException {
    if (image != null) {
        float boxWidth = Math.abs(x2 - x1) + 1;
        float boxHeight = Math.abs(y2 - y1) + 1;
        log.debug("Print Image (Size w=" + image.getPlainWidth() + ",h=" + image.getPlainHeight()
                + ") wthin BOX (w=" + boxWidth + ",h=" + boxHeight + ") FitMethod = " + fitMethod);

        // Clip the image based on the bounding box
        if (fitMethod == FIT_METHOD_CLIP) {
            if ((boxWidth < image.getPlainWidth()) || (boxHeight < image.getPlainHeight())) {
                // @TODO - Clip image
                log.warn("IMAGE CLIPPING REQUIRED, but not implemented - default to 'SCALE'...");
                fitMethod = FIT_METHOD_SCALE;
            }/*from w w  w .  ja  v  a2s . c  om*/
        }
        // Stretch/shrink both the X/Y to fit the bounding box
        if (fitMethod == FIT_METHOD_FILL) {
            log.debug("Scale image to fill box");
            image.scaleToFit(x2 - x1, y2 - y1);
        }
        // Stretch/shrink preserving the aspect ratio to fit the bounding box
        if (fitMethod == FIT_METHOD_SCALE) {
            float multipler = Math.min(boxWidth / image.getPlainWidth(), boxHeight / image.getPlainHeight());
            log.debug("Need to scale image by " + (Math.floor(multipler * 10000) / 100) + "%");
            image.scalePercent(multipler * 100);
        }
        log.debug("Print image at (" + x1 + "," + y1 + ")");
        image.setAbsolutePosition(x1, y1);
        image.setRotationDegrees(rotate);
        cb.addImage(image);
        //Phrase text = new Phrase(new Chunk(image, 0, 0));
        //ColumnText ct = new ColumnText(cb);
        //ct.setSimpleColumn(text, x1, y1, x2, y2, 10, alignment);
        //ct.go();
    }
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void stampImage(int pageCount, PdfPageData currentPageData, final StampImageToPDFPages stampImage) {
    File tempFile = null;//  ww  w  . ja va  2  s  .  c  o m

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = stampImage.getPages();

        if (pgsToEdit == null)
            return;

        File fileToTest = new File(stampImage.getImageLocation());
        if (!fileToTest.exists()) {
            currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.ImageDoesNotExist"));
            return;
        }

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        final PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        int n = reader.getNumberOfPages();

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        Image img = Image.getInstance(fileToTest.getAbsolutePath());

        int chosenWidthScale = stampImage.getWidthScale();
        int chosenHeightScale = stampImage.getHeightScale();

        img.scalePercent(chosenWidthScale, chosenHeightScale);

        String chosenPlacement = stampImage.getPlacement();

        int chosenRotation = stampImage.getRotation();
        img.setRotationDegrees(chosenRotation);

        String chosenHorizontalPosition = stampImage.getHorizontalPosition();
        String chosenVerticalPosition = stampImage.getVerticalPosition();

        float chosenHorizontalOffset = stampImage.getHorizontalOffset();
        float chosenVerticalOffset = stampImage.getVerticalOffset();

        for (int page = 0; page <= n; page++) {
            if (pagesToEdit.contains(new Integer(page))) {

                PdfContentByte cb;
                if (chosenPlacement.equals("Overlay"))
                    cb = stamp.getOverContent(page);
                else
                    cb = stamp.getUnderContent(page);

                int currentRotation = currentPageData.getRotation(page);
                Rectangle pageSize;
                if (currentRotation == 90 || currentRotation == 270)
                    pageSize = reader.getPageSize(page).rotate();
                else
                    pageSize = reader.getPageSize(page);

                float startx, starty;
                if (chosenVerticalPosition.equals("From the top")) {
                    starty = pageSize.height() - ((img.height() * (chosenHeightScale / 100)) / 2);
                } else if (chosenVerticalPosition.equals("Centered")) {
                    starty = (pageSize.height() / 2) - ((img.height() * (chosenHeightScale / 100)) / 2);
                } else {
                    starty = 0;
                }

                if (chosenHorizontalPosition.equals("From the left")) {
                    startx = 0;
                } else if (chosenHorizontalPosition.equals("Centered")) {
                    startx = (pageSize.width() / 2) - ((img.width() * (chosenWidthScale / 100)) / 2);
                } else {
                    startx = pageSize.width() - ((img.width() * (chosenWidthScale / 100)) / 2);
                }

                img.setAbsolutePosition(startx + chosenHorizontalOffset, starty + chosenVerticalOffset);

                cb.addImage(img);
            }
        }

        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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  v  a 2s.  co 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));
            }
        }
    }
}