Example usage for com.lowagie.text Image scaleToFit

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

Introduction

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

Prototype

public void scaleToFit(float fitWidth, float fitHeight) 

Source Link

Document

Scales the image so that it fits a certain width and height.

Usage

From source file:com.conecta.sat.utils.BuildImportTokensPDF.java

@Override
protected void buildPdfDocument(Map<String, Object> map, Document document, PdfWriter writer,
        HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
    //        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    System.out.println("Into BuildImportTokensPDF");
    hsr1.setContentType("application/pdf");
    DateFormat name = new SimpleDateFormat("ddMMyyyyhhmmss");
    hsr1.setHeader("Content-disposition",
            "attachment; filename=ImportTokens" + name.format(new Date()) + ".pdf");
    ImportTokensPDF list = (ImportTokensPDF) map.get("list");
    String nombreUsuario = (String) map.get("nombreUsuario");

    PdfPTable table = new PdfPTable(3);
    table.setWidthPercentage(100);//  www.j a  v a2s  .c  om
    table.setSpacingBefore(10);

    Font font = FontFactory.getFont(FontFactory.HELVETICA);
    try {
        font.setFamily(fontName);
    } catch (Exception e) {
        font.setFamily("Verdana");
    }

    try {
        ServletContext servletContext = hsr.getSession().getServletContext();
        String relativeWebPath = logoPath;
        String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
        Image logo = Image.getInstance(absoluteDiskPath);
        //            Image logo = Image.getInstance("logo.png");
        System.out.println("La imagen se cargo correctamente");
        logo.scaleToFit(widthLogo, heightLogo);
        document.add(logo);
    } catch (Exception e) {
        System.err.println("ERROR" + Excepciones.getStackTrace(e));
        document.add(new Paragraph("Sin imagen " + logoPath));
    }
    font.setSize(fontSize + 3);
    Paragraph titulo = new Paragraph("Reporte de Tokens", font);
    titulo.setAlignment(Element.ALIGN_RIGHT);
    document.add(titulo);

    Chunk CONNECT = new Chunk(new LineSeparator(0.5f, 100, java.awt.Color.BLACK, Element.ALIGN_CENTER, 3.5f));
    document.add(CONNECT);

    DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
    font.setSize(fontSize + 2);
    Paragraph fecha = new Paragraph(df.format(new Date()), font);
    fecha.setAlignment(Element.ALIGN_RIGHT);
    document.add(fecha);

    Paragraph pNombre = new Paragraph(nombreUsuario, font);
    pNombre.setAlignment(Element.ALIGN_RIGHT);
    document.add(pNombre);

    font.setSize(fontSize);
    font.setColor(java.awt.Color.white);

    // define table header cell
    PdfPCell cell = new PdfPCell();
    java.awt.Color color = java.awt.Color.LIGHT_GRAY;
    cell.setBackgroundColor(color);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);

    cell.setPadding(5);

    // write table header
    cell.setPhrase(new Phrase("Nmero de empleado que importo en token", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Fecha y Hora", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Tokens importados", font));
    table.addCell(cell);

    //        cell.setPhrase(new Phrase("Centro Financiero", font));
    //        table.addCell(cell);
    //         
    //        cell.setPhrase(new Phrase("Tipo", font));
    //        table.addCell(cell);
    //        
    //        cell.setPhrase(new Phrase("Cliente nico", font));
    //        table.addCell(cell);
    //        
    //        cell.setPhrase(new Phrase("Fecha de ultima modificacin", font));
    //        table.addCell(cell);

    Font font2 = FontFactory.getFont(FontFactory.HELVETICA);
    try {
        font2.setFamily(fontName);
    } catch (Exception e) {
        font2.setFamily("Verdana");
    }
    font2.setSize(fontSize);
    font2.setColor(java.awt.Color.black);
    // write table row data
    //        for (ImportTokensPDF pdf : list) {
    //        ImportTokensPDF pdf;
    cell = new PdfPCell();
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.addElement(new Phrase(list.getUsuario(), font2));
    table.addCell(cell);

    cell = new PdfPCell();
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.addElement(new Phrase(df.format(list.getFecha()), font2));
    table.addCell(cell);

    cell = new PdfPCell();
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.addElement(new Phrase(list.getTokens(), font2));
    table.addCell(cell);

    //            cell = new PdfPCell();
    //            cell.setHorizontalAlignment( Element.ALIGN_CENTER );
    //            cell.addElement( new Phrase(pdf.getCentro(),font2) );
    //            table.addCell(cell);
    //            
    //            cell = new PdfPCell();
    //            cell.setHorizontalAlignment( Element.ALIGN_CENTER );
    //            cell.addElement( new Phrase(pdf.getTipo(),font2) );
    //            table.addCell(cell);
    //            
    //            cell = new PdfPCell();
    //            cell.setHorizontalAlignment( Element.ALIGN_CENTER );
    //            cell.addElement( new Phrase(pdf.getCliente(),font2) );
    //            table.addCell(cell);
    //            
    //            cell = new PdfPCell();
    //            cell.setHorizontalAlignment( Element.ALIGN_CENTER );
    //            cell.addElement( new Phrase(pdf.getLastUpdate(),font2) );
    //            table.addCell(cell);
    //        }

    document.add(table);
}

From source file:com.conecta.sat.utils.BuildPDF.java

