Example usage for com.lowagie.text Image getInstance

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

Introduction

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

Prototype

public static Image getInstance(Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:ispyb.client.mx.collection.PdfRtfExporter.java

License:Open Source License

private void setImagesTable(Document document, DataCollectionInformation dcInfo) throws Exception {
    String imgCrystal = dcInfo.getPathjpgCrystal();
    String imgDiff1 = dcInfo.getPathDiffractionImg1();
    String imgDiff2 = dcInfo.getPathDiffractionImg2();
    int nbCol = 0;
    if (imgCrystal != null && !imgCrystal.equals("")) {
        nbCol++;/*from   w w  w .  ja va 2s .c o m*/
    }
    if (imgDiff1 != null && !imgDiff1.equals("")) {
        nbCol++;
    }
    if (imgDiff2 != null && !imgDiff2.equals("")) {
        nbCol++;
    }
    if (nbCol > 0) {
        Table tableImage = new Table(nbCol);
        tableImage.setCellsFitPage(true);
        tableImage.setWidth(100); // percentage
        tableImage.getDefaultCell().setBorderWidth(0);
        tableImage.setBorderWidth(0);
        tableImage.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        // ------------------------------------- Insert crystal image
        // ----------------------------
        if (imgCrystal != null && !imgCrystal.equals("")) {
            try {
                Image jpgCrystal = Image.getInstance(imgCrystal);
                jpgCrystal.scaleAbsolute(CRYSTAL_IMAGE_WIDTH, CRYSTAL_IMAGE_HEIGHT);
                Cell cellCrystalImage = new Cell(jpgCrystal);
                cellCrystalImage.setLeading(0);
                cellCrystalImage.setBorderWidth(0);
                cellCrystalImage.setHorizontalAlignment(Element.ALIGN_CENTER);
                tableImage.addCell(cellCrystalImage);
            } catch (IOException e) {
                tableImage.addCell(new Paragraph(imgCrystal + " not found", FONT_DOC));
            }
        }
        // --- Image 1
        if (imgDiff1 != null && !imgDiff1.equals("")) {
            try {
                Image jpg1 = Image.getInstance(imgDiff1);
                jpg1.scaleAbsolute(DIFF_IMAGE_WIDTH, DIFF_IMAGE_HEIGHT);
                Cell cellDiffractionThumbnail1 = new Cell(jpg1);
                cellDiffractionThumbnail1.setLeading(0);
                cellDiffractionThumbnail1.setBorderWidth(0);
                cellDiffractionThumbnail1.setHorizontalAlignment(Element.ALIGN_CENTER);
                tableImage.addCell(cellDiffractionThumbnail1);
            } catch (IOException e) {
                tableImage.addCell(new Paragraph(imgDiff1 + " not found", FONT_DOC));
            }
        }
        // --- Image 2
        if (imgDiff2 != null && !imgDiff2.equals("")) {
            try {
                Image jpg2 = Image.getInstance(imgDiff2);
                jpg2.scaleAbsolute(DIFF_IMAGE_WIDTH, DIFF_IMAGE_HEIGHT);
                Cell cellDiffractionThumbnail2 = new Cell(jpg2);
                cellDiffractionThumbnail2.setLeading(0);
                cellDiffractionThumbnail2.setBorderWidth(0);
                cellDiffractionThumbnail2.setHorizontalAlignment(Element.ALIGN_CENTER);
                tableImage.addCell(cellDiffractionThumbnail2);
            } catch (IOException e) {
                tableImage.addCell(new Paragraph(imgDiff2 + " not found", FONT_DOC));
            }
        }
        //
        document.add(tableImage);
        document.add(new Paragraph(" ", VERY_SMALL_FONT));
    }
}

From source file:ispyb.client.mx.collection.PdfRtfExporter.java

License:Open Source License

/**
 * returns the cell for the mesh map//from  w ww  .j  a  v a 2  s .  c o m
 * 
 * @param wfMesh
 * @return
 */
private Cell getMeshMapCell(WorkflowMesh3VO wfMesh) {
    String imgMap = null;
    String cartographyPath = wfMesh.getCartographyPath();
    if (cartographyPath != null) {
        imgMap = PathUtils.FitPathToOS(cartographyPath);
    }
    try {
        if (imgMap != null) {
            Image jpgMap = Image.getInstance(imgMap);
            // System.out.println(jpgMap.getWidth()+" * "+jpgMap.getHeight());
            jpgMap.scaleAbsolute(jpgMap.getWidth() * IMAGE_HEIGHT / jpgMap.getHeight(), IMAGE_HEIGHT);
            Cell cellImage = new Cell(jpgMap);
            cellImage.setLeading(0);
            cellImage.setBorderWidth(0);
            cellImage.setHorizontalAlignment(Element.ALIGN_CENTER);
            return cellImage;
        } else {
            return new Cell(new Paragraph("no map found", FONT_DOC));
        }
    } catch (IOException e) {
        try {
            return new Cell(new Paragraph(imgMap + " not found", FONT_DOC));
        } catch (BadElementException e1) {
            e1.printStackTrace();
            return null;
        }
    } catch (Exception e) {
        try {
            return new Cell(new Paragraph(imgMap + " not found", FONT_DOC));
        } catch (BadElementException e1) {
            e1.printStackTrace();
            return null;
        }
    }

}

From source file:ispyb.client.mx.collection.PdfRtfExporter.java

License:Open Source License

/**
 * returns a cell with a given image inside
 * /*from  w  w  w .  j a va  2s. c  o m*/
 * @param image
 * @return
 * @throws Exception
 */
private Cell getCellImage(String image) throws Exception {
    if (image != null && !image.equals("")) {
        try {
            Image jpg1 = Image.getInstance(image);
            jpg1.scaleAbsolute(jpg1.getWidth() * IMAGE_HEIGHT / jpg1.getHeight(), IMAGE_HEIGHT);
            Cell cell = new Cell(jpg1);
            cell.setLeading(0);
            cell.setBorderWidth(0);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            return cell;
        } catch (IOException e) {
            return new Cell(new Paragraph(image + " not found", FONT_DOC));
        }
    }
    return new Cell(new Paragraph("", FONT_DOC));
}

From source file:ispyb.client.mx.collection.PdfRtfExporter.java

License:Open Source License

private Chunk getChunkImage(String image) throws BadElementException, MalformedURLException, IOException {
    Image jpg = Image.getInstance(image);
    jpg.scaleAbsolute(jpg.getWidth() * 10 / jpg.getHeight(), 10);
    return new Chunk(jpg, 0, 0);
}

From source file:ispyb.common.util.export.ExiPdfRtfExporter.java

License:Open Source License

/**
 * returns a cell with a given image inside
 * /* www .ja va  2 s  .co m*/
 * @param image
 * @return
 * @throws Exception
 */
private Cell getCellImage(Map<String, Object> dataCollectionMapItem, String imageParam) throws Exception {

    if (dataCollectionMapItem.get(imageParam) != null
            && !(dataCollectionMapItem.get(imageParam).toString()).equals("")) {
        String image = dataCollectionMapItem.get(imageParam).toString();
        image = PathUtils.getPath(image);
        try {
            Image jpg1 = Image.getInstance(image);
            jpg1.scaleAbsolute(jpg1.getWidth() * IMAGE_HEIGHT / jpg1.getHeight(), IMAGE_HEIGHT);
            Cell cell = new Cell(jpg1);
            cell.setLeading(0);
            cell.setBorderWidth(0);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            return cell;
        } catch (IOException e) {
            return new Cell(new Paragraph(image + " not found", FONT_DOC));
        }
    }
    return new Cell(new Paragraph("", FONT_DOC));
}

From source file:ispyb.common.util.export.ExiPdfRtfExporter.java

License:Open Source License

/**
 * returns a cell with a given image inside
 * /*from   w ww  .jav a 2 s.  co  m*/
 * @param image
 * @return
 * @throws Exception
 */
private Cell getCellImage(String imagePath) throws Exception {

    if (imagePath != null) {
        String image = PathUtils.getPath(imagePath);
        try {
            Image jpg1 = Image.getInstance(image);
            jpg1.scaleAbsolute(jpg1.getWidth() * IMAGE_HEIGHT / jpg1.getHeight(), IMAGE_HEIGHT);
            Cell cell = new Cell(jpg1);
            cell.setLeading(0);
            cell.setBorderWidth(0);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            return cell;
        } catch (IOException e) {
            return new Cell(new Paragraph(image + " not found", FONT_DOC));
        }
    }
    return new Cell(new Paragraph("", FONT_DOC));
}

From source file:it.eng.spagobi.engines.chart.Utilities.ExportCharts.java

License:Mozilla Public License

public static void transformSVGIntoPDF(InputStream inputStream, OutputStream outputStream)
        throws IOException, DocumentException {
    FileOutputStream imageFileOutputStream = null;
    File imageFile = null;/*from   www  .  j  a v a2s  .  c o  m*/
    try {
        imageFile = File.createTempFile("chart", ".jpg");
        imageFileOutputStream = new FileOutputStream(imageFile);
        transformSVGIntoPNG(inputStream, imageFileOutputStream);

        Document pdfDocument = new Document(PageSize.A4.rotate());
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);
        pdfDocument.open();
        Image jpg = Image.getInstance(imageFile.getPath());
        fitImage(jpg);

        pdfDocument.add(jpg);
        pdfDocument.close();
        docWriter.close();
    } finally {
        if (imageFileOutputStream != null) {
            try {
                imageFileOutputStream.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        if (imageFile.exists()) {
            imageFile.delete();
        }
    }
}

From source file:it.eng.spagobi.engines.documentcomposition.exporterUtils.PdfCreator.java

License:Mozilla Public License

public FileOutputStream createPdfFile(FileOutputStream fileOutputStream,
        Map<String, DocumentContainer> documentsMap, boolean defaultStyle)
        throws MalformedURLException, IOException, DocumentException {

    logger.debug("IN");

    Document document = new Document(PageSize.A4.rotate());
    Rectangle rect = document.getPageSize();
    docWidth = rect.getWidth();/*from  w w w  .ja  v  a2 s  .c om*/
    docHeight = rect.getHeight();

    logger.debug("document size width: " + docWidth + " height: " + docHeight);

    //PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("C:/comp/SpagoBIProva.pdf"));
    PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
    document.open();

    int documentsNumber = documentsMap.keySet().size();
    int columnnsNumber = 2;

    if (defaultStyle == true) {
        logger.debug("use default style");
        int cellsCounter = 0;

        PdfPTable table = new PdfPTable(columnnsNumber);
        table.setWidthPercentage(100);

        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            DocumentContainer docContainer = documentsMap.get(label);
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                    table.addCell(img);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    table.addCell("");
                    //                  try {
                    //                     PdfReader reader = new PdfReader(content);
                    //                     PdfImportedPage page = writer.getImportedPage(reader, 1);
                    //                     writer.addPage(page);
                    //                     table.addCell("");
                    //                  } catch (Exception x) {
                    //                     logger.error("Error in inserting image for document " + label, e);
                    //                     logger.error("Error in inserting pdf file for document " + label, x);
                    //                     table.addCell("");
                    //                  }
                }
            }
            cellsCounter++;
        }

        // if cell counter is not pair make it pair
        if (cellsCounter % 2 != 0) {
            table.addCell("");
        }
        document.add(table);

    } else { // ************* NO DEFAULT STYLE *****************
        logger.debug("No default style");

        // I want to calculate total height of scaled heights!!
        //int totalScaledHeight=calculateTotaleScaledHeights(documentsMap, defaultStyle);

        // run on all documents
        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            logger.debug("document with label " + label);

            DocumentContainer docContainer = documentsMap.get(label);
            MetadataStyle style = docContainer.getStyle();

            // one table for each image, set at absolute position
            PdfPTable table = new PdfPTable(1);

            // width and height specified for the container by style attribute
            int widthStyle = style.getWidth();
            int heightStyle = style.getHeight();
            logger.debug("style for document width: " + widthStyle + " height: " + heightStyle);

            // width and height for the table scaled to the document size
            int tableWidth = calculatePxSize(docWidth, widthStyle, videoWidth);
            int tableHeight = calculatePxSize(docHeight, heightStyle, videoHeight);

            logger.debug("table for document width: " + tableWidth + " height: " + tableHeight);

            // x and y position as specified for the container by the style attribute
            int yStyle = style.getY();
            int xStyle = style.getX();
            // width and height scaled to the document size
            int xPos = (calculatePxPos(docWidth, xStyle, videoWidth));
            int yPos = (int) docHeight - (calculatePxPos(docHeight, yStyle, videoHeight));
            logger.debug("Table position at x: " + xPos + " y: " + yPos);

            // get the image
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    try {
                        PdfReader reader = new PdfReader(content);
                        PdfContentByte cb = writer.getDirectContent();
                        PdfImportedPage page = writer.getImportedPage(reader, 1);
                        float[] tm = getTransformationMatrix(page, xPos, yPos, tableWidth, tableHeight);
                        cb.addTemplate(page, tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]);
                    } catch (Exception x) {
                        logger.error("Error in inserting image for document " + label, e);
                        logger.error("Error in inserting pdf file for document " + label, x);
                    }
                    continue;
                }

                //if it is a REPORT and has more than one page, too large, you have to resize the image, but how to understand it?
                // if image size is more than double of the container size cut the first part,otherwise scale it
                if (docContainer.getDocumentType().equals("REPORT")) {
                    boolean cutImageWIdth = isToCutWidth(img, tableWidth);
                    boolean cutImageHeight = isToCutHeight(img, tableWidth);

                    if (cutImageWIdth == true || cutImageHeight == true) {
                        logger.debug(
                                "Report will be cut to width " + tableWidth + " and height " + tableHeight);
                        try {
                            img = cutImage(content, cutImageHeight, cutImageWIdth, tableHeight, tableWidth,
                                    (int) img.getWidth(), (int) img.getHeight());
                        } catch (Exception e) {
                            logger.error(
                                    "Error in image cut, cutt will be ignored and image will be drawn anyway ",
                                    e);
                        }
                    }
                }

                // this is percentage to resize
                // The image must be size within the cell               
                int percToResize = percentageToResize((int) img.getWidth(), (int) img.getHeight(), tableWidth,
                        tableHeight);
                logger.debug("image will be scaled of percentage " + percToResize);
                img.scalePercent(percToResize);

                PdfPCell cell = new PdfPCell(img);
                cell.setNoWrap(true);
                cell.setFixedHeight(tableHeight);
                cell.setBorderWidth(0);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                //table.setWidthPercentage(tableWidthPerc);
                table.setTotalWidth(tableWidth);
                table.setLockedWidth(true);
            } else {
                // TODO: setALT!
            }
            logger.debug("Add table");
            table.writeSelectedRows(0, -1, xPos, yPos, writer.getDirectContent());
            logger.debug("Document added");
        }

    }
    document.close();
    logger.debug("OUT");
    return fileOutputStream;
}

