Example usage for com.lowagie.text Chunk Chunk

List of usage examples for com.lowagie.text Chunk Chunk

Introduction

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

Prototype

public Chunk(DrawInterface separator, float tabPosition, boolean newline) 

Source Link

Document

Creates a tab Chunk.

Usage

From source file:airportpainter.util.AirportPainter.java

License:Open Source License

private void createSheetsRunways(Airport airport, Document document) {
    notifyAction("createSheetsRunways");

    PdfPTable table = new PdfPTable(6);

    // titles/*from w w w.  java  2 s. c om*/
    com.lowagie.text.Font fontTitle = new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 8,
            com.lowagie.text.Font.NORMAL);
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidth);
        Paragraph p = new Paragraph("RWY N" + degrees, fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("Dimension (ft) - Surface", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("TORA (ft)", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("LDA (ft)", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("Strength", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);

    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidth);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("Lights", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }

    // data
    com.lowagie.text.Font fontData = new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 10,
            com.lowagie.text.Font.NORMAL);
    int rc = 0;
    for (final Runway runway : airport.getRunways()) {
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidth);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            Paragraph p = new Paragraph(runway.getNumber() + "\r\n" + runway.getOppositeNumber(), fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);
        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            String runwayLength = new Integer(runway.getLength()).toString() + " x "
                    + new Integer(runway.getWidth()).toString() + " " + runway.getSurfaceName();
            Paragraph p = new Paragraph(runwayLength, fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);

        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            Paragraph p = new Paragraph(runway.getLength() + "\r\n" + runway.getLength(), fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);
        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            Paragraph p = new Paragraph((runway.getLength() - runway.getDisplacement()) + "\r\n"
                    + (runway.getLength() - runway.getDisplacementOpposite()), fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);
        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            Paragraph p = new Paragraph("to do...", fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);
        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            cell.setBorderWidthRight(borderWidth);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            Paragraph p = new Paragraph();
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            try {
                if (runway.hasALSF_I(true) || runway.hasALSF_I(false) || runway.hasALSF_II(true)
                        || runway.hasALSF_II(false) || runway.hasPapi(true) || runway.hasPapi(false)
                        || runway.hasSALSF(true) || runway.hasSALSF(false) || runway.hasSSLP(true)
                        || runway.hasSSLP(false) || runway.hasVasi(true) || runway.hasVasi(false)) {
                    p.add(new Chunk(Image.getInstance(getClass().getResource(Main.imgFolder + "light.png")), 0,
                            0));
                } else {
                    p.add(new Chunk("--", fontData));
                }
            } catch (BadElementException ex) {
                Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
            }
            cell.addElement(p);
            table.addCell(cell);
        }

        rc++;

    }

    float[] widths2 = { 1f, 2f, 1f, 1f, 2f, 1f };
    try {
        table.setWidths(widths2);
    } catch (DocumentException ex) {
        Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
    }

    table.setWidthPercentage(100);
    try {
        document.add(table);
    } catch (DocumentException ex) {
        Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:ambit.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public void headerTable(Document pdfdoc, org.w3c.dom.Document xmldoc) {
    try {//from   ww  w  . ja  v  a  2 s .c  om
        int header_font_size = 10;
        Image png_left = Image
                .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
        Image png_right = Image
                .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
        png_left.setAlignment(Image.LEFT);
        png_right.setAlignment(Image.RIGHT);
        png_left.scalePercent(60);
        png_right.scalePercent(60);
        //png.scaleAbsolute(76, 67);
        //png.setAlignment(Image.MIDDLE);

        PdfPCell cell;

        float[] widths = { 1f, 5f, 1f };
        float[] widths1 = { 1f };
        PdfPTable table = new PdfPTable(widths);
        PdfPTable table1 = new PdfPTable(widths1);

        table.setWidthPercentage(100);

        cell = new PdfPCell();
        cell.setMinimumHeight(70);
        cell.addElement(new Chunk(png_left, +14, -40));
        table.addCell(cell);

        String Text = "";
        try {

            Text = findNodeValue(xml_QMRF_number, xmldoc);
            Chunk ident_title = new Chunk("QMRF identifier (JRC Inventory):");
            Chunk ident_text = new Chunk(Text);

            Font bi_font = new Font(baseFont, header_font_size, Font.BOLDITALIC);
            Font i_font = new Font(baseFont, header_font_size, Font.ITALIC);

            ident_title.setFont(bi_font);
            ident_text.setFont(i_font);
            Paragraph p = new Paragraph();
            p.add(ident_title);
            p.add(ident_text);
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            ident_title = new Chunk("QMRF Title:");
            Phrase textPhrase = new Phrase();
            createNodePhrase("QSAR_title", xmldoc, textPhrase, i_font);
            ident_title.setFont(bi_font);

            p = new Paragraph();
            p.add(ident_title);
            p.add(textPhrase);
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            java.util.Date now = new java.util.Date();
            java.text.DateFormat df = java.text.DateFormat.getDateInstance();
            String date = df.format(now);
            ident_title = new Chunk("Printing Date:");
            ident_text = new Chunk(date);
            ident_title.setFont(bi_font);
            ident_text.setFont(i_font);
            p = new Paragraph();
            p.add(ident_title);
            p.add(ident_text);

            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            p = new Paragraph("");
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);
            cell = new PdfPCell(table1);
            cell.setPadding(0f);
            table.addCell(cell);

        } catch (Throwable x) {
            x.printStackTrace();

        }

        //table.addCell(new PdfPCell(png, true));
        cell.addElement(new Chunk(png_right, +14, -40));
        table.addCell(cell);
        pdfdoc.add(table);
        pdfdoc.add(new Paragraph(16));

    } catch (Exception x) {
        x.printStackTrace();
    }
}