@Override
protected void buildPdfDocument(Map<String, Object> map, Document document, PdfWriter writer,
        HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
    //        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    hsr1.setContentType("application/pdf");
    DateFormat name = new SimpleDateFormat("ddMMyyyyhhmmss");
    hsr1.setHeader("Content-disposition", "attachment; filename=Reporte" + name.format(new Date()) + ".pdf");
    List<PdfDTO> list = (List<PdfDTO>) map.get("list");
    String nombreUsuario = (String) map.get("nombreUsuario");

    PdfPTable table = new PdfPTable(9);
    table.setWidthPercentage(100);//from w  ww .  j a  v  a2  s  .  c  o m
    table.setSpacingBefore(10);

    Font font = FontFactory.getFont(FontFactory.HELVETICA);
    try {
        font.setFamily(fontName);
    } catch (Exception e) {
        font.setFamily("Verdana");
    }

    try {
        ServletContext servletContext = hsr.getSession().getServletContext();
        String relativeWebPath = logoPath;
        String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
        Image logo = Image.getInstance(absoluteDiskPath);
        //            Image logo = Image.getInstance("logo.png");
        System.out.println("La imagen se cargo correctamente");
        logo.scaleToFit(widthLogo, heightLogo);
        document.add(logo);
    } catch (Exception e) {
        System.err.println("ERROR" + Excepciones.getStackTrace(e));
        document.add(new Paragraph("Sin imagen " + logoPath));
    }
    font.setSize(fontSize + 3);
    Paragraph titulo = new Paragraph("Reporte de Tokens", font);
    titulo.setAlignment(Element.ALIGN_RIGHT);
    document.add(titulo);

    Chunk CONNECT = new Chunk(new LineSeparator(0.5f, 100, java.awt.Color.BLACK, Element.ALIGN_CENTER, 3.5f));
    document.add(CONNECT);

    DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
    font.setSize(fontSize + 2);
    Paragraph fecha = new Paragraph(df.format(new Date()), font);
    fecha.setAlignment(Element.ALIGN_RIGHT);
    document.add(fecha);

    Paragraph pNombre = new Paragraph(nombreUsuario, font);
    pNombre.setAlignment(Element.ALIGN_RIGHT);
    document.add(pNombre);

    font.setSize(fontSize);
    font.setColor(java.awt.Color.white);

    // define table header cell
    PdfPCell cell = new PdfPCell();
    java.awt.Color color = java.awt.Color.LIGHT_GRAY;
    cell.setBackgroundColor(color);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);

    cell.setPadding(5);

    // write table header
    cell.setPhrase(new Phrase("Serial Token", font));
    table.addCell(cell);

    //        cell.setPhrase(new Phrase("Estatus Entrega", font));
    cell.setPhrase(new Phrase("Estatus Entrega al Centro Financiero", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Estatus Entrega al Cliente", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Estatus Activacin", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Centro Financiero", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Tipo", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Cliente nico", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Folio Pivotal", font));
    table.addCell(cell);

    //        cell.setPhrase(new Phrase("ID nico", font));
    //        table.addCell(cell);

    cell.setPhrase(new Phrase("Fecha de ltima modificacin", font));
    table.addCell(cell);

    Font font2 = FontFactory.getFont(FontFactory.HELVETICA);
    try {
        font2.setFamily(fontName);
    } catch (Exception e) {
        font2.setFamily("Verdana");
    }
    font2.setSize(fontSize);
    font2.setColor(java.awt.Color.black);
    // write table row data
    for (PdfDTO pdf : list) {
        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getSerial(), font2));
        table.addCell(cell);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getEntrega(), font2));
        table.addCell(cell);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getEntrega(), font2));
        table.addCell(cell);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getActivacion(), font2));
        table.addCell(cell);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getCentro(), font2));
        table.addCell(cell);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getTipo(), font2));
        table.addCell(cell);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getCliente(), font2));
        table.addCell(cell);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getFolioPivotal(), font2));
        table.addCell(cell);

        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment( Element.ALIGN_CENTER );
        //            cell.addElement( new Phrase(pdf.getIdUnico(),font2) );
        //            table.addCell(cell);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.addElement(new Phrase(pdf.getLastUpdate(), font2));
        table.addCell(cell);
    }

    document.add(table);
}

From source file:com.develog.utils.report.engine.export.JRPdfExporter.java

License:Open Source License

/**
 *
 *//*  w  w w. jav  a  2 s .  c o m*/