From source file:it.eng.spagobi.engines.documentcomposition.exporterUtils.PdfCreator.java

License:Mozilla Public License

Image cutImage(byte[] bytes, boolean cutImageHeight, boolean cutImageWidth, int tableHeight, int tableWidth,
        int imgWidth, int imgHeight) throws IOException, BadElementException {
    logger.debug("IN");

    BufferedImage image = null; // Read from a file 
    BufferedImage region = null;//w  w  w. j a v  a2s  . c o m

    int pxWidthToCut = (cutImageWidth == true) ? tableWidth : imgWidth;
    int pxHeightToCut = (cutImageHeight == true) ? tableHeight : imgHeight;

    InputStream inputStream = new ByteArrayInputStream(bytes);

    image = ImageIO.read(inputStream); // Read from an input stream 
    try {
        region = image.getSubimage(0, 0, pxWidthToCut, pxHeightToCut);
    } catch (Exception e) {
        e.printStackTrace();
    }
    byte[] newBytes = getBytes(region);
    Image cutImg = Image.getInstance(newBytes);
    //ImageIO.write(region,"PNG",new File("C:/nuovaImmagine222.PNG"));
    logger.debug("OUT");

    return cutImg;
}

From source file:it.eng.spagobi.engines.exporters.ChartExporter.java