From source file:ambit2.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public void headerTable(Document pdfdoc, org.w3c.dom.Document xmldoc) {
    try {//  w ww. jav a2s .  c o m
        int header_font_size = 10;
        Image png_left = Image
                .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
        Image png_right = Image
                .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
        png_left.setAlignment(Image.LEFT);
        png_right.setAlignment(Image.RIGHT);
        png_left.scalePercent(60);
        png_right.scalePercent(60);
        //png.scaleAbsolute(76, 67);
        //png.setAlignment(Image.MIDDLE);

        PdfPCell cell;

        float[] widths = { 1f, 5f, 1f };
        float[] widths1 = { 1f };
        PdfPTable table = new PdfPTable(widths);
        PdfPTable table1 = new PdfPTable(widths1);

        table.setWidthPercentage(100);

        cell = new PdfPCell();
        cell.setMinimumHeight(70);
        cell.addElement(new Chunk(png_left, +14, -40));
        table.addCell(cell);

        String Text = "";
        try {

            Text = findNodeValue(xml_QMRF_number, xmldoc);
            Chunk ident_title = new Chunk("QMRF identifier (ECB Inventory):");
            Chunk ident_text = new Chunk(Text);

            Font bi_font = new Font(baseFont, header_font_size, Font.BOLDITALIC);
            Font i_font = new Font(baseFont, header_font_size, Font.ITALIC);

            ident_title.setFont(bi_font);
            ident_text.setFont(i_font);
            Paragraph p = new Paragraph();
            p.add(ident_title);
            p.add(ident_text);
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            ident_title = new Chunk("QMRF Title:");
            Phrase textPhrase = new Phrase();
            createNodePhrase("QSAR_title", xmldoc, textPhrase, i_font);
            ident_title.setFont(bi_font);

            p = new Paragraph();
            p.add(ident_title);
            p.add(textPhrase);
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            java.util.Date now = new java.util.Date();
            java.text.DateFormat df = java.text.DateFormat.getDateInstance();
            String date = df.format(now);
            ident_title = new Chunk("Printing Date:");
            ident_text = new Chunk(date);
            ident_title.setFont(bi_font);
            ident_text.setFont(i_font);
            p = new Paragraph();
            p.add(ident_title);
            p.add(ident_text);

            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            p = new Paragraph("");
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);
            cell = new PdfPCell(table1);
            cell.setPadding(0f);
            table.addCell(cell);

        } catch (Throwable x) {
            x.printStackTrace();

        }

        //table.addCell(new PdfPCell(png, true));
        cell.addElement(new Chunk(png_right, +14, -40));
        table.addCell(cell);
        pdfdoc.add(table);
        pdfdoc.add(new Paragraph(16));

    } catch (Exception x) {
        x.printStackTrace();
    }
}

