Example usage for com.lowagie.text Image getInstance

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

Introduction

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

Prototype

public static Image getInstance(Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:questions.ocg.StatusBars1.java

public Image getImage(PdfContentByte cb, int i) throws BadElementException {
    PdfTemplate tmp = cb.createTemplate(100, 10);
    tmp.setBoundingBox(new Rectangle(-5, -2, 105, 12));
    Rectangle r = new Rectangle(0, 0, 100, 10);
    tmp.rectangle(r);//from   w ww  . ja  v a 2s  . c o m
    r = new Rectangle(0, 0, i, 10);
    tmp.beginLayer(colorLayerColored);
    if (i % 2 == 0)
        r.setBackgroundColor(Color.RED);
    else
        r.setBackgroundColor(Color.GREEN);
    tmp.rectangle(r);
    tmp.endLayer();
    tmp.beginLayer(colorLayerGreyed);
    r = new Rectangle(0, 0, i, 10);
    if (i % 2 == 0)
        r.setBackgroundColor(new GrayColor(10));
    else
        r.setBackgroundColor(new GrayColor(97));
    tmp.rectangle(r);
    tmp.endLayer();
    return Image.getInstance(tmp);
}

From source file:questions.tables.AddTableAsHeaderFooter.java

public void onEndPage(PdfWriter writer, Document document) {
    try {/*from  ww w.j ava  2  s  . c o  m*/
        // Header
        headerTable.writeSelectedRows(0, -1, document.leftMargin(),
                document.top() + headerTable.getTotalHeight(), writer.getDirectContent());
        // Footer
        PdfPTable footerTable = new PdfPTable(2);
        PdfPCell cell1 = new PdfPCell(new Phrase("page " + writer.getPageNumber()));
        footerTable.addCell(cell1);
        PdfPCell cell2 = new PdfPCell(Image.getInstance(tpl));
        footerTable.addCell(cell2);
        footerTable.setTotalWidth(document.right() - document.left());
        footerTable.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:recite18th.controller.Controller.java

License:Open Source License

public void print(String action) {
    /** thanks to http://www.java2s.com/Code/Java/PDF-RTF/DemonstratesthecreatingPDFinportraitlandscape.htm
     * QUICK FIX : do landscape/* w w w  .j a v a2s .c o  m*/
     */
    response.setContentType("application/pdf"); // Code 1
    if (action.equals("download")) {
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "Report " + controllerName + ".pdf\"");
    }
    Document document = new Document(PageSize.A1.rotate());
    try {
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
        document.open();

        // various fonts
        BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
        BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
        BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);

        String headerImage = Config.base_path + "images/report-logo.gif";

        Image imghead = Image.getInstance(headerImage);
        imghead.setAbsolutePosition(0, 0);
        PdfContentByte cbhead = writer.getDirectContent();
        PdfTemplate tpLogo = cbhead.createTemplate(600, 300);
        tpLogo.addImage(imghead);

        PdfTemplate tpTitle = cbhead.createTemplate(1100, 300);
        String txtHeader = "BADAN KEPEGAWAIAN DAERAH PEMERINTAH DAERAH";//Config.application_title;
        tpTitle.beginText();
        tpTitle.setFontAndSize(bf_times, 36);
        tpTitle.showText(txtHeader);
        tpTitle.endText();

        PdfTemplate tpTitle2 = cbhead.createTemplate(900, 300);
        String txtHeader2 = "         KABUPATEN BANTUL YOGYAKARTA";
        tpTitle2.beginText();
        tpTitle2.setFontAndSize(bf_times, 36);
        tpTitle2.showText(txtHeader2);
        tpTitle2.endText();

        PdfTemplate tpAlamat = cbhead.createTemplate(1000, 400);
        tpAlamat.beginText();
        tpAlamat.setFontAndSize(bf_times, 24);
        tpAlamat.showText(
                "Alamat : Jln. R. W. Monginsidi No. 01 Kompleks Parasamya Bantul, Telp. (0274) 367509");
        tpAlamat.endText();

        DateFormat df = new SimpleDateFormat("dd MMM yyyy");
        java.util.Date dt = new java.util.Date();
        PdfTemplate tp3 = cbhead.createTemplate(600, 300);
        tp3.beginText();
        tp3.setFontAndSize(bf_times, 16);

        tp3.showText("Tanggal : " + df.format(dt));
        tp3.endText();

        cbhead.addTemplate(tpLogo, 800, 1500);//logo
        cbhead.addTemplate(tpTitle, 1000, 1580);
        cbhead.addTemplate(tpTitle2, 1000, 1540);
        cbhead.addTemplate(tpAlamat, 1000, 1500);//alamat
        cbhead.addTemplate(tp3, 270, 1500);//tanggal

        HeaderFooter header = new HeaderFooter(new Phrase(cbhead + "", new Font(bf_helv)), false);
        header.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);

        //PdfContentByte cb = writer.getDirectContent();
        Paragraph par = new Paragraph(
                "\n\n\n\n\n\n\nLAPORAN DATA SELURUH " + controllerName.toUpperCase() + "\n");
        par.getFont().setStyle(Font.BOLD);
        par.getFont().setSize(18);
        par.setAlignment("center");
        document.add(par);
        document.add(new Paragraph("\n\n"));

        // get data
        initSqlViewDataPerPage();
        if (sqlViewDataPerPageForReport == null) {
            sqlViewDataPerPageForReport = sqlViewDataPerPage;
        }
        PreparedStatement pstmt = Db.getCon().prepareStatement(sqlViewDataPerPageForReport,
                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();
        // thanks to set cell width http://www.jexp.ru/index.php/Java/PDF_RTF/Table_Cell_Size#Setting_Cell_Widths
        if (nColoumn > 0) {
            Model model = initModel();
            String tableName = model.getTableName();
            // create table header
            //     float[] widths = {1, 4};
            PdfPTable table;// = new PdfPTable(nColoumn);
            PdfPCell cell = new PdfPCell(new Paragraph("Daftar " + controllerName));

            Hashtable hashModel = TableCustomization.getTable(model.getTableName());

            int ncolumnHeader = nColoumn + 1; // +1 because of row. number
            if (hashModel != null) {
                ncolumnHeader = Integer.parseInt("" + hashModel.get("columnCount")) + 1;
            }
            table = new PdfPTable(ncolumnHeader);
            cell.setColspan(ncolumnHeader);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            Paragraph p2 = new Paragraph("No.");
            p2.getFont().setSize(20);
            PdfPCell cellColNo = new PdfPCell(p2);
            cellColNo.setNoWrap(true);
            cellColNo.setMinimumHeight(50);
            cellColNo.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellColNo);

            if (hashModel != null) {
                Enumeration k = hashModel.keys();
                while (k.hasMoreElements()) {
                    String key = (String) k.nextElement();
                    if (key.equals("columnCount")) {
                        continue;
                    }
                    PdfPCell cellCol = new PdfPCell(new Paragraph(hashModel.get(key) + ""));
                    cellCol.setNoWrap(true);
                    cellCol.setMinimumHeight(50);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);

                    table.addCell(cellCol);
                }
            } else {
                for (int i = 1; i < ncolumnHeader; i++) {
                    System.out.println("DATA = " + metaColumn.getColumnName(i));
                    Paragraph p1 = new Paragraph(metaColumn.getColumnName(i) + "");
                    p1.getFont().setSize(20);
                    PdfPCell cellCol = new PdfPCell(p1);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(cellCol);
                }
            }

            //iterate all columns : table data
            resultSet.beforeFirst();
            int row = 1;
            while (resultSet.next()) {
                System.out.println(row);
                Paragraph p3 = new Paragraph(row + "");
                p3.getFont().setSize(20);
                cell = new PdfPCell(p3);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                if (hashModel != null) {//skip dulu u/ kasus ga pny class kustomasi table
                    Enumeration k = hashModel.keys();
                    while (k.hasMoreElements()) {
                        String key = (String) k.nextElement();
                        if (key.equals("columnCount")) {
                            continue;
                        }
                        table.addCell(resultSet.getObject(key) + "");
                    }
                } else {
                    for (int i = 1; i < ncolumnHeader; i++) {
                        System.out.println("DATA = " + metaColumn.getColumnName(i));
                        Paragraph p1 = new Paragraph(resultSet.getObject(metaColumn.getColumnName(i)) + "");
                        p1.getFont().setSize(18);
                        PdfPCell cellCol = new PdfPCell(p1);
                        cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(cellCol);
                    }
                }

                row++;
            }

            document.add(table);
            document.add(new Paragraph("\n\n"));
            par = new Paragraph("Mengetahui");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Kepada Badan Kepegawaian");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("\n\n\n");

            document.add(par);
            par = new Paragraph("Drs. Maman Permana");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Nip: 197802042006041013");
            par.setAlignment("center");

            document.add(par);

        }
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ro.nextreports.engine.exporter.RtfExporter.java

License:Apache License

private RtfCell renderRtfCell(BandElement bandElement, Object value, int gridRow, int gridColumn, int rowSpan,
        int colSpan, boolean image) {
    Map<String, Object> style = buildCellStyleMap(bandElement, value, gridRow, gridColumn, colSpan);
    String stringValue;/*from w ww  . ja  va2  s.co  m*/

    FontFactoryImp fact = new FontFactoryImp();
    Font fnt;
    if (bandElement != null) {
        String fontName = (String) style.get(StyleFormatConstants.FONT_NAME_KEY);
        int size = ((Float) style.get(StyleFormatConstants.FONT_SIZE)).intValue();
        fnt = getFont(fontName, size);
    } else {
        fnt = getFont(10);
    }

    RtfCell cell = null;
    boolean specialCell = false;
    if (image) {
        try {
            if (value == null) {
                cell = new RtfCell(new Phrase(IMAGE_NOT_FOUND));
            } else {
                ImageBandElement ibe = (ImageBandElement) bandElement;
                byte[] imageBytes = getImage((String) value, ibe.getWidth(), ibe.getHeight());
                cell = new RtfCell(Image.getInstance(imageBytes));
            }
        } catch (Exception e) {
            cell = new RtfCell(IMAGE_NOT_LOADED);
        }
        specialCell = true;
    } else if (bandElement instanceof HyperlinkBandElement) {
        Hyperlink hyperlink = ((HyperlinkBandElement) bandElement).getHyperlink();
        Anchor anchor = new Anchor(hyperlink.getText(), fnt);
        anchor.setReference(hyperlink.getUrl());
        Phrase ph = new Phrase();
        ph.add(anchor);
        try {
            cell = new RtfCell(ph);
        } catch (BadElementException e) {
            e.printStackTrace();
            cell = new RtfCell(hyperlink.getText());
        }
        specialCell = true;
    } else if (bandElement instanceof ReportBandElement) {
        Report report = ((ReportBandElement) bandElement).getReport();
        ExporterBean eb = null;
        try {
            eb = getSubreportExporterBean(report);
            RtfExporter subExporter = new RtfExporter(eb);
            subExporter.export();
            Table innerTable = subExporter.getTable();
            cell = new RtfCell(innerTable);
        } catch (Exception e) {
            cell = new RtfCell();
            e.printStackTrace();
        } finally {
            if ((eb != null) && (eb.getResult() != null)) {
                eb.getResult().close();
            }
        }
        specialCell = true;
    } else if (bandElement instanceof VariableBandElement) {
        VariableBandElement vbe = (VariableBandElement) bandElement;
        Variable var = VariableFactory.getVariable(vbe.getVariable());
        if (var instanceof PageNoVariable) {
            cell = new RtfCell();
            cell.add(new RtfPageNumber());
            cell.setBorderWidth(0);
            specialCell = true;
        }
    } else if (bandElement instanceof ExpressionBandElement) {
        // special case pageNo inside an expression
        // bandName is not important here (it is used for groupRow
        // computation)
        PrefixSuffix pf = interpretPageNo(bandElement);
        if (pf != null) {
            updateFont(fnt, style);
            cell = new RtfCell();
            if (!"".equals(pf.getPrefix())) {
                cell.add(new Phrase(pf.getPrefix(), fnt));
            }
            cell.add(new RtfPageNumber(fnt));
            if (!"".equals(pf.getSuffix())) {
                cell.add(new Phrase(pf.getSuffix(), fnt));
            }
            specialCell = true;
        }
    } else if (bandElement instanceof ImageColumnBandElement) {
        try {
            String v = StringUtil.getValueAsString(value, null);
            if (StringUtil.BLOB.equals(v)) {
                cell = new RtfCell(new Phrase(StringUtil.BLOB));
            } else {
                ImageColumnBandElement icbe = (ImageColumnBandElement) bandElement;
                byte[] imageD = StringUtil.decodeImage(v);
                byte[] imageBytes = getImage(imageD, icbe.getWidth(), icbe.getHeight());
                cell = new RtfCell(Image.getInstance(imageBytes));
            }
        } catch (Exception e) {
            cell = new RtfCell(IMAGE_NOT_LOADED);
        }
        specialCell = true;
    }
    if (!specialCell) {
        if (style.containsKey(StyleFormatConstants.PATTERN)) {
            stringValue = StringUtil.getValueAsString(value, (String) style.get(StyleFormatConstants.PATTERN),
                    getReportLanguage());
        } else {
            stringValue = StringUtil.getValueAsString(value, null, getReportLanguage());
        }
        if (stringValue == null) {
            stringValue = "";
        }
        Phrase ph;
        if (stringValue.startsWith("<html>")) {
            StringReader reader = new StringReader(stringValue);
            List<Element> elems = new ArrayList<Element>();
            try {
                elems = HTMLWorker.parseToList(reader, new StyleSheet());
                ph = new Phrase();
                for (int i = 0; i < elems.size(); i++) {
                    Element elem = (Element) elems.get(i);
                    ph.add(elem);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                ph = new Phrase(stringValue, fnt);
            }
        } else {
            ph = new Phrase(stringValue, fnt);
        }

        try {
            cell = new RtfCell(ph);
        } catch (BadElementException e) {
            e.printStackTrace();
            cell = new RtfCell(stringValue);
        }
    }

    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

    if (colSpan > 1) {
        cell.setColspan(colSpan);
    }

    if (rowSpan > 1) {
        cell.setRowspan(rowSpan);
    }

    setCellStyle(fnt, style, cell);

    return cell;
}

From source file:rtf.shapes.RTFShapeTextWrap.java

/**
 * @param args//w w w.  j  av  a2  s .co  m
 */
public static void main(String[] args) {
    Document document = new Document();

    try {
        RtfWriter2.getInstance(document, new FileOutputStream(resultsPath + outFile));
        document.open();
        Image logo = Image.getInstance(resourcePath + inFile1);

        Paragraph p = new Paragraph();
        Chunk c = new Chunk();
        c.append(
                "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. "
                        + "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. ");

        RtfShapePosition position = new RtfShapePosition(2000, 6000, 10500, 4500);
        RtfShape shape = new RtfShape(RtfShape.SHAPE_RECTANGLE, position);
        shape.setWrapping(RtfShape.SHAPE_WRAP_LEFT);
        shape.setProperty(new RtfShapeProperty(RtfShapeProperty.PROPERTY_IMAGE, logo));

        p.add(shape);
        p.add(c);
        document.add(p);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (BadElementException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:s2s.luna.reports.Report_REP_SOP.java

License:GNU General Public License

@Override
public void doReport() throws DocumentException, IOException, BadElementException, Exception {

    SecurityWrapper Security = SecurityWrapper.getInstance();
    ISopraluogoHome home1 = (ISopraluogoHome) PseudoContext.lookup("SopraluogoBean");
    ISopraluogo bean = home1.findByPrimaryKey(new Long(new Long(request.getParameter("ID"))));
    IAnagrProcedimentoHome home_pro = (IAnagrProcedimentoHome) PseudoContext.lookup("AnagrProcedimentoBean");
    IAnagrProcedimento bean_pro = home_pro.findByPrimaryKey(new Long(bean.getCOD_PRO()));
    IDipendenteHome home_dpd = (IDipendenteHome) PseudoContext.lookup("DipendenteBean");

    ICantiereHome home_can = (ICantiereHome) PseudoContext.lookup("CantiereBean");
    ICantiere bean_can = home_can.findByPrimaryKey(new Long(bean.getCOD_CAN()));

    IAnagrOpereHome home_ope = (IAnagrOpereHome) PseudoContext.lookup("AnagrOpereBean");
    IAnagrOpere bean_ope = null;/*from  w w w. j  a  v  a  2  s.com*/
    long COD_OPE = bean.getCOD_OPE();
    if (COD_OPE != 0) {
        bean_ope = home_ope.findByPrimaryKey(COD_OPE);
    }

    lCOD_AZL = Security.getAziendaR();
    IAziendaHome home_az = (IAziendaHome) PseudoContext.lookup("AziendaBean");
    IAzienda bean_az = home_az.findByPrimaryKey(new Long(lCOD_AZL));

    initDocument("the doc",
            // Intestazione - Cella a sinistra
            bean_pro.getstrDES(),
            // Intestazione - Cella centrale
            bean_can.getNOM_CAN() + " - " + bean.getNUM_SOP(),
            // Pi di pagina Cella a sinistra
            bean_az.getRAG_SCL_AZL(),
            // Pi di pagina Cella a destra
            formatPlain(bean.getDAT_SOP()));

    m_handler.bShowDate = false;

    // LOGO E TITOLO
    {
        CenterMiddleTable tbl = new CenterMiddleTable(2);
        tbl.setDefaultCellBorder(0);
        int width[] = { 15, 75 };
        tbl.setWidths(width);
        if (IncludeLogo) {
            Image png = loadImage("LOGO");
            png.scalePercent(50);
            png.setAlignment(Image.ALIGN_LEFT);
            Cell cImage = new Cell(png);
            tbl.addCell(cImage);
        } else {
            tbl.addCell("");
        }
        CenterMiddleTable tbl2 = new CenterMiddleTable(1);
        tbl2.setDefaultCellBorder(0);
        tbl2.addCellBU(ApplicationConfigurator.CUSTOMER_NAME.toUpperCase(), 15);
        tbl2.addCellBU(ApplicationConfigurator.LanguageManager.getString("Coordinamento.sicurezza.cantieri")
                .toUpperCase(), 15);

        Cell cText = new Cell(tbl2);
        tbl.addCell(cText);
        m_document.add(tbl);
    }

    writeIndent();
    {
        CenterMiddleTable tbl = new CenterMiddleTable(1);
        if (bStandAlone) {
        }
        m_document.add(tbl);
    }

    // DATI DEL SOPRALLUOGO
    {
        CenterMiddleTable tbl = new CenterMiddleTable(4);
        tbl.toLeft();
        int width[] = { 30, 20, 25, 25 };
        tbl.setWidths(width);
        tbl.addCell(
                ApplicationConfigurator.LanguageManager.getString("Sopralluogo.N") + "  " + bean.getNUM_SOP(),
                defaultFontSize);
        tbl.addCell(ApplicationConfigurator.LanguageManager.getString("del") + "  "
                + formatPlain(bean.getDAT_SOP()), defaultFontSize);
        tbl.addCell(
                ApplicationConfigurator.LanguageManager.getString("Inizio.h")
                        + (bean.getORA_INI() != null ? bean.getORA_INI().toString().substring(0, 5) : ""),
                defaultFontSize);
        tbl.addCell(
                ApplicationConfigurator.LanguageManager.getString("Fine.h")
                        + (bean.getORA_FIN() != null ? bean.getORA_FIN().toString().substring(0, 5) : ""),
                defaultFontSize);
        m_document.add(tbl);
    }
    {
        CenterMiddleTable tbl = new CenterMiddleTable(3);
        tbl.toLeft();
        int width[] = { 34, 33, 33 };
        tbl.setWidths(width);
        tbl.addCell(ApplicationConfigurator.LanguageManager.getString("Linea") + ":  " + bean_pro.getstrDES(),
                defaultFontSize);
        tbl.addCell(
                ApplicationConfigurator.LanguageManager.getString("Stazione") + ":  " + bean_can.getNOM_CAN(),
                defaultFontSize);
        tbl.addCell(ApplicationConfigurator.LanguageManager.getString("Opera") + ":  "
                + (bean_ope != null ? bean_ope.getstrNOM_OPE() : ""), defaultFontSize);
        m_document.add(tbl);
    }

    // PRESENTI AZIENDA
    {
        CenterMiddleTable tbl = new CenterMiddleTable(2);
        tbl.toLeft();
        int width[] = { 25, 70 };
        tbl.setWidths(width);
        tbl.border();
        java.util.Collection col = home_dpd.getDipendentiBySOP_View(lCOD_SOP);
        tbl.addCell(ApplicationConfigurator.LanguageManager.getString("Presenti.RM"), defaultFontSize);
        java.util.Iterator it = col.iterator();
        String presentiRM = "";
        while (it.hasNext()) {
            DipendentiBySOP_View obj = (DipendentiBySOP_View) it.next();
            presentiRM += (StringManager.isEmpty(presentiRM) ? "" : ", ") + obj.COG_DPD + " " + obj.NOM_DPD;
        }
        tbl.addCell(presentiRM, defaultFontSize);
        m_document.add(tbl);
    }

    // PRESENTI IMPRESA
    {
        CenterMiddleTable tbl = new CenterMiddleTable(2);
        tbl.toLeft();
        tbl.setPadding(1 / 2);
        int width[] = { 25, 70 };
        tbl.setWidths(width);
        tbl.border();
        java.util.Collection col = home_dpd.getDipendentiEstBySOP_View(lCOD_SOP);
        java.util.Iterator it = col.iterator();
        tbl.addCell(ApplicationConfigurator.LanguageManager.getString("Presenti.impresa"), defaultFontSize);
        String presentiIMP = "";
        while (it.hasNext()) {
            DipendentiBySOP_View obj = (DipendentiBySOP_View) it.next();
            presentiIMP += (StringManager.isEmpty(presentiIMP) ? "" : ", ") + obj.COG_DPD + " " + obj.NOM_DPD
                    + " (" + obj.IMPRESA + ")";
        }
        tbl.addCell(presentiIMP, defaultFontSize);
        m_document.add(tbl);
    }
    writeLine();

    // CONSTATAZIONI
    {
        CenterMiddleTable tbl = new CenterMiddleTable(1);
        tbl.toLeft();
        int width[] = { 100 };
        tbl.setWidths(width);
        tbl.addHeaderCellB2(ApplicationConfigurator.LanguageManager.getString("CONSTATAZIONI"), 1, false, 11);
        m_document.add(tbl);
    }
    {
        CenterMiddleTable tbl = new CenterMiddleTable(2);
        tbl.toLeft();
        int width[] = { 5, 85 };
        tbl.setWidths(width);
        java.util.Collection col = home1.getConstatazioniSop(lCOD_SOP);
        java.util.Iterator it = col.iterator();
        tbl.setWidths(width);
        String constElementSeparator = " - ";
        Alphabet c = new Alphabet();
        String REV1 = c.getNextElement("1");
        while (it.hasNext()) {
            jbConstatazione obj = (jbConstatazione) it.next();

            // Numerazione alfabetica
            Cell cell = new Cell(new Phrase(Formatter.format(REV1), REPORT_SETTINGS.ftText9B));
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            tbl.addCell(cell);

            // Constatazione
            tbl.addCell(Formatter.format(
                    (StringManager.isNotEmpty(obj.sRAG_SCL_DTE) ? obj.sRAG_SCL_DTE + constElementSeparator : "")
                            + (StringManager.isNotEmpty(obj.sNOM_ATT)
                                    ? obj.sNOM_ATT + constElementSeparator
                                    : "")
                            + (StringManager.isNotEmpty(obj.sDES_LIB) ? obj.sDES_LIB + constElementSeparator
                                    : "")
                            + obj.sDESC),
                    defaultFontSize);
            REV1 = c.getNextElement(REV1);
        }
        m_document.add(tbl);
    }
    writeLine();

    // DISPOSIZIONI
    {
        CenterMiddleTable tbl = new CenterMiddleTable(1);
        tbl.toLeft();
        int width[] = { 85 };
        tbl.setWidths(width);
        tbl.addHeaderCellB2(ApplicationConfigurator.LanguageManager.getString("DISPOSIZIONI"), 1, false, 11);
        m_document.add(tbl);
    }
    {
        CenterMiddleTable tbl = new CenterMiddleTable(2);
        tbl.toLeft();
        int width[] = { 5, 85 };
        java.util.Collection col = home1.getConstatazioniSop(lCOD_SOP);
        java.util.Iterator it = col.iterator();
        tbl.setWidths(width);
        Alphabet c = new Alphabet();
        String REV2 = c.getNextElement("1");
        while (it.hasNext()) {
            jbConstatazione obj = (jbConstatazione) it.next();

            // Numerazione alfabetica
            Cell cell = new Cell(new Phrase(Formatter.format(REV2), REPORT_SETTINGS.ftText9B));
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            tbl.addCell(cell);

            // Disposizione generata
            tbl.addCell(Formatter.format(obj.sDIS_GEN), defaultFontSize);
            REV2 = c.getNextElement(REV2);
        }
        m_document.add(tbl);
    }

    // FIRME
    // Spazio per le firme
    for (int i = 1; i <= 5; i++) {
        writeLine();
    }
    {
        CenterMiddleTable tbl = new CenterMiddleTable(2);
        int width[] = { 50, 50 };
        tbl.setWidths(width);
        tbl.setDefaultCellBorder(0);

        // Firme del personale dell'azienda
        Cell cell = new Cell(
                new Phrase(ApplicationConfigurator.CUSTOMER_NAME.toUpperCase(), REPORT_SETTINGS.ftText9));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        tbl.addCell(cell);

        // Firme del personale delle imprese
        Cell cell2 = new Cell(
                new Phrase(ApplicationConfigurator.LanguageManager.getString("Impresa").toUpperCase(),
                        REPORT_SETTINGS.ftText9));
        cell2.setHorizontalAlignment(Element.ALIGN_RIGHT);
        tbl.addCell(cell2);

        m_document.add(tbl);
    }

    // FOTO
    {
        Collection<jbMedia> listaFoto = home1.getMediaSOP(lCOD_SOP);
        if (listaFoto != null && listaFoto.size() > 0) {

            // STAMPA L'INDICE DELLE FOTO.
            boolean firstFoto = true;
            int fotoIndex = 0;
            for (jbMedia foto : listaFoto) {
                try {
                    // Verifica che l'immagine sia in un formato supportato.
                    Image.getInstance(foto.mediaData);
                    fotoIndex++;
                    if (firstFoto) {
                        writePage();
                        writeTitle(ApplicationConfigurator.LanguageManager.getString("Indice.foto.allegate"));
                        firstFoto = false;
                    }
                    writeLine();
                    // Stampo il progessivo della foto, nel formato "Foto n".
                    writeText2Bold(ApplicationConfigurator.LanguageManager.getString("Foto") + " " + fotoIndex);
                    // Stampo il "nome" o se questo  assente, "il nome file".
                    writeText2(StringManager.isNotEmpty(foto.sNOM_MED) ? Formatter.format(foto.sNOM_MED)
                            : Formatter.format(foto.sFile));
                    // Stampo, se presente, la "descrizione".
                    writeText2(StringManager.isNotEmpty(foto.sDES_MED) ? Formatter.format(foto.sDES_MED) : "");
                } catch (Exception ex) {
                    // Eccezione silenziosa.
                    // Gestisce il caso in cui l'allegato non sia un immagine
                }
            }
            // STAMPA LE FOTO.
            firstFoto = true;
            fotoIndex = 0;
            byte SPACE_FOR_TITLE = 20;
            byte SPACE_FOR_BOTTOM_MARGIN = 20;
            boolean strictImageSequence = m_writer.isStrictImageSequence();
            m_writer.setStrictImageSequence(true);
            for (jbMedia foto : listaFoto) {
                Element image = prepareImage(m_document, foto.mediaData);
                if (image != null) {
                    fotoIndex++;
                    if (firstFoto) {
                        writePage();
                        firstFoto = false;
                    }
                    if (m_document.getPageSize().getHeight() - m_document.topMargin()
                            + 20 < getAvailablePageSpace(m_document, m_writer)) {
                        writeLine();
                    }
                    if (getAvailablePageSpace(m_document, m_writer)
                            - (SPACE_FOR_TITLE + SPACE_FOR_BOTTOM_MARGIN) < ((Image) image).getScaledHeight()) {
                        writePage();
                    }
                    // Stampo il progessivo della foto, nel formato "Foto n".
                    writeText2(ApplicationConfigurator.LanguageManager.getString("Foto") + " " + fotoIndex);
                    // Stampo l'immagine.
                    m_document.add(image);
                }
            }
            m_writer.setStrictImageSequence(strictImageSequence);
        }
    }
    // DOCUMENTI ALLEGATI
    Collection<DocumentiAssociati_Sopralluogo_View> listadocumenti = home1
            .getDocumentiCantiereSOP_STAMPA(lCOD_SOP);
    if (listadocumenti != null && listadocumenti.size() > 0) {

        // STAMPA L'INDICE DEI DOCUMENTI ALLEGATI
        // i documenti allegati sono quei documenti la cui tipologia risulta avere attivo
        //il flag di stampa in sopralluogo.
        boolean firstdocument = true;
        int documentIndex = 0;
        for (DocumentiAssociati_Sopralluogo_View documento : listadocumenti) {
            try {
                // Verifica che l'immagine sia in un formato supportato.
                documentIndex++;
                if (firstdocument) {
                    writePage();
                    writeTitle(ApplicationConfigurator.LanguageManager.getString("Indice.documenti.allegati"));
                    firstdocument = false;
                }
                writeLine();
                // Stampo il "titolo" del documento.
                writeText3Bold(documentIndex + ")"
                        + (StringManager.isNotEmpty(documento.TIT_DOC) ? Formatter.format(documento.TIT_DOC)
                                : Formatter.format(documento.NOM_TPL_DOC)));
                // Stampo, se presente, la "descrizione".
                if (!(documento.DES).equals("")) {
                    writeLine();
                }
                writeText3_3(StringManager.isNotEmpty(documento.DES) ? Formatter.format(documento.DES) : "");

                IAnagrDocumentoHome doc_home = (IAnagrDocumentoHome) PseudoContext.lookup("AnagrDocumentoBean");
                AnagDocumentoFileInfo fileInfo = null;
                AnagDocumentoFileInfo fileInfoLink = null;
                fileInfo = doc_home.getFileInfoU("", documento.lCOD_DOC);
                fileInfoLink = doc_home.getFileInfoULink("", documento.lCOD_DOC);

                // se esiste stampo il file allegato
                if (fileInfo != null) {
                    writeLine();
                    writeText3_3(Formatter.format("   " + "File Allegato:  " + fileInfo.strName));
                } else {
                    writeLine();
                    writeText3_3(Formatter.format("   " + "File Allegato:  "));
                }

                // se esiste stampo il file link allegato
                if (fileInfoLink != null) {
                    writeText3_3(Formatter.format("   " + "File Link Allegato:  " + fileInfoLink.strName));
                } else {
                    writeText3_3(Formatter.format("   " + "File Link Allegato:  "));
                }
                writeLine();
            } catch (Exception ex) {
                // Eccezione silenziosa.
                // Gestisce il caso in cui l'allegato non sia un immagine
            }

        }
        writePage();
        // Stampa documenti allegati
        boolean endWithNewPage = false;
        endWithNewPage = StampaDocumenti(home1, bean.getCOD_SOP(), m_document, m_writer);

    }
    closeDocument();
}

From source file:s2s.luna.reports.Stampa_documento.java

License:GNU General Public License

@SuppressWarnings("CallToThreadDumpStack")
private boolean addPDF(String titolo, byte[] fileContent, Document document, PdfWriter writer) {
    try {/*from   w w w .ja  va2 s.  com*/
        // Inizializzo il contenitore del pdf da importare.
        PdfContentByte cb = writer.getDirectContent();

        // Inizializzo la variabile dove appogger (una alla volta)
        // le pagine del pdf da importare.
        PdfImportedPage page;

        // Apro in lettura il pdf da importare.
        PdfReader pdfReader = new PdfReader(fileContent);

        // Ne determino il numero di pagine totali.
        int pdfPageNumber = pdfReader.getNumberOfPages();

        // Inzializzo il contatore delle pagine.
        int pageOfCurrentReaderPDF = 1;

        // Per ogni pagina...
        while (pageOfCurrentReaderPDF <= pdfPageNumber) {
            // Creo una nuova pagina vuota sul pdf di destinazione.
            document.newPage();
            // Estraggo la pagina dal pdf da importare.
            page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
            // Coverto la pagina in un immagine.
            Image pageImg = Image.getInstance(page);
            // Aggiungo la pagina estratta al pdf di destinazione, ruotandola se necessario.
            PdfPTable table = new PdfPTable(1);
            PdfPCell defaultCell = table.getDefaultCell();
            defaultCell.setRotation(-pdfReader.getPageRotation(pageOfCurrentReaderPDF));
            defaultCell.setBorder(Rectangle.NO_BORDER);
            table.addCell(pageImg);
            document.add(table);
            // Incremento il contatore delle pagine
            pageOfCurrentReaderPDF++;
        }
        return true;
    } catch (Exception ex) {
        // Eccezione silenziosa.
        // Gestisce il caso in cui si verifica un errore non previsto
        ex.printStackTrace();
        return false;
    }
}

From source file:s2s.report.Report.java

License:GNU General Public License

public Element prepareImage(Document doc, byte[] fileContent, boolean marginConsider,
        float distanceFromBottomMargin) {
    try {/*from   w ww. ja  va  2  s .  c om*/
        Image img = Image.getInstance(fileContent);

        // Detemino le dimensioni della pagina, margini esclusi.
        float pageWidth = doc.getPageSize().getWidth()
                - (marginConsider ? doc.leftMargin() + doc.topMargin() : 0);
        float pageHeight = doc.getPageSize().getHeight()
                - (marginConsider ? doc.topMargin() + doc.bottomMargin() : 0)
                - (distanceFromBottomMargin > 0 ? distanceFromBottomMargin : 0);

        // Se l'immagine  pi larga e/o pi alta della pagina, 
        // esclusi i margini...
        if (img.getWidth() > pageWidth || img.getHeight() > pageHeight) {

            // Determino le percentuali di riduzione di entrambi le grandezze 
            // dell'immagine (larghezza ed altezza).
            float reducePrecentWidth = (img.getWidth() - pageWidth) > 0 ? (pageWidth * 100) / img.getWidth()
                    : 100;
            float reducePrecentHeight = (img.getHeight() - pageHeight) > 0
                    ? (pageHeight * 100) / img.getHeight()
                    : 100;

            // Determino la percentuale di riduzione
            float ReducePrecent = reducePrecentWidth;
            ReducePrecent = reducePrecentHeight < ReducePrecent ? reducePrecentHeight : ReducePrecent;

            img.scalePercent(ReducePrecent);
        }
        return img;
    } catch (Exception ex) {
        // Eccezione silenziosa.
        // Gestisce il caso in cui l'allegato non sia un immagine
        ex.printStackTrace();
        return null;
    }
}

From source file:s2s.report.Report.java

License:GNU General Public License

public Image loadImage(String strName) throws Exception {

    SecurityWrapper Security = SecurityWrapper.getInstance();
    String strPath = request.getServletPath();
    String strRealPath = request.getRealPath(strPath);

    strPath = Security.Replace(strPath, "/", File.separator);
    strRealPath = Security.Replace(strRealPath, strPath, "")
            + Security.Replace("/WEB/_images/report/", "/", File.separator);

    if (strName.equals("LOGO")) {
        return Image.getInstance(strRealPath + "626.gif");
    }/*from w  ww  .ja  v a2 s. c  om*/
    return null;
}

From source file:servlets.InvioServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    servletContext = getServletContext();

    HttpSession session = request.getSession(true);
    int idpre = Integer.parseInt(request.getParameter("idpre"));
    System.out.println(idpre);//from  w  ww.  j ava2 s.  c om
    Prenotazione preno = null;
    try {
        preno = manager.getPrenotazione(idpre);
    } catch (SQLException ex) {
        Logger.getLogger(InvioServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    //int id=preno.getId_prenotazione();
    double prezzo_pagato = preno.getId_prezzo();
    int posto = preno.getId_posto();
    int spettacolo = preno.getId_spettacolo();
    Date data = preno.getData_ora_prenotazione();
    String email;
    email = preno.getEmail();
    Date data_spettacolo = preno.getData_ora_spettacolo();
    String film = preno.getTitolo();

    //creo il pdf per la prenotazione
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(servletContext.getRealPath("/") + "ticket.pdf"));
        System.out.println("Creazione file riuscita");
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }
    document.open();

    //creo il paragrafo per il tiolo della pagina
    Paragraph p = new Paragraph("Biglietto n " + idpre);
    p.setAlignment(Element.ALIGN_CENTER);
    try {
        document.add(p);
        System.out.println("Scrittura file riuscita");
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti.");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    //creo il paragrafo per i dati del biglietto
    p = new Paragraph("");
    p.setAlignment(Element.ALIGN_LEFT);
    p.add("Biglietto: " + idpre + "\n");
    p.add("Utente: " + email + "\n");
    p.add("Prezzo pagato: " + prezzo_pagato + "\n");
    p.add("Numero posto: " + posto + "\n");
    p.add("Spettacolo: " + spettacolo + "\n");
    p.add("Data: " + data + "\n");
    p.add("Data spettacolo: " + data_spettacolo + "\n");
    p.add("Film: " + film + "\n");

    try {
        document.add(p);
        System.out.println("Scrittura file riuscita");
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    //creo il qrcode e lo aggiungo alla pagina
    Image image = null;
    File file;
    p = new Paragraph("");
    file = QRCode
            .from("utente:" + email + "\n" + "prezzo:" + prezzo_pagato + "\n" + "numero posto:" + posto + "\n"
                    + "spettacolo:" + spettacolo + "\n" + "data prenotazione:" + data + "\n"
                    + "data spettacolo:" + data_spettacolo + "\n" + "film:" + film)
            .to(ImageType.JPG).withSize(100, 100).file();
    try {
        image = Image.getInstance(file.getAbsolutePath());
    } catch (BadElementException | MalformedURLException ex) {
        // Logger.getLogger(SendTicket.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(file.toString());
    try {
        document.add(image);
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    try {
        document.add(p);
        document.newPage();
        System.out.println("Scrittura file riuscita");
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    document.close();

    try {
        //invio la mail per la conferma della prenotazione con allegato il pdf
        Email.ticketEmail("smtp.gmail.com", "587", "cinemangiare@gmail.com", "Cinemangiaredb", email,
                "Conferma acquisto biglietti",
                "Gentile cliente," + "\n" + "le confermiamo la prenotazione presso il nostro cinema." + "\n"
                        + "In allegato trover il file pdf da stampare contenente i biglietti",
                servletContext.getRealPath("/") + "ticket.pdf");
    } catch (MessagingException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/final.jsp");
    dispatcher.forward(request, response);
}