protected void exportImage(JRPrintImage printImage) throws DocumentException, IOException {
    pdfContentByte.setRGBColorFill(printImage.getBackcolor().getRed(), printImage.getBackcolor().getGreen(),
            printImage.getBackcolor().getBlue());

    int borderOffset = 0;
    float borderCorrection = 0f;
    float lineWidth = 1f;
    boolean isLineDotted = false;

    switch (printImage.getPen()) {
    case JRGraphicElement.PEN_DOTTED: {
        borderOffset = 0;
        borderCorrection = 0f;
        lineWidth = 1f;
        isLineDotted = true;
        break;
    }
    case JRGraphicElement.PEN_4_POINT: {
        borderOffset = 2;
        borderCorrection = 0f;
        lineWidth = 4f;
        isLineDotted = false;
        break;
    }
    case JRGraphicElement.PEN_2_POINT: {
        borderOffset = 1;
        borderCorrection = 0f;
        lineWidth = 2f;
        isLineDotted = false;
        break;
    }
    case JRGraphicElement.PEN_THIN: {
        borderOffset = 0;
        borderCorrection = 0.25f;
        lineWidth = 0.5f;
        isLineDotted = false;
        break;
    }
    case JRGraphicElement.PEN_NONE: {
        borderOffset = 0;
        borderCorrection = 0.5f;
        lineWidth = 1f;
        isLineDotted = false;

        break;
    }
    case JRGraphicElement.PEN_1_POINT:
    default: {
        borderOffset = 0;
        borderCorrection = 0f;
        lineWidth = 1f;
        isLineDotted = false;
        break;
    }
    }

    if (printImage.getMode() == JRElement.MODE_OPAQUE) {
        pdfContentByte.setRGBColorStroke(printImage.getBackcolor().getRed(),
                printImage.getBackcolor().getGreen(), printImage.getBackcolor().getBlue());
        pdfContentByte.setLineWidth(0.1f);
        pdfContentByte.setLineDash(0f);
        pdfContentByte.rectangle(printImage.getX() - borderCorrection,
                jasperPrint.getPageHeight() - printImage.getY() + borderCorrection,
                printImage.getWidth() + 2 * borderCorrection - 1,
                -printImage.getHeight() - 2 * borderCorrection + 1);
        pdfContentByte.fillStroke();
    }

    int availableImageWidth = printImage.getWidth() - 2 * borderOffset;
    availableImageWidth = (availableImageWidth < 0) ? 0 : availableImageWidth;

    int availableImageHeight = printImage.getHeight() - 2 * borderOffset;
    availableImageHeight = (availableImageHeight < 0) ? 0 : availableImageHeight;

    int xoffset = 0;
    int yoffset = 0;

    if (printImage.getImageData() != null && availableImageWidth > 0 && availableImageHeight > 0) {
        //java.awt.Image awtImage = JRImageLoader.loadImage(printImage.getImageData());

        //com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(awtImage, printImage.getBackcolor());
        //com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(awtImage, null);
        com.lowagie.text.Image image = null;

        float xalignFactor = 0f;
        switch (printImage.getHorizontalAlignment()) {
        case JRAlignment.HORIZONTAL_ALIGN_RIGHT: {
            xalignFactor = 1f;
            break;
        }
        case JRAlignment.HORIZONTAL_ALIGN_CENTER: {
            xalignFactor = 0.5f;
            break;
        }
        case JRAlignment.HORIZONTAL_ALIGN_LEFT:
        default: {
            xalignFactor = 0f;
            break;
        }
        }

        float yalignFactor = 0f;
        switch (printImage.getVerticalAlignment()) {
        case JRAlignment.VERTICAL_ALIGN_BOTTOM: {
            yalignFactor = 1f;
            break;
        }
        case JRAlignment.VERTICAL_ALIGN_MIDDLE: {
            yalignFactor = 0.5f;
            break;
        }
        case JRAlignment.VERTICAL_ALIGN_TOP:
        default: {
            yalignFactor = 0f;
            break;
        }
        }

        switch (printImage.getScaleImage()) {
        case JRImage.SCALE_IMAGE_CLIP: {
            java.awt.Image awtImage = JRImageLoader.loadImage(printImage.getImageData());
            //image = com.lowagie.text.Image.getInstance(awtImage, null);

            int awtWidth = awtImage.getWidth(null);
            int awtHeight = awtImage.getHeight(null);

            xoffset = (int) (xalignFactor * (availableImageWidth - awtWidth));
            yoffset = (int) (yalignFactor * (availableImageHeight - awtHeight));

            int minWidth = Math.min(awtWidth, availableImageWidth);
            int minHeight = Math.min(awtHeight, availableImageHeight);

            BufferedImage bi = new BufferedImage(minWidth, minHeight, BufferedImage.TYPE_INT_RGB);

            Graphics g = bi.getGraphics();
            g.setColor(printImage.getBackcolor());
            g.fillRect(0, 0, minWidth, minHeight);
            g.drawImage(awtImage, (xoffset > 0 ? 0 : xoffset), (yoffset > 0 ? 0 : yoffset), null);

            xoffset = (xoffset < 0 ? 0 : xoffset);
            yoffset = (yoffset < 0 ? 0 : yoffset);

            //awtImage = bi.getSubimage(0, 0, minWidth, minHeight);
            awtImage = bi;

            //image = com.lowagie.text.Image.getInstance(awtImage, printImage.getBackcolor());
            image = com.lowagie.text.Image.getInstance(awtImage, null);

            break;
        }
        case JRImage.SCALE_IMAGE_FILL_FRAME: {
            try {
                image = com.lowagie.text.Image.getInstance(printImage.getImageData());
                imageTesterPdfContentByte.addImage(image, 10, 0, 0, 10, 0, 0);
            } catch (Exception e) {
                java.awt.Image awtImage = JRImageLoader.loadImage(printImage.getImageData());
                image = com.lowagie.text.Image.getInstance(awtImage, null);
            }
            image.scaleAbsolute(availableImageWidth, availableImageHeight);
            break;
        }
        case JRImage.SCALE_IMAGE_RETAIN_SHAPE:
        default: {
            try {
                image = com.lowagie.text.Image.getInstance(printImage.getImageData());
                imageTesterPdfContentByte.addImage(image, 10, 0, 0, 10, 0, 0);
            } catch (Exception e) {
                java.awt.Image awtImage = JRImageLoader.loadImage(printImage.getImageData());
                image = com.lowagie.text.Image.getInstance(awtImage, null);
            }
            image.scaleToFit(availableImageWidth, availableImageHeight);

            xoffset = (int) (xalignFactor * (availableImageWidth - image.plainWidth()));
            yoffset = (int) (yalignFactor * (availableImageHeight - image.plainHeight()));

            xoffset = (xoffset < 0 ? 0 : xoffset);
            yoffset = (yoffset < 0 ? 0 : yoffset);

            break;
        }
        }

        /*
        image.setAbsolutePosition(
           printImage.getX() + borderOffset,
           jasperPrint.getPageHeight() - printImage.getY() - image.scaledHeight() - borderOffset
           );
                
        pdfContentByte.addImage(image);
        */

        Chunk chunk = new Chunk(image, -0.5f, 0.5f);

        if (printImage.getAnchorName() != null) {
            chunk.setLocalDestination(printImage.getAnchorName());
        }

        switch (printImage.getHyperlinkType()) {
        case JRHyperlink.HYPERLINK_TYPE_REFERENCE: {
            if (printImage.getHyperlinkReference() != null) {
                chunk.setAnchor(printImage.getHyperlinkReference());
            }
            break;
        }
        case JRHyperlink.HYPERLINK_TYPE_LOCAL_ANCHOR: {
            if (printImage.getHyperlinkAnchor() != null) {
                chunk.setLocalGoto(printImage.getHyperlinkAnchor());
            }
            break;
        }
        case JRHyperlink.HYPERLINK_TYPE_LOCAL_PAGE: {
            if (printImage.getHyperlinkPage() != null) {
                chunk.setLocalGoto("JR_PAGE_ANCHOR_" + printImage.getHyperlinkPage().toString());
            }
            break;
        }
        case JRHyperlink.HYPERLINK_TYPE_REMOTE_ANCHOR: {
            if (printImage.getHyperlinkReference() != null && printImage.getHyperlinkAnchor() != null) {
                chunk.setRemoteGoto(printImage.getHyperlinkReference(), printImage.getHyperlinkAnchor());
            }
            break;
        }
        case JRHyperlink.HYPERLINK_TYPE_REMOTE_PAGE: {
            if (printImage.getHyperlinkReference() != null && printImage.getHyperlinkPage() != null) {
                chunk.setRemoteGoto(printImage.getHyperlinkReference(),
                        printImage.getHyperlinkPage().intValue());
            }
            break;
        }
        case JRHyperlink.HYPERLINK_TYPE_NONE:
        default: {
            break;
        }
        }

        ColumnText colText = new ColumnText(pdfContentByte);
        colText.setSimpleColumn(new Phrase(chunk), printImage.getX() + xoffset + borderOffset,
                jasperPrint.getPageHeight() - printImage.getY() - image.scaledHeight() - yoffset - borderOffset,
                printImage.getX() + xoffset + borderOffset + image.scaledWidth(),
                jasperPrint.getPageHeight() - printImage.getY() - yoffset - borderOffset, image.scaledHeight(),
                Element.ALIGN_LEFT);

        colText.go();
    }

    if (printImage.getPen() != JRGraphicElement.PEN_NONE) {
        pdfContentByte.setRGBColorStroke(printImage.getForecolor().getRed(),
                printImage.getForecolor().getGreen(), printImage.getForecolor().getBlue());

        pdfContentByte.setLineWidth(lineWidth);

        if (isLineDotted) {
            pdfContentByte.setLineDash(5f, 3f, 0f);
        } else {
            pdfContentByte.setLineDash(0f);
        }

        pdfContentByte.rectangle(printImage.getX() - borderCorrection,
                jasperPrint.getPageHeight() - printImage.getY() + borderCorrection,
                printImage.getWidth() + 2 * borderCorrection - 1,
                -printImage.getHeight() - 2 * borderCorrection + 1);

        pdfContentByte.stroke();
    }
}

From source file:com.dlya.facturews.DlyaPdfExporter2.java

License:Open Source License

/**
 *
 *///from w  w  w  .j  a v a 2  s  .  c  om
public void exportImage(JRPrintImage printImage) throws DocumentException, IOException, JRException {
    if (printImage.getModeValue() == ModeEnum.OPAQUE) {
        pdfContentByte.setRGBColorFill(printImage.getBackcolor().getRed(), printImage.getBackcolor().getGreen(),
                printImage.getBackcolor().getBlue());
        pdfContentByte.rectangle(printImage.getX() + getOffsetX(),
                jasperPrint.getPageHeight() - printImage.getY() - getOffsetY(), printImage.getWidth(),
                -printImage.getHeight());
        pdfContentByte.fill();
    }

    int topPadding = printImage.getLineBox().getTopPadding().intValue();
    int leftPadding = printImage.getLineBox().getLeftPadding().intValue();
    int bottomPadding = printImage.getLineBox().getBottomPadding().intValue();
    int rightPadding = printImage.getLineBox().getRightPadding().intValue();

    int availableImageWidth = printImage.getWidth() - leftPadding - rightPadding;
    availableImageWidth = (availableImageWidth < 0) ? 0 : availableImageWidth;

    int availableImageHeight = printImage.getHeight() - topPadding - bottomPadding;
    availableImageHeight = (availableImageHeight < 0) ? 0 : availableImageHeight;

    Renderable renderer = printImage.getRenderable();

    if (renderer != null && availableImageWidth > 0 && availableImageHeight > 0) {
        if (renderer.getTypeValue() == RenderableTypeEnum.IMAGE) {
            // Image renderers are all asked for their image data at some point. 
            // Better to test and replace the renderer now, in case of lazy load error.
            renderer = RenderableUtil.getInstance(jasperReportsContext).getOnErrorRendererForImageData(renderer,
                    printImage.getOnErrorTypeValue());
        }
    } else {
        renderer = null;
    }

    if (renderer != null) {
        int xoffset = 0;
        int yoffset = 0;

        Chunk chunk = null;

        float scaledWidth = availableImageWidth;
        float scaledHeight = availableImageHeight;

        if (renderer.getTypeValue() == RenderableTypeEnum.IMAGE) {
            com.lowagie.text.Image image = null;

            float xalignFactor = getXAlignFactor(printImage);
            float yalignFactor = getYAlignFactor(printImage);

            switch (printImage.getScaleImageValue()) {
            case CLIP: {
                // Image load might fail, from given image data. 
                // Better to test and replace the renderer now, in case of lazy load error.
                renderer = RenderableUtil.getInstance(jasperReportsContext)
                        .getOnErrorRendererForDimension(renderer, printImage.getOnErrorTypeValue());
                if (renderer == null) {
                    break;
                }

                int normalWidth = availableImageWidth;
                int normalHeight = availableImageHeight;

                Dimension2D dimension = renderer.getDimension(jasperReportsContext);
                if (dimension != null) {
                    normalWidth = (int) dimension.getWidth();
                    normalHeight = (int) dimension.getHeight();
                }

                xoffset = (int) (xalignFactor * (availableImageWidth - normalWidth));
                yoffset = (int) (yalignFactor * (availableImageHeight - normalHeight));

                int minWidth = Math.min(normalWidth, availableImageWidth);
                int minHeight = Math.min(normalHeight, availableImageHeight);

                BufferedImage bi = new BufferedImage(minWidth, minHeight, BufferedImage.TYPE_INT_ARGB);

                Graphics2D g = bi.createGraphics();
                if (printImage.getModeValue() == ModeEnum.OPAQUE) {
                    g.setColor(printImage.getBackcolor());
                    g.fillRect(0, 0, minWidth, minHeight);
                }
                renderer.render(jasperReportsContext, g, new java.awt.Rectangle((xoffset > 0 ? 0 : xoffset),
                        (yoffset > 0 ? 0 : yoffset), normalWidth, normalHeight));
                g.dispose();

                xoffset = (xoffset < 0 ? 0 : xoffset);
                yoffset = (yoffset < 0 ? 0 : yoffset);

                //awtImage = bi.getSubimage(0, 0, minWidth, minHeight);

                //image = com.lowagie.text.Image.getInstance(awtImage, printImage.getBackcolor());
                image = com.lowagie.text.Image.getInstance(bi, null);

                break;
            }
            case FILL_FRAME: {
                if (printImage.isUsingCache() && loadedImagesMap.containsKey(renderer)) {
                    image = loadedImagesMap.get(renderer);
                } else {
                    try {
                        image = com.lowagie.text.Image.getInstance(renderer.getImageData(jasperReportsContext));
                        imageTesterPdfContentByte.addImage(image, 10, 0, 0, 10, 0, 0);
                    } catch (Exception e) {
                        JRImageRenderer tmpRenderer = JRImageRenderer.getOnErrorRendererForImage(
                                jasperReportsContext,
                                JRImageRenderer.getInstance(renderer.getImageData(jasperReportsContext)),
                                printImage.getOnErrorTypeValue());
                        if (tmpRenderer == null) {
                            break;
                        }
                        java.awt.Image awtImage = tmpRenderer.getImage(jasperReportsContext);
                        image = com.lowagie.text.Image.getInstance(awtImage, null);
                    }

                    if (printImage.isUsingCache()) {
                        loadedImagesMap.put(renderer, image);
                    }
                }

                image.scaleAbsolute(availableImageWidth, availableImageHeight);
                break;
            }
            case RETAIN_SHAPE:
            default: {
                if (printImage.isUsingCache() && loadedImagesMap.containsKey(renderer)) {
                    image = loadedImagesMap.get(renderer);
                } else {
                    try {
                        image = com.lowagie.text.Image.getInstance(renderer.getImageData(jasperReportsContext));
                        imageTesterPdfContentByte.addImage(image, 10, 0, 0, 10, 0, 0);
                    } catch (Exception e) {
                        JRImageRenderer tmpRenderer = JRImageRenderer.getOnErrorRendererForImage(
                                jasperReportsContext,
                                JRImageRenderer.getInstance(renderer.getImageData(jasperReportsContext)),
                                printImage.getOnErrorTypeValue());
                        if (tmpRenderer == null) {
                            break;
                        }
                        java.awt.Image awtImage = tmpRenderer.getImage(jasperReportsContext);
                        image = com.lowagie.text.Image.getInstance(awtImage, null);
                    }

                    if (printImage.isUsingCache()) {
                        loadedImagesMap.put(renderer, image);
                    }
                }

                image.scaleToFit(availableImageWidth, availableImageHeight);

                xoffset = (int) (xalignFactor * (availableImageWidth - image.plainWidth()));
                yoffset = (int) (yalignFactor * (availableImageHeight - image.plainHeight()));

                xoffset = (xoffset < 0 ? 0 : xoffset);
                yoffset = (yoffset < 0 ? 0 : yoffset);

                break;
            }
            }

            if (image != null) {
                chunk = new Chunk(image, 0, 0);

                scaledWidth = image.scaledWidth();
                scaledHeight = image.scaledHeight();
            }
        } else {
            double normalWidth = availableImageWidth;
            double normalHeight = availableImageHeight;

            double displayWidth = availableImageWidth;
            double displayHeight = availableImageHeight;

            double ratioX = 1f;
            double ratioY = 1f;

            Rectangle2D clip = null;

            Dimension2D dimension = renderer.getDimension(jasperReportsContext);
            if (dimension != null) {
                normalWidth = dimension.getWidth();
                normalHeight = dimension.getHeight();
                displayWidth = normalWidth;
                displayHeight = normalHeight;

                float xalignFactor = getXAlignFactor(printImage);
                float yalignFactor = getYAlignFactor(printImage);

                switch (printImage.getScaleImageValue()) {
                case CLIP: {
                    xoffset = (int) (xalignFactor * (availableImageWidth - normalWidth));
                    yoffset = (int) (yalignFactor * (availableImageHeight - normalHeight));
                    clip = new Rectangle2D.Double(-xoffset, -yoffset, availableImageWidth,
                            availableImageHeight);
                    break;
                }
                case FILL_FRAME: {
                    ratioX = availableImageWidth / normalWidth;
                    ratioY = availableImageHeight / normalHeight;
                    normalWidth *= ratioX;
                    normalHeight *= ratioY;
                    xoffset = 0;
                    yoffset = 0;
                    break;
                }
                case RETAIN_SHAPE:
                default: {
                    ratioX = availableImageWidth / normalWidth;
                    ratioY = availableImageHeight / normalHeight;
                    ratioX = ratioX < ratioY ? ratioX : ratioY;
                    ratioY = ratioX;
                    normalWidth *= ratioX;
                    normalHeight *= ratioY;
                    xoffset = (int) (xalignFactor * (availableImageWidth - normalWidth));
                    yoffset = (int) (yalignFactor * (availableImageHeight - normalHeight));
                    break;
                }
                }
            }

            PdfTemplate template = pdfContentByte.createTemplate((float) displayWidth, (float) displayHeight);

            Graphics2D g = forceSvgShapes
                    ? template.createGraphicsShapes((float) displayWidth, (float) displayHeight)
                    : template.createGraphics(availableImageWidth, availableImageHeight, new LocalFontMapper());

            if (clip != null) {
                g.setClip(clip);
            }

            if (printImage.getModeValue() == ModeEnum.OPAQUE) {
                g.setColor(printImage.getBackcolor());
                g.fillRect(0, 0, (int) displayWidth, (int) displayHeight);
            }

            Rectangle2D rectangle = new Rectangle2D.Double(0, 0, displayWidth, displayHeight);

            renderer.render(jasperReportsContext, g, rectangle);
            g.dispose();

            pdfContentByte.saveState();
            pdfContentByte.addTemplate(template, (float) ratioX, 0f, 0f, (float) ratioY,
                    printImage.getX() + getOffsetX() + xoffset, jasperPrint.getPageHeight() - printImage.getY()
                            - getOffsetY() - (int) normalHeight - yoffset);
            pdfContentByte.restoreState();

            Image image = getPxImage();
            image.scaleAbsolute(availableImageWidth, availableImageHeight);
            chunk = new Chunk(image, 0, 0);
        }

        /*
        image.setAbsolutePosition(
           printImage.getX() + offsetX + borderOffset,
           jasperPrint.getPageHeight() - printImage.getY() - offsetY - image.scaledHeight() - borderOffset
           );
                
        pdfContentByte.addImage(image);
        */

        if (chunk != null) {
            setAnchor(chunk, printImage, printImage);
            setHyperlinkInfo(chunk, printImage);

            //tagHelper.startImage(printImage);

            ColumnText colText = new ColumnText(pdfContentByte);
            int upperY = jasperPrint.getPageHeight() - printImage.getY() - topPadding - getOffsetY() - yoffset;
            int lowerX = printImage.getX() + leftPadding + getOffsetX() + xoffset;
            colText.setSimpleColumn(new Phrase(chunk), lowerX, upperY - scaledHeight, lowerX + scaledWidth,
                    upperY, scaledHeight, Element.ALIGN_LEFT);

            colText.go();

            //tagHelper.endImage();
        }
    }

    if (printImage.getLineBox().getTopPen().getLineWidth().floatValue() <= 0f
            && printImage.getLineBox().getLeftPen().getLineWidth().floatValue() <= 0f
            && printImage.getLineBox().getBottomPen().getLineWidth().floatValue() <= 0f
            && printImage.getLineBox().getRightPen().getLineWidth().floatValue() <= 0f) {
        if (printImage.getLinePen().getLineWidth().floatValue() > 0f) {
            exportPen(printImage.getLinePen(), printImage);
        }
    } else {
        /*   */
        exportBox(printImage.getLineBox(), printImage);
    }
}

From source file:com.ikon.util.DocConverter.java

License:Open Source License

/**
 * TIFF to PDF conversion//from w w  w  .j  a  v a2s  . c om
 */
public void tiff2pdf(File input, File output) throws ConversionException {
    RandomAccessFileOrArray ra = null;
    Document doc = null;

    try {
        // Open PDF
        doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
        PdfContentByte cb = writer.getDirectContent();
        doc.open();
        //int pages = 0;

        // Open TIFF
        ra = new RandomAccessFileOrArray(input.getPath());
        int comps = TiffImage.getNumberOfPages(ra);

        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);

            if (img != null) {
                log.debug("tiff2pdf - page {}", c + 1);

                if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                    img.scaleToFit(500, 700);
                }

                img.setAbsolutePosition(20, 20);
                //doc.add(new Paragraph("page " + (c + 1)));
                cb.addImage(img);
                doc.newPage();
                //++pages;
            }
        }
    } catch (FileNotFoundException e) {
        throw new ConversionException("File not found: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Document exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ConversionException("IO exception: " + e.getMessage(), e);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        if (doc != null) {
            doc.close();
        }
    }
}

From source file:com.kahlon.guard.controller.DocumentManager.java

/**
 *
 * @param document/*  w  w w .  j  ava 2 s .  c  om*/
 */
public void preProcessPDF(Object document) {
    try {

        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);

        Document pdf = (Document) document;
        pdf.setPageSize(PageSize.A4);
        pdf.setMargins(5f, 5f, 10f, 5f);

        // headers and footers must be added before the document is opened
        HeaderFooter footer = new HeaderFooter(new Phrase("page: ", new Font(bf_courier)), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);
        pdf.setFooter(footer);

        //            HeaderFooter header = new HeaderFooter(
        //                        new Phrase("This is a header without a page number", new Font(bf_courier)), false);
        //            header.setAlignment(Element.ALIGN_CENTER);
        //            pdf.setHeader(header);

        pdf.open();

        String logoPath = "/resources/image/logo.png";
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String logo = servletContext.getRealPath(logoPath);

        pdf.add(Image.getInstance(logo));

        Person person = context.getSelectedPerson().getDisplayPerson();

        String name = FacesMessageUtil.getMessage("person.name") + " : " + person.getName();
        String age = FacesMessageUtil.getMessage("person.age") + " : " + Integer.toString(person.getAge());
        String gender = FacesMessageUtil.getMessage("person.gender") + " : "
                + person.getGender().getDescription();
        String race = FacesMessageUtil.getMessage("person.ethnicity") + " : "
                + person.getEthnicity().getDescription();

        Person rootPerson = person.getRootPerson();
        PersonImage imgp = imageService.getLastestPersonImage(rootPerson.getId());
        Image imgb = Image.getInstance(imgp.getContent());
        imgb.scaleToFit(100, 120);

        PdfPTable headerTable = new PdfPTable(2);

        PdfPTable personTable = new PdfPTable(1);
        personTable.setWidthPercentage(100);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase(name));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(age));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(gender));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(race));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        BarcodePDF417 pdf417 = new BarcodePDF417();
        pdf417.setText(Integer.toString(person.getId()));
        Image img = pdf417.getImage();
        img.scalePercent(150, 60 * pdf417.getYHeight());
        cell = new PdfPCell(img);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(15);
        personTable.addCell(cell);

        cell.addElement(personTable);
        headerTable.addCell(cell);

        cell = new PdfPCell(imgb);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(Rectangle.NO_BORDER);
        headerTable.addCell(cell);

        headerTable.setSpacingAfter(15);
        pdf.add(headerTable);

        LineSeparator lineSeparator = new LineSeparator();
        lineSeparator.setPercentage(82);
        pdf.add(lineSeparator);
        Paragraph space = new Paragraph();
        space.add("");
        space.setSpacingAfter(15);
        pdf.add(space);

    } catch (IOException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (BadElementException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (DocumentException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (Exception e) {
        logger.log(Level.INFO, e.getMessage());
    }

}

From source file:com.openkm.util.DocConverter.java

License:Open Source License

/**
 * TIFF to PDF conversion//from   ww  w. j  a v  a 2s  .c o m
 */
public void tiff2pdf(File input, File output) throws ConversionException {
    RandomAccessFileOrArray ra = null;
    Document doc = null;

    try {
        // Open PDF
        doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
        PdfContentByte cb = writer.getDirectContent();
        doc.open();
        // int pages = 0;

        // Open TIFF
        ra = new RandomAccessFileOrArray(input.getPath());
        int comps = TiffImage.getNumberOfPages(ra);

        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);

            if (img != null) {
                log.debug("tiff2pdf - page {}", c + 1);

                if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                    img.scaleToFit(500, 700);
                }

                img.setAbsolutePosition(20, 20);
                // doc.add(new Paragraph("page " + (c + 1)));
                cb.addImage(img);
                doc.newPage();
                // ++pages;
            }
        }
    } catch (FileNotFoundException e) {
        throw new ConversionException("File not found: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Document exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ConversionException("IO exception: " + e.getMessage(), e);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        if (doc != null) {
            doc.close();
        }
    }
}

From source file:com.orange.atk.compModel.PDFGenerator.java

License:Apache License

/**
 * @see com.orange.atk.results.logger.documentGenerator.DocumentGenerator#dumpInStream(boolean, interpreter.logger.DocumentLogger)
 *///www . j av  a  2  s  .c om