License:Mozilla Public License

public File getChartPDF(String uuid, boolean multichart, String orientation) throws Exception {
    logger.debug("IN");

    File tmpFile;/*from ww  w .  j a v a  2 s .  c  om*/

    try {
        tmpFile = null;
        String dir = System.getProperty("java.io.tmpdir");
        String path = (new StringBuilder(String.valueOf(dir))).append("/").append(uuid).append(".png")
                .toString();
        File dirF = new File(dir);
        tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF);
        Document pdfDocument = new Document();
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile));
        //pdfDocument.open();
        if (multichart) {
            pdfDocument.open();

            List images = new ArrayList();
            for (int i = 0; i < MAX_NUM_IMG; i++) {
                String imgName = (new StringBuilder(String.valueOf(path.substring(0, path.indexOf(".png")))))
                        .append(i).append(".png").toString();
                Image png = Image.getInstance(imgName);
                if (png == null) {
                    break;
                }
                images.add(png);
            }

            Table table = new Table(images.size());
            for (int i = 0; i < images.size(); i++) {
                Image png = (Image) images.get(i);
                if (HORIZONTAL_ORIENTATION.equalsIgnoreCase(orientation)) {
                    Cell pngCell = new Cell(png);
                    pngCell.setBorder(0);
                    table.setBorder(0);
                    table.addCell(pngCell);
                } else {
                    png.setAlignment(5);
                    pdfDocument.add(png);
                }
            }

            pdfDocument.add(table);
        } else {
            Image jpg = Image.getInstance(path);
            float height = jpg.getHeight();
            float width = jpg.getWidth();

            // if in need to change layout
            if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                changeLayout(pdfDocument, jpg, width, height);
            }

            pdfDocument.open();
            pdfDocument.add(jpg);
        }
        pdfDocument.close();
        docWriter.close();

        logger.debug("OUT");

        return tmpFile;

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        throw new Exception(e);
    } finally {

        //tmpFile.delete();

    }
}