From source file:biblivre3.administration.reports.AssetHoldingFullReport.java

License:Open Source License

@Override
protected void generateReportBody(Document document, BaseReportDto reportData) throws Exception {
    AssetHoldingDto dto = (AssetHoldingDto) reportData;
    String title = "";
    if (this.topographic) {
        title = this.getText("REPORTS_TOPOGRAPHIC_TITLE");
    } else {//from   w  w w .ja  va2s.c o m
        title = this.getText("REPORTS_ASSET_HOLDING_TITLE");
    }
    Paragraph p1 = new Paragraph(title);
    p1.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(p1);
    document.add(new Phrase("\n"));
    PdfPTable table = new PdfPTable(20);
    table.setWidthPercentage(100f);
    createHeader(table);
    PdfPCell cell;
    List<String[]> dataList = dto.getData();
    Collections.sort(dataList, this);
    for (String[] data : dataList) {
        PdfContentByte cb = getWriter().getDirectContent();

        String holdingSerial = StringUtils.leftPad(data[0], 10, "0");
        Barcode39 code39 = new Barcode39();
        code39.setExtended(true);
        code39.setCode(holdingSerial);
        code39.setStartStopText(false);

        Image image39 = code39.createImageWithBarcode(cb, null, null);
        image39.scalePercent(100f);
        cell = new PdfPCell(new Paragraph(new Phrase(new Chunk(image39, 0, 0))));
        cell.setColspan(6);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(this.getSmallFontChunk(data[1])));
        cell.setColspan(3);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);

        Paragraph para = new Paragraph();
        para.add(new Phrase(this.getSmallFontChunk(data[2] + "\n")));
        para.add(new Phrase(this.getSmallFontChunk(data[3] + "\n")));

        if (StringUtils.isNotBlank(data[4])) {
            para.add(new Phrase(this.getBoldChunk(this.getText("REPORTS_LOCATION") + ": ")));
            para.add(new Phrase(this.getSmallFontChunk(data[4] + " ")));
        }

        if (StringUtils.isNotBlank(data[5])) {
            para.add(new Phrase(this.getBoldChunk(this.getText("REPORTS_EDITION") + ": ")));
            para.add(new Phrase(this.getSmallFontChunk(data[5] + " ")));
        }

        if (StringUtils.isNotBlank(data[6])) {
            para.add(new Phrase(this.getBoldChunk(this.getText("REPORTS_DATE") + ": ")));
            para.add(new Phrase(this.getSmallFontChunk(data[6])));
        }

        cell = new PdfPCell(para);
        cell.setColspan(11);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
        cell.setPaddingTop(5f);
        cell.setPaddingLeft(7f);
        cell.setPaddingBottom(4f);
        table.addCell(cell);
    }
    document.add(table);
}

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

License:Open Source License