public void dumpInStream(boolean isParseErrorHappened, /*DocumentLogger dl,*/ org.w3c.dom.Document xmlDoc,
        Model model3) {
    long endTime = new Date().getTime();
    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = null;

    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to the outputStream
    try {
        writer = PdfWriter.getInstance(document, outputStream);
    } catch (DocumentException e1) {
        e1.printStackTrace();
        return;
    }
    writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
    // step 3: we open the document
    document.open();
    document.addTitle("REPORT");
    document.addCreationDate();

    HeaderFooter headerPage = new HeaderFooter(new Phrase("ScreenShot report"), false);
    HeaderFooter footerPage = new HeaderFooter(new Phrase(" - "), new Phrase(" - "));
    headerPage.setAlignment(Element.ALIGN_CENTER);
    footerPage.setAlignment(Element.ALIGN_CENTER);
    document.setHeader(headerPage);
    document.setFooter(footerPage);

    // Chapter 1 : Summary
    // Section 1 : Informations

    Chunk c = new Chunk("Summary");
    c.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c.setFont(FONT_PAR_TITLE);

    Paragraph title1 = new Paragraph(c);
    title1.setAlignment("CENTER");
    title1.setLeading(20);
    Chapter chapter1 = new Chapter(title1, 1);
    chapter1.setNumberDepth(0);

    Paragraph title11 = new Paragraph("Informations");
    Section section1 = chapter1.addSection(title11);
    Paragraph pSum = new Paragraph();
    pSum.add("Author : " + author);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Group : " + group);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Script : " + script);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Reference directory: " + model3.getRefDirectory());
    pSum.add(Chunk.NEWLINE);
    pSum.add("Test directory: " + model3.getTestDirectory());
    pSum.add(Chunk.NEWLINE);
    SimpleDateFormat formatter = new SimpleDateFormat("MMMMM dd, yyyy - hh:mm aaa");
    String dateString = formatter.format(endTime);
    pSum.add("Date : " + dateString);
    pSum.add(Chunk.NEWLINE);
    pSum.add(Chunk.NEWLINE);
    if (model3.getNbFail() > 0) {
        pSum.add(model3.getNbFail() + "/" + model3.getNbImages() + " images didn't succeed the test.");
    } else {
        pSum.add("All images (" + model3.getNbImages() + ") have succeed this comparaison.");
    }
    pSum.add(Chunk.NEWLINE);
    pSum.setIndentationLeft(20);
    section1.add(pSum);
    section1.add(new Paragraph(Chunk.NEXTPAGE));

    try {
        document.add(chapter1);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    if (isParseErrorHappened) {
        document.close();
        return;
    }

    // Add generated pictures
    Chunk c3 = new Chunk("ScreenShots");
    c3.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c3.setFont(FONT_PAR_TITLE);
    Paragraph p3 = new Paragraph(c3);
    p3.setAlignment("CENTER");
    p3.setLeading(20);
    Chapter chapter3 = new Chapter(p3, 1);
    chapter3.setNumberDepth(0);

    NodeList imgs = xmlDoc.getElementsByTagName("img");
    for (int i = 0; i < imgs.getLength(); i++) {
        org.w3c.dom.Element eImg = (org.w3c.dom.Element) imgs.item(i);
        if (eImg.getElementsByTagName("Pass").item(0).getTextContent().equals(Model.FAIL)) {

            org.w3c.dom.Element eRef = (org.w3c.dom.Element) eImg.getElementsByTagName("Ref").item(0);
            org.w3c.dom.Element eTest = (org.w3c.dom.Element) eImg.getElementsByTagName("Test").item(0);
            Paragraph pScreen = new Paragraph(eTest.getAttributes().getNamedItem("name").getNodeValue() + " "
                    + eImg.getElementsByTagName("Pass").item(0).getTextContent());
            Section section31 = chapter3.addSection(pScreen);
            PdfPTable scTable = null;
            scTable = new PdfPTable(2);
            scTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            scTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            scTable.getDefaultCell().setPadding(5);
            if (new File(eRef.getTextContent()).exists()) {
                Image refImg;
                try {
                    refImg = Image.getInstance(eRef.getTextContent());
                    refImg.scaleToFit(310, 260);
                    refImg.setAlignment(Element.ALIGN_BASELINE);
                    scTable.addCell(refImg);
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (DOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (new File(eTest.getTextContent()).exists()) {
                Image testImg;
                try {
                    BufferedImage bi = ImageIO.read(new File(eTest.getTextContent()));
                    Graphics2D g2d = (Graphics2D) bi.getGraphics();
                    g2d.setStroke(new BasicStroke(1.5f));
                    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));

                    Boolean2D dif = model3.getCouplesComparaison().get(i).getDifWithMask();
                    //               if (squarable){
                    g2d.setColor(Color.red);
                    int w = bi.getWidth();
                    int h = bi.getHeight();
                    //TODO: Gurvan, Maybe we need to have the list of masks in the report?
                    Mask mask = model3.getCouplesComparaison().get(i).getMaskSum();
                    //g2d.drawRect(0, 0, mask.getWidth()*2*sampleWidth, mask.getHeight()*2*sampleHeight);
                    for (int x = 0; x < mask.getWidth(); x++) {

                        for (int y = 0; y < mask.getHeight(); y++) {

                            if (mask.getCell(x, y)) {
                                g2d.setColor(Color.blue);
                                ////Logger.getLogger(this.getClass() ).debug("grise");
                                g2d.fillRect(x * 2 * Mask.getCELL_HALF_SIZE(), y * 2 * Mask.getCELL_HALF_SIZE(),
                                        2 * Mask.getCELL_HALF_SIZE(), 2 * Mask.getCELL_HALF_SIZE());
                            }

                            if (!dif.get(x, y)) {
                                g2d.setColor(Color.green);
                                g2d.fillRect(x * 2 * Mask.getCELL_HALF_SIZE(), y * 2 * Mask.getCELL_HALF_SIZE(),
                                        2 * Mask.getCELL_HALF_SIZE(), 2 * Mask.getCELL_HALF_SIZE());
                            }
                        }
                    }
                    testImg = Image.getInstance(bi, null);
                    testImg.scaleToFit(310, 260);
                    testImg.setAlignment(Element.ALIGN_BASELINE);
                    scTable.addCell(testImg);
                    section31.add(Chunk.NEWLINE);
                    section31.add(scTable);
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (DOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            section31.add(new Paragraph("Reference screenshot description : "
                    + eImg.getElementsByTagName("RefDescription").item(0).getTextContent()));
            section31.add(Chunk.NEWLINE);

            section31
                    .add(new Paragraph("Mask : " + eImg.getElementsByTagName("Mask").item(0).getTextContent()));
            section31.add(Chunk.NEWLINE);

            section31.add(new Paragraph(
                    "Comment : " + eImg.getElementsByTagName("Comment").item(0).getTextContent()));
            section31.add(new Paragraph(Chunk.NEXTPAGE));

        }
    }
    try {
        document.add(chapter3);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    // step 5: we close the document
    document.close();
}

From source file:com.qcadoo.report.internal.PdfHelperImpl.java

License:Open Source License

@Override
public void addImage(final Document document, final String fileName) {
    try {//from w w  w .  j a  va 2  s.c om
        Image img = Image.getInstance(fileName);
        if (img.getWidth() > 515 || img.getHeight() > 370) {
            img.scaleToFit(515, 370);
        }

        document.add(img);
        document.add(Chunk.NEWLINE);
    } catch (BadElementException e) {
        LOG.error(e.getMessage(), e);
    } catch (MalformedURLException e) {
        LOG.error(e.getMessage(), e);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    } catch (DocumentException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:com.slamd.report.PDFReportGenerator.java

License:Open Source License

/**
 * Writes information about the provided job to the document.
 *
 * @param  document  The document to which the job information should be
 *                   written.//w ww. jav  a  2s.  c o  m
 * @param  job       The job to include in the document.
 *
 * @throws  DocumentException  If a problem occurs while writing the contents.
 */
private void writeJob(Document document, Job job) throws DocumentException {
    Anchor anchor = new Anchor("Job " + job.getJobID(),
            FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD, Color.BLACK));
    anchor.setName(job.getJobID());
    Paragraph p = new Paragraph(anchor);
    document.add(p);

    // Write the general information to the document.
    p = new Paragraph("General Information",
            FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
    document.add(p);

    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.setWidths(new int[] { 30, 70 });
    writeTableCell(table, "Job ID");
    writeTableCell(table, job.getJobID());

    String optimizingJobID = job.getOptimizingJobID();
    if ((optimizingJobID != null) && (optimizingJobID.length() > 0)) {
        writeTableCell(table, "Optimizing Job ID");
        writeTableCell(table, optimizingJobID);
    }

    String descriptionStr = job.getJobDescription();
    if ((descriptionStr == null) || (descriptionStr.length() == 0)) {
        descriptionStr = "(Not Specified)";
    }
    writeTableCell(table, "Job Description");
    writeTableCell(table, descriptionStr);

    writeTableCell(table, "Job Type");
    writeTableCell(table, job.getJobClassName());

    writeTableCell(table, "Job Class");
    writeTableCell(table, job.getJobClass().getClass().getName());

    writeTableCell(table, "Job State");
    writeTableCell(table, job.getJobStateString());
    document.add(table);

    // Write the schedule config if appropriate.
    if (includeScheduleConfig) {
        document.add(new Paragraph(" "));
        p = new Paragraph("Schedule Information",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Date startTime = job.getStartTime();
        String startStr;
        if (startTime == null) {
            startStr = "(Not Available)";
        } else {
            startStr = dateFormat.format(startTime);
        }
        writeTableCell(table, "Scheduled Start Time");
        writeTableCell(table, startStr);

        Date stopTime = job.getStopTime();
        String stopStr;
        if (stopTime == null) {
            stopStr = "(Not Specified)";
        } else {
            stopStr = dateFormat.format(stopTime);
        }
        writeTableCell(table, "Scheduled Stop Time");
        writeTableCell(table, stopStr);

        int duration = job.getDuration();
        String durationStr;
        if (duration > 0) {
            durationStr = duration + " seconds";
        } else {
            durationStr = "(Not Specified)";
        }
        writeTableCell(table, "Scheduled Duration");
        writeTableCell(table, durationStr);

        writeTableCell(table, "Number of Clients");
        writeTableCell(table, String.valueOf(job.getNumberOfClients()));

        String[] requestedClients = job.getRequestedClients();
        if ((requestedClients != null) && (requestedClients.length > 0)) {
            PdfPTable clientTable = new PdfPTable(1);
            for (int i = 0; i < requestedClients.length; i++) {
                PdfPCell clientCell = new PdfPCell(new Phrase(requestedClients[i]));
                clientCell.setBorder(0);
                clientTable.addCell(clientCell);
            }

            writeTableCell(table, "Requested Clients");
            table.addCell(clientTable);
        }

        String[] monitorClients = job.getResourceMonitorClients();
        if ((monitorClients != null) && (monitorClients.length > 0)) {
            PdfPTable clientTable = new PdfPTable(1);
            for (int i = 0; i < monitorClients.length; i++) {
                PdfPCell clientCell = new PdfPCell(new Phrase(monitorClients[i]));
                clientCell.setBorder(0);
                clientTable.addCell(clientCell);
            }

            writeTableCell(table, "Resource Monitor Clients");
            table.addCell(clientTable);
        }

        writeTableCell(table, "Threads per Client");
        writeTableCell(table, String.valueOf(job.getThreadsPerClient()));

        writeTableCell(table, "Thread Startup Delay");
        writeTableCell(table, job.getThreadStartupDelay() + " milliseconds");

        writeTableCell(table, "Statistics Collection Interval");
        writeTableCell(table, job.getCollectionInterval() + " seconds");

        document.add(table);
    }

    // Write the job-specific parameter information if appropriate.
    if (includeJobConfig) {
        document.add(new Paragraph(" "));
        p = new Paragraph("Parameter Information",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Parameter[] params = job.getParameterList().getParameters();
        for (int i = 0; i < params.length; i++) {
            writeTableCell(table, params[i].getDisplayName());
            writeTableCell(table, params[i].getDisplayValue());
        }

        document.add(table);
    }

    // Write the statistical data if appropriate.
    if (includeStats && job.hasStats()) {
        document.add(new Paragraph(" "));
        p = new Paragraph("General Execution Data",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Date actualStartTime = job.getActualStartTime();
        String startStr;
        if (actualStartTime == null) {
            startStr = "(Not Available)";
        } else {
            startStr = dateFormat.format(actualStartTime);
        }
        writeTableCell(table, "Actual Start Time");
        writeTableCell(table, startStr);

        Date actualStopTime = job.getActualStopTime();
        String stopStr;
        if (actualStopTime == null) {
            stopStr = "(Not Available)";
        } else {
            stopStr = dateFormat.format(actualStopTime);
        }
        writeTableCell(table, "Actual Stop Time");
        writeTableCell(table, stopStr);

        int actualDuration = job.getActualDuration();
        String durationStr;
        if (actualDuration > 0) {
            durationStr = actualDuration + " seconds";
        } else {
            durationStr = "(Not Available)";
        }
        writeTableCell(table, "Actual Duration");
        writeTableCell(table, durationStr);

        String[] clients = job.getStatTrackerClientIDs();
        if ((clients != null) && (clients.length > 0)) {
            PdfPTable clientTable = new PdfPTable(1);
            for (int i = 0; i < clients.length; i++) {
                PdfPCell clientCell = new PdfPCell(new Phrase(clients[i]));
                clientCell.setBorder(0);
                clientTable.addCell(clientCell);
            }

            writeTableCell(table, "Clients Used");
            table.addCell(clientTable);
        }

        document.add(table);

        String[] trackerNames = job.getStatTrackerNames();
        for (int i = 0; i < trackerNames.length; i++) {
            StatTracker[] trackers = job.getStatTrackers(trackerNames[i]);
            if ((trackers != null) && (trackers.length > 0)) {
                document.newPage();
                StatTracker tracker = trackers[0].newInstance();
                tracker.aggregate(trackers);

                document.add(new Paragraph(" "));
                document.add(new Paragraph(trackerNames[i],
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));

                String[] summaryNames = tracker.getSummaryLabels();
                String[] summaryValues = tracker.getSummaryData();
                table = new PdfPTable(2);
                table.setWidthPercentage(100);
                table.setWidths(new int[] { 50, 50 });
                for (int j = 0; j < summaryNames.length; j++) {
                    writeTableCell(table, summaryNames[j]);
                    writeTableCell(table, summaryValues[j]);
                }
                document.add(table);

                if (includeGraphs) {
                    try {
                        ParameterList params = tracker.getGraphParameterStubs(job);
                        BufferedImage graphImage = tracker.createGraph(job, Constants.DEFAULT_GRAPH_WIDTH,
                                Constants.DEFAULT_GRAPH_HEIGHT, params);
                        Image image = Image.getInstance(imageToByteArray(graphImage));
                        image.scaleToFit(inchesToPoints(5.5), inchesToPoints(4.5));
                        document.add(image);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }

    // Write the resource monitor data if appropriate.
    if (includeMonitorStats && job.hasResourceStats()) {
        String[] trackerNames = job.getResourceStatTrackerNames();
        for (int i = 0; i < trackerNames.length; i++) {
            StatTracker[] trackers = job.getResourceStatTrackers(trackerNames[i]);
            if ((trackers != null) && (trackers.length > 0)) {
                document.newPage();
                StatTracker tracker = trackers[0].newInstance();
                tracker.aggregate(trackers);

                document.add(new Paragraph(" "));
                document.add(new Paragraph(trackerNames[i],
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));

                String[] summaryNames = tracker.getSummaryLabels();
                String[] summaryValues = tracker.getSummaryData();
                table = new PdfPTable(2);
                table.setWidthPercentage(100);
                table.setWidths(new int[] { 50, 50 });
                for (int j = 0; j < summaryNames.length; j++) {
                    writeTableCell(table, summaryNames[j]);
                    writeTableCell(table, summaryValues[j]);
                }
                document.add(table);

                if (includeGraphs) {
                    try {
                        ParameterList params = tracker.getGraphParameterStubs(job);
                        BufferedImage graphImage = tracker.createMonitorGraph(job,
                                Constants.DEFAULT_GRAPH_WIDTH, Constants.DEFAULT_MONITOR_GRAPH_HEIGHT, params);
                        Image image = Image.getInstance(imageToByteArray(graphImage));
                        image.scaleToFit(inchesToPoints(5.5), inchesToPoints(4.5));
                        document.add(image);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}