public MemoryFileDTO createFileLabelsPDF(ArrayList<LabelDTO> labels, LabelConfigDTO labelConfig) {
    Document document = new Document();
    final MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("biblivre_etiquetas_" + new Date().getTime() + ".pdf");
    try {/*from   w ww . j  a v  a2  s.  co m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        float verticalMargin = (297.0f - (labelConfig.getHeight() * labelConfig.getRows())) / 2;
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                verticalMargin * ApplicationConstants.MM_UNIT, verticalMargin * ApplicationConstants.MM_UNIT);
        document.open();

        PdfPTable table = new PdfPTable(labelConfig.getColumns());
        table.setWidthPercentage(100f);
        PdfPCell cell;

        int i = 0;
        for (i = 0; i < labelConfig.getOffset(); i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }

        for (LabelDTO ldto : labels) {
            PdfContentByte cb = writer.getDirectContent();

            String holdingSerial = String.valueOf(ldto.getHoldingSerial());
            while (holdingSerial.length() < 10) {
                holdingSerial = "0" + holdingSerial;
            }
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            code39.setCode(holdingSerial);
            code39.setStartStopText(false);

            Image image39 = code39.createImageWithBarcode(cb, null, null);
            if (labelConfig.getHeight() > 30.0f) {
                image39.scalePercent(110f);
            } else {
                image39.scalePercent(90f);
            }

            Paragraph para = new Paragraph();
            Phrase p1 = new Phrase(StringUtils.left(ldto.getAuthor(), 28) + "\n");
            Phrase p2 = new Phrase(StringUtils.left(ldto.getTitle(), 28) + "\n\n");
            Phrase p3 = new Phrase(new Chunk(image39, 0, 0));
            para.add(p1);
            para.add(p2);
            para.add(p3);

            cell = new PdfPCell(para);
            i++;
            cell.setNoWrap(true);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);

            Paragraph para2 = new Paragraph();
            Phrase p5 = new Phrase(ldto.getLocationA() + "\n");
            Phrase p6 = new Phrase(ldto.getLocationB() + "\n");
            Phrase p7 = new Phrase(ldto.getLocationC() + "\n");
            Phrase p8 = new Phrase(ldto.getLocationD() + "\n");
            Phrase p4 = new Phrase(ldto.getAssetHolding() + "\n");
            para2.add(p5);
            para2.add(p6);
            para2.add(p7);
            para2.add(p8);
            para2.add(p4);

            cell = new PdfPCell(para2);
            i++;
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % labelConfig.getColumns()) != 0) {
            while ((i % labelConfig.getColumns()) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        file.setFileData(baos.toByteArray());
    } catch (Exception de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:biblivre3.circulation.CirculationBO.java

License:Open Source License

public MemoryFileDTO createFileUserCardsPDF(ArrayList<UserCardDTO> cards, int startOffset, Properties i18n) {
    Document document = new Document();
    MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("user_cards_" + new Date().getTime() + ".pdf");
    try {//from  w  w w. j a  v a2s.c o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                9.09f * ApplicationConstants.MM_UNIT, 9.09f * ApplicationConstants.MM_UNIT);
        document.open();
        PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100f);
        PdfPCell cell;
        int i = 0;
        for (i = 0; i < startOffset; i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }
        for (UserCardDTO card : cards) {
            String userEnrollNumber = String.valueOf(card.getUserId());
            PdfContentByte cb = writer.getDirectContent();
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            while (userEnrollNumber.length() < 10) {
                userEnrollNumber = "0" + userEnrollNumber;
            }
            code39.setCode(userEnrollNumber);
            code39.setStartStopText(false);
            Image image39 = code39.createImageWithBarcode(cb, null, null);
            image39.scalePercent(110f);
            Paragraph para = new Paragraph();
            String name = card.getUserName();
            name = name.length() >= 30 ? name.substring(0, 30) : name;
            Phrase p1 = new Phrase(name + "\n");
            Phrase p2 = new Phrase(new Chunk(image39, 0, 0));
            Phrase p3 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_SERIAL") + ": " + card.getUserId() + "\n");
            Phrase p4 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_TYPE") + ": " + card.getUserType() + "\n\n");
            para.add(p1);
            para.add(p3);
            para.add(p4);
            para.add(p2);
            cell = new PdfPCell(para);
            i++;
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % 3) != 0) {
            while ((i % 3) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        writer.close();
        file.setFileData(baos.toByteArray());
    } catch (DocumentException de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:com.aryjr.nheengatu.pdf.PDFTable.java

License:Open Source License

private static float extractVisibleComponents(final Tag tag, final PdfPCell cell, final Paragraph paragraph,
        float cellWidth) throws DocumentException {
    final Iterator tags = tag.tags();// tags inside the cell
    Object component;/*  w  ww .  j av a 2 s .c o  m*/
    final TagsManager tm = TagsManager.getInstance();
    // Seting the HTML row or table background color
    if (tag.getName().equalsIgnoreCase("TD")) {
        cell.setBorderColor(tm.getPreviousState(2).getBgcolor());
        cell.setBorderWidth(tag.getPropertyValue(PDFTable.CELLSPACING) == null ? 1
                : Integer.parseInt(tag.getPropertyValue(PDFTable.CELLSPACING)));
        //cell.setBackgroundColor(tm.getBgcolor());
        cell.setBackgroundColor(new Color(255, 255, 255));
        cell.setVerticalAlignment(tm.getValign());
        cell.setHorizontalAlignment(tm.getAlign());
        paragraph.setAlignment(tm.getAlign());
    }
    while (tags.hasNext()) {
        component = tags.next();
        if (component instanceof Text) {
            String s = ((Text) component).getText();
            if (s.contains("\\\"")) {
                s = s.replace("\\\"", "\"");
                ((Text) component).setText(s);
            }
            // If it's a text, create a iText text component for it
            paragraph.add(PDFText.createChunk((Text) component));
            cellWidth += PDFText.getWidth((Text) component);
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("br")) {
            // If it's a HTML line break
            paragraph.add("\n");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("img")) {
            // If it's a HTML image, create a iText image component for it
            try {
                final Image img = PDFImage.createImage((Tag) component);
                //Nato: paragraph.add(new Chunk(img, 0, -2));
                paragraph.add(new Chunk(img, 0, 0));
                cellWidth += img.getScaledWidth();
                // TODO Is there an iText bug here?
                //if (img.scaledHeight() == 1f) {
                //cell.setFixedHeight(img.getScaledHeight());
                //}
            } catch (final Exception e) {
                e.printStackTrace();
            }
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("table")) {
            // If it's a HTML table, create a iText table component for it
            try {
                // TODO the default value of nowrap here will be true or
                // false??? If true, there is a problem with the cell width
                cell.setNoWrap(false);
                final PDFTable t = PDFTable.createTable((Tag) component);
                cell.addElement(t);
                final float[] cw = t.getWidths();
                for (final float element : cw) {
                    cellWidth += element;
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("select")) {
            // If it's a HTML select field, I will get only the selected
            // option
            final Tag select = (Tag) component;
            Tag opt;
            tm.checkTag(select);
            final Iterator opts = select.tags();
            boolean selected = false;
            while (opts.hasNext()) {
                opt = (Tag) opts.next();
                if (opt.getPropertyValue("selected") != null) {
                    tm.checkTag(opt);
                    cellWidth = PDFTable.extractVisibleComponents(opt, cell, paragraph, cellWidth);
                    selected = true;
                    break;
                }
            }
            if (!selected) {
                // if none option have the selected attribute the first will
                // be shown
                opt = select.getFirstTag("option");
                tm.checkTag(opt);
                cellWidth = PDFTable.extractVisibleComponents(opt, cell, paragraph, cellWidth);
            }
        } else {
            // If it's an another tag, check the name and call this method
            // again
            tm.checkTag((Tag) component);
            cellWidth = PDFTable.extractVisibleComponents((Tag) component, cell, paragraph, cellWidth);
            tm.back();
        }
    }
    return cellWidth;
}

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

License:Open Source License

/**
 *
 */// ww  w .j a va 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

/**
 *
 *///w w  w. j  av 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.geek.tutorial.itext.image.EmbedImage.java

License:Open Source License

public EmbedImage() throws Exception {

    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("EmbedImage.pdf"));
    document.open();//from w w  w  .j a  va2 s.  c o  m

    // Code 1
    document.add(new Phrase("Please press "));
    document.add(new Chunk(Image.getInstance("save.gif"), 0, 0));
    document.add(new Phrase(" to save the file."));

    document.close();
}