Example usage for com.itextpdf.text Image getInstance

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

Introduction

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

Prototype

public static Image getInstance(final Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:reporteFertilizacion.ReporteResultadoLaboratorio.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w .  jav  a2  s .c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/pdf");
    try {
        Font font9BoldWhite = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.BOLD, BaseColor.WHITE);
        Font font7Bold = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.BOLD);
        Font font7Normal = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL);
        Font font8Bold = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD);
        Font font8Normal = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL);
        Font font9Bold = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.BOLD);
        Font font9Normal = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.NORMAL);
        Font font10Bold = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);
        Font font10Normal = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL);
        Font font12Bold = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
        Font font12Normal = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
        Font font14Bold = FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD);
        Font font14Normal = FontFactory.getFont(FontFactory.HELVETICA, 14, Font.NORMAL);
        Font font18Bold = FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD);
        Font font22Bold = FontFactory.getFont(FontFactory.HELVETICA, 22, Font.BOLD);

        //obtencion parametros *********************************************************
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Map params = facesContext.getExternalContext().getRequestParameterMap();
        ObjectId parametroObtenido = new ObjectId(params.get("idMuestra").toString());

        ResultadoLaboratorio resLab = ResultadoLaboratorio.getResultadoLaboratorioById(parametroObtenido);
        MuestraLaboratorio muestra = MuestraLaboratorio.getMuestraLaboratorioById(resLab.getMuestra());
        Cliente cli = Cliente.getClienteById(
                Hacienda.getHaciendaById(muestra.getSiembraCultivo().getIdHacienda()).getIdCliente());
        Hacienda hac = Hacienda
                .getHaciendaById(Hacienda.getHaciendaById(muestra.getSiembraCultivo().getIdHacienda()).getId());
        //Lote lot = Lote.getLoteById(muestra.getLote());
        //String lot = muestra.getLote();
        Cultivo cul = Cultivo.getCultivoById(muestra.getSiembraCultivo().getIdCultivo());

        String cliente = cli.getNombre().toUpperCase();
        String ubicacion = Canton.getCantonById(cli.getCanton()).getNombre() + " - "
                + Canton.getCantonById(cli.getCanton()).getLeyendaProvincia() + " - "
                + Canton.getCantonById(cli.getCanton()).getLeyendaPais();
        String codigMuestra = muestra.getCodigo();

        String hacienda = hac.getNombre();
        String cultivo = cul.getNombre();
        //String varie = Variedad.getVariedadById(lot.getIdVariedad()).getNombre();
        String varie = muestra.getSiembraCultivo().getLeyendaVariedad();
        //String estacionMonitoreo = lot.getEstacion().get(0).getCodigo();
        String estacionMonitoreo = muestra.getSiembraCultivo().getUnidadManejo();
        //String estacionMonitoreo = muestra.getLoteCompleto().getListadoMonitoreo().get(0).getCodigo();
        String tituloProyecto = "Anlisis" + resLab.getLeyendaMatriz();
        String tipoMuestra = resLab.getLeyendaMatriz();
        String numeroMuestra = Integer.toString(
                MuestraLaboratorio.getNumberMuestraLaboratorio(muestra.getId(), muestra.getIdSiembraCultivo()));
        String numeroMonitoreo = numeroMuestra;
        //String lote = lot.getCodigo();
        String lote = "";
        int nn = muestra.getSiembraCultivo().getListaLotesSiembra().size();
        for (int i = 0; i < nn; i++) {
            lote = lote.concat(muestra.getSiembraCultivo().getListaLotesSiembra().get(i).getLeyendaLote());
        }

        String muestreador = muestra.getMuestreador();
        String fechaMuestreo = muestra.getFechaFormatMuestreo();
        String fechaRecepcionMuestra = muestra.getFechaFormatEnvio();
        String fechaResultado = resLab.getFechaFormatResultado();
        String periodoPrueba = resLab.getFechaFormatRecepcion() + " al " + resLab.getFechaFormatResultado();

        String contenidoHoja1 = TextoReporteResultadoLaboratorio.getByReferencia("HOJA 1 TEXTO INFORME")
                .getDescripcion();
        String responsableTecnico = TextoReporteResultadoLaboratorio.getByReferencia("RESPONSABLE TECNICO")
                .getDescripcion();
        String datosLaboratorio = TextoReporteResultadoLaboratorio.getByReferencia("DATOS LABORATORIO")
                .getDescripcion();
        String piePagina = TextoReporteResultadoLaboratorio.getByReferencia("PIE DE PAGINA").getDescripcion();
        String contenidoHoja2 = TextoReporteResultadoLaboratorio.getByReferencia("HOJA 2 OBSERVACION")
                .getDescripcion();

        //fin obtencion parametros *****************************************************

        /* TODO output your page here. You may use following sample code. */
        float left = 60;
        float right = 30;
        float top = 0;
        float bottom = 0;
        Document document = new Document(PageSize.A4, left, right, top, bottom);
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

        //FOOTER TABLE *****************************************************************
        PdfPTable table = new PdfPTable(1);
        table.setTotalWidth(550);
        PdfPCell cell = new PdfPCell(new Phrase(piePagina, font8Normal));
        cell.setBackgroundColor(BaseColor.GREEN);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("www.agrorum.com.ec", font9BoldWhite));
        cell.setBackgroundColor(BaseColor.ORANGE);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        table.addCell(cell);

        FooterTable event = new FooterTable(table);
        writer.setPageEvent(event);
        //FIN FOOTER TABLE *****************************************************************

        document.open();

        //HOJA 1 *********************************************************************************************************************************                        
        //IMAGE **********************************************************************************
        String relativeWebPathAg = "/images/agrorum.png";
        String absoluteDiskPathAg = getServletContext().getRealPath(relativeWebPathAg);
        Image logoAg = Image.getInstance(absoluteDiskPathAg);
        logoAg.setAbsolutePosition(10f, 750f);
        logoAg.scalePercent(80f);
        document.add(logoAg);

        String relativeWebPathEu = "/images/eurofins.png";
        String absoluteDiskPathEu = getServletContext().getRealPath(relativeWebPathEu);
        Image logoEu = Image.getInstance(absoluteDiskPathEu);
        logoEu.setAbsolutePosition(500f, 770f);
        logoEu.scalePercent(60f);
        document.add(logoEu);
        //FIN IMAGE ********************************************************************************         

        //CLIENTE UBICACION MUESTRA*****************************************************************
        Paragraph parphRepor = new Paragraph("Reporte de anlisis 1/2", font10Normal);
        parphRepor.setAlignment(Element.ALIGN_RIGHT);
        parphRepor.setSpacingBefore(90f);
        Paragraph parphCli = new Paragraph(cliente, font10Bold);
        parphCli.setAlignment(Element.ALIGN_LEFT);
        parphCli.setSpacingBefore(15f);
        Paragraph parphUbi = new Paragraph(ubicacion, font10Bold);
        parphUbi.setAlignment(Element.ALIGN_LEFT);
        parphUbi.setSpacingBefore(15f);
        //PARRAFO combinado con frases********************************************
        Phrase p1 = new Phrase("Cdigo de la Muestra:     ", font10Normal);
        Phrase p2 = new Phrase(codigMuestra, font10Bold);
        Paragraph parphMue = new Paragraph(p1);
        parphMue.add(p2);
        parphMue.setAlignment(Element.ALIGN_LEFT);
        parphMue.setSpacingBefore(15f);
        //FIN PARRAFO combinado***************************************************

        document.add(parphRepor);
        document.add(parphCli);
        document.add(parphUbi);
        document.add(parphMue);

        //FIN CLIENTE UBICACION MUESTRA*************************************************************
        //TABLA ***********************************************************************************
        PdfPTable tableDatos = new PdfPTable(new float[] { 0.20f, 0.80f });
        tableDatos.setWidthPercentage(100);

        tableDatos.addCell(getCell("Propiedad:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(hacienda, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Cultivo Actual:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(cultivo, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Estacin Monitoreo:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(estacionMonitoreo, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Ttulo Proyecto:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(tituloProyecto, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Tipo Muestra:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(tipoMuestra, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Nmero Muestra:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(numeroMuestra, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Nmero Monitoreo:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(numeroMonitoreo, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Lote:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(lote, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Muestreador:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(muestreador.toUpperCase(), PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Fecha Muestreo:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(fechaMuestreo, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Recepcin Muestra:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(fechaRecepcionMuestra, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.addCell(getCell("Perodo de Prueba:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatos.addCell(getCell(periodoPrueba, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatos.setSpacingBefore(20f);
        document.add(tableDatos);
        //FIN TABLA ********************************************************************************

        //CONTENIDO ********************************************************************************
        Paragraph parphCont = new Paragraph(contenidoHoja1, font8Normal);
        parphCont.setAlignment(Element.ALIGN_JUSTIFIED);
        parphCont.setSpacingBefore(20f);

        Paragraph parphLLeida = new Paragraph("LLeida, " + fechaResultado, font8Normal);
        parphLLeida.setAlignment(Element.ALIGN_LEFT);
        parphLLeida.setSpacingBefore(20f);

        Paragraph parphTecnico = new Paragraph(responsableTecnico, font9Bold);
        parphTecnico.setAlignment(Element.ALIGN_LEFT);
        parphTecnico.setSpacingBefore(20f);

        Paragraph parphResponsable = new Paragraph("Responsable Tcnico", font8Normal);
        parphResponsable.setAlignment(Element.ALIGN_LEFT);
        parphResponsable.setSpacingBefore(1f);

        Paragraph parphLaboratorio = new Paragraph(datosLaboratorio, font8Bold);
        parphLaboratorio.setAlignment(Element.ALIGN_LEFT);
        parphLaboratorio.setSpacingBefore(30f);

        document.add(parphCont);
        document.add(parphLLeida);
        document.add(parphTecnico);
        document.add(parphResponsable);
        document.add(parphLaboratorio);
        //FIN CONTENIDO ****************************************************************************

        //FIN HOJA 1 *****************************************************************************************************************************
        document.newPage();

        //HOJA 2 *********************************************************************************************************************************                        
        //IMAGE **********************************************************************************
        String relativeWebPathAg1 = "/images/agrorum.png";
        String absoluteDiskPathAg1 = getServletContext().getRealPath(relativeWebPathAg1);
        Image logoAg1 = Image.getInstance(absoluteDiskPathAg1);
        logoAg1.setAbsolutePosition(10f, 750f);
        logoAg1.scalePercent(80f);
        document.add(logoAg1);

        String relativeWebPathEu1 = "/images/eurofins.png";
        String absoluteDiskPathEu1 = getServletContext().getRealPath(relativeWebPathEu1);
        Image logoEu1 = Image.getInstance(absoluteDiskPathEu1);
        logoEu1.setAbsolutePosition(500f, 770f);
        logoEu1.scalePercent(60f);
        document.add(logoEu1);

        Paragraph ini = new Paragraph("", font12Bold);
        ini.setAlignment(Element.ALIGN_CENTER);
        ini.setSpacingBefore(100f);

        PdfPTable cabT = new PdfPTable(new float[] { 1f });
        cabT.setWidthPercentage(100);
        PdfPCell cellCab = new PdfPCell(new Phrase("Informe de Prueba", font12Bold));
        cellCab.setPadding(2f);
        cellCab.setHorizontalAlignment(Element.ALIGN_CENTER);
        cabT.addCell(cellCab);

        Paragraph parphRep = new Paragraph("Reporte de anlisis 2/2", font10Normal);
        parphRep.setAlignment(Element.ALIGN_RIGHT);

        document.add(ini);
        document.add(cabT);
        document.add(parphRep);

        //TABLA ***********************************************************************************
        PdfPTable tableDatosH2 = new PdfPTable(new float[] { 0.20f, 0.80f });
        tableDatosH2.setWidthPercentage(100);

        tableDatosH2.addCell(getCell("Cliente:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(cliente, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell(" ", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(" ", PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Propiedad:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(hacienda, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Estacin Monitoreo:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(estacionMonitoreo, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Nmero Monitoreo:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(numeroMuestra, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Codigo Muestra:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(codigMuestra, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Matriz:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(tipoMuestra, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Cultivo:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(cultivo, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Variedad:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(varie, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Fecha Muestreo:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(fechaMuestreo, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Recepcin Muestra:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(fechaRecepcionMuestra, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.addCell(getCell("Perodo de Prueba:", PdfPCell.ALIGN_LEFT, font8Normal));
        tableDatosH2.addCell(getCell(periodoPrueba, PdfPCell.ALIGN_LEFT, font8Bold));

        tableDatosH2.setSpacingBefore(20f);
        document.add(tableDatosH2);
        //FIN TABLA ********************************************************************************

        Paragraph parphCont1 = new Paragraph(contenidoHoja2, font8Normal);
        parphCont1.setAlignment(Element.ALIGN_JUSTIFIED);
        parphCont1.setSpacingBefore(20f);

        PdfPTable tableDatosH3 = new PdfPTable(new float[] { 0.30f, 0.70f });
        tableDatosH3.setWidthPercentage(100);

        tableDatosH3.addCell(getCell(datosLaboratorio, PdfPCell.ALIGN_LEFT, font8Bold));

        PdfPTable subTable = new PdfPTable(new float[] { 1f });
        subTable.setWidthPercentage(100);

        subTable.addCell(getCell("LLeida, " + fechaResultado, PdfPCell.ALIGN_CENTER, font8Normal));
        subTable.addCell(getCell(" ", PdfPCell.ALIGN_CENTER, font8Normal));
        subTable.addCell(getCell(" ", PdfPCell.ALIGN_CENTER, font8Normal));
        subTable.addCell(getCell(" ", PdfPCell.ALIGN_CENTER, font8Normal));

        subTable.addCell(getCell(responsableTecnico, PdfPCell.ALIGN_CENTER, font9Bold));
        subTable.addCell(getCell("Responsable Tcnico", PdfPCell.ALIGN_CENTER, font8Normal));

        PdfPCell cellsub = new PdfPCell(subTable);
        cellsub.setBorder(PdfPCell.NO_BORDER);
        cellsub.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        tableDatosH3.addCell(cellsub);

        tableDatosH3.setSpacingBefore(20f);

        document.add(parphCont1);
        document.add(tableDatosH3);

        //FIN IMAGE ********************************************************************************            
        //FIN HOJA 2 *****************************************************************************************************************************
        document.close();
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }
}

From source file:ro.ldir.chartpackage.GarbagePackageBuilder.java

License:Open Source License

public void writePDF(OutputStream out)
        throws DocumentException, MalformedURLException, XPathExpressionException, IOException {
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, "Cp1250", BaseFont.NOT_EMBEDDED);
    final Font hfFont = new Font(bf, 8, Font.NORMAL, BaseColor.GRAY);

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    PdfWriter writer = PdfWriter.getInstance(document, out);
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    writer.setPageEvent(new PdfPageEventHelper() {
        private int page = 0;

        @Override//from  w  ww  .ja  v a2s.c om
        public void onEndPage(PdfWriter writer, Document arg1) {
            page++;
            Rectangle rect = writer.getBoxSize("art");
            ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
                    new Phrase("Pachet mormane - \u00a9 Let's Do It, Romania!", hfFont),
                    (rect.getLeft() + rect.getRight()) / 2, rect.getTop() + 18, 0);
            ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
                    new Phrase("- " + page + " -", hfFont), (rect.getLeft() + rect.getRight()) / 2,
                    rect.getBottom() - 18, 0);
        }
    });

    document.open();
    document.addAuthor("Let's Do It, Romania!");
    document.addTitle("Pachet mormane");
    document.addCreationDate();

    Font titleFont = new Font(bf, 24, Font.BOLD);
    Font noteFont = new Font(bf, 12, Font.NORMAL, BaseColor.RED);
    Font headerFont = new Font(bf, 12, Font.BOLD);
    Font normalFont = new Font(bf, 11);
    Font defFont = new Font(bf, 11, Font.BOLD);
    Paragraph par;
    int page = 0;

    for (Garbage garbage : garbages) {
        par = new Paragraph();
        par.setAlignment(Element.ALIGN_CENTER);
        par.add(new Chunk("Morman " + garbage.getGarbageId() + "\n", titleFont));
        par.add(new Chunk("Citi\u0163i cu aten\u0163ie!", noteFont));
        document.add(par);

        par = new Paragraph();
        par.setSpacingBefore(20);
        par.add(new Chunk("1. Date generale\n", headerFont));
        par.add(new Chunk("Jude\u0163ul: ", defFont));
        par.add(new Chunk(garbage.getCounty().getName() + "\n", normalFont));
        par.add(new Chunk("Comuna: ", defFont));
        par.add(new Chunk(garbage.getTown().getName() + "\n", normalFont));
        if (garbage.getChartedArea() != null) {
            par.add(new Chunk("Zona cartare: ", defFont));
            par.add(new Chunk(garbage.getChartedArea().getName() + "\n", normalFont));
        }
        par.add(new Chunk("Pozi\u0163ie: ", defFont));
        par.add(new Chunk(garbage.getY() + ", " + garbage.getX() + "\n", normalFont));
        par.add(new Chunk("Descriere:\n", defFont));
        par.add(new Phrase(garbage.getDescription() + "\n", normalFont));
        par.add(new Chunk("Componen\u0163\u0103 gunoi:\n", defFont));
        List list = new List();
        list.add(new ListItem(
                new Chunk("Procent plastic: " + garbage.getPercentagePlastic() + "%", normalFont)));
        list.add(new ListItem(
                new Chunk("Procent sticl\u0103: " + garbage.getPercentageGlass() + "%", normalFont)));
        list.add(new ListItem(new Chunk("Procent metale: " + garbage.getPercentageMetal() + "%", normalFont)));
        list.add(new ListItem(
                new Chunk("Procent nereciclabile: " + garbage.getPercentageWaste() + "%", normalFont)));
        par.add(list);
        document.add(par);

        par = new Paragraph();
        par.setSpacingBefore(20);
        par.add(new Chunk("2. Indica\u0163ii rutiere\n", headerFont));
        Image img = Image.getInstance(getImage(garbage));
        img.scaleToFit((float) (PageSize.A4.getWidth() * .75), (float) (PageSize.A4.getHeight() * .75));
        img.setAlignment(Element.ALIGN_CENTER);
        par.add(img);
        document.add(par);

        if (page < garbages.size() - 1)
            document.newPage();
        page++;
    }

    document.close();
}

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

License:Apache License

private PdfPCell renderPdfCell(BandElement bandElement, Object value, int gridRow, int rowSpan, int colSpan,
        boolean image, int column) {
    Map<String, Object> style = buildCellStyleMap(bandElement, value, gridRow, column, colSpan);

    FontFactoryImp fact = new FontFactoryImp();
    com.itextpdf.text.Font fnt;/*from w w  w.j  a v  a2  s .  co  m*/
    if (bandElement != null) {
        fontName = (String) style.get(StyleFormatConstants.FONT_NAME_KEY);
        int size = ((Float) style.get(StyleFormatConstants.FONT_SIZE)).intValue();
        fnt = getFont(size);
    } else {
        fnt = getFont(10);
    }

    PdfPCell cell;
    if (image) {
        if (value == null) {
            cell = new PdfPCell(new Phrase(IMAGE_NOT_FOUND));
        } else {
            ImageBandElement ibe = (ImageBandElement) bandElement;
            try {
                byte[] imageBytes = getImage((String) value);
                cell = getImageCell(ibe, imageBytes, column, colSpan);
            } catch (Exception e) {
                cell = new PdfPCell(new Phrase(IMAGE_NOT_LOADED));
            }
        }
    } 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);
        cell = new PdfPCell(ph);
    } else if (bandElement instanceof ReportBandElement) {
        Report report = ((ReportBandElement) bandElement).getReport();
        ExporterBean eb = null;
        try {
            eb = getSubreportExporterBean(report);
            PdfExporter subExporter = new PdfExporter(eb);
            subExporter.export();
            PdfPTable innerTable = subExporter.getTable();
            cell = new PdfPCell(innerTable);
        } catch (Exception e) {
            cell = new PdfPCell();
            e.printStackTrace();
        } finally {
            if ((eb != null) && (eb.getResult() != null)) {
                eb.getResult().close();
            }
        }
    } else if ((bandElement instanceof VariableBandElement) && (VariableFactory
            .getVariable(((VariableBandElement) bandElement).getVariable()) instanceof TotalPageNoVariable)) {
        try {
            cell = new PdfPCell(Image.getInstance(total));
        } catch (BadElementException e) {
            cell = new PdfPCell(new Phrase("NA"));
        }

    } else if (bandElement instanceof ImageColumnBandElement) {
        try {
            String v = StringUtil.getValueAsString(value, null);
            if (StringUtil.BLOB.equals(v)) {
                cell = new PdfPCell(new Phrase(StringUtil.BLOB));
            } else {
                byte[] bytes = StringUtil.decodeImage(v);
                cell = getImageCell(bandElement, bytes, column, colSpan);
            }
        } catch (Exception e) {
            e.printStackTrace();
            cell = new PdfPCell(new Phrase(IMAGE_NOT_LOADED));
        }
    } else {
        String stringValue;
        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 = "";
        }
        if (stringValue.startsWith("<html>")) {
            StringReader reader = new StringReader(stringValue);
            List<Element> elems = new ArrayList<Element>();
            try {
                elems = HTMLWorker.parseToList(reader, new StyleSheet());
                Phrase ph = new Phrase();
                for (int i = 0; i < elems.size(); i++) {
                    Element elem = (Element) elems.get(i);
                    ph.add(elem);
                }
                cell = new PdfPCell(ph);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Phrase ph = new Phrase(stringValue, fnt);
                cell = new PdfPCell(ph);
            }

        } else {
            Phrase ph = new Phrase(stringValue, fnt);
            cell = new PdfPCell(ph);
        }
    }

    cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
    cell.setUseDescender(true); // needed for a cell without padding
    cell.setMinimumHeight(MINIMUM_HEIGHT); // needed if there is a row in which all cells are empty

    if (bandElement != null) {
        cell.setRotation(bandElement.getTextRotation());
    }

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

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

    if (style != null) {

        updateFont(style, fnt);

        if (style.containsKey(StyleFormatConstants.BACKGROUND_COLOR)) {
            Color val = (Color) style.get(StyleFormatConstants.BACKGROUND_COLOR);
            cell.setBackgroundColor(new BaseColor(val));
        }
        if (style.containsKey(StyleFormatConstants.HORIZONTAL_ALIGN_KEY)) {
            if (StyleFormatConstants.HORIZONTAL_ALIGN_LEFT
                    .equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) {
                cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            }
            if (StyleFormatConstants.HORIZONTAL_ALIGN_RIGHT
                    .equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) {
                cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
            }
            if (StyleFormatConstants.HORIZONTAL_ALIGN_CENTER
                    .equals(style.get(StyleFormatConstants.HORIZONTAL_ALIGN_KEY))) {
                cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            }
        }

        if (style.containsKey(StyleFormatConstants.VERTICAL_ALIGN_KEY)) {
            if (StyleFormatConstants.VERTICAL_ALIGN_TOP
                    .equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) {
                cell.setVerticalAlignment(Element.ALIGN_TOP);
            }
            if (StyleFormatConstants.VERTICAL_ALIGN_MIDDLE
                    .equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) {
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            }
            if (StyleFormatConstants.VERTICAL_ALIGN_BOTTOM
                    .equals(style.get(StyleFormatConstants.VERTICAL_ALIGN_KEY))) {
                cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
            }
        }

        if (style.containsKey(StyleFormatConstants.PADDING_LEFT)) {
            Float val = (Float) style.get(StyleFormatConstants.PADDING_LEFT);
            cell.setPaddingLeft(val);
        }
        if (style.containsKey(StyleFormatConstants.PADDING_RIGHT)) {
            Float val = (Float) style.get(StyleFormatConstants.PADDING_RIGHT);
            cell.setPaddingRight(val);
        }
        if (style.containsKey(StyleFormatConstants.PADDING_TOP)) {
            Float val = (Float) style.get(StyleFormatConstants.PADDING_TOP);
            cell.setPaddingTop(val);
        }
        if (style.containsKey(StyleFormatConstants.PADDING_BOTTOM)) {
            Float val = (Float) style.get(StyleFormatConstants.PADDING_BOTTOM);
            cell.setPaddingBottom(val);
        }
        cell.setBorderWidth(0);

        if (style.containsKey(StyleFormatConstants.BORDER_LEFT)) {
            Float val = (Float) style.get(StyleFormatConstants.BORDER_LEFT);
            cell.setBorderWidthLeft(val / 2);
            Color color = (Color) style.get(StyleFormatConstants.BORDER_LEFT_COLOR);
            cell.setBorderColorLeft(new BaseColor(color));
        }
        if (style.containsKey(StyleFormatConstants.BORDER_RIGHT)) {
            Float val = (Float) style.get(StyleFormatConstants.BORDER_RIGHT);
            cell.setBorderWidthRight(val / 2);
            Color color = (Color) style.get(StyleFormatConstants.BORDER_RIGHT_COLOR);
            cell.setBorderColorRight(new BaseColor(color));
        }
        if (style.containsKey(StyleFormatConstants.BORDER_TOP)) {
            Float val = (Float) style.get(StyleFormatConstants.BORDER_TOP);
            cell.setBorderWidthTop(val / 2);
            Color color = (Color) style.get(StyleFormatConstants.BORDER_TOP_COLOR);
            cell.setBorderColorTop(new BaseColor(color));
        }
        if (style.containsKey(StyleFormatConstants.BORDER_BOTTOM)) {
            Float val = (Float) style.get(StyleFormatConstants.BORDER_BOTTOM);
            cell.setBorderWidthBottom(val / 2);
            Color color = (Color) style.get(StyleFormatConstants.BORDER_BOTTOM_COLOR);
            cell.setBorderColorBottom(new BaseColor(color));
        }

        // for subreports we use default no wrap
        if (cell.getTable() == null) {
            cell.setNoWrap(true);
            if (bandElement != null) {
                if (bandElement.isWrapText()) {
                    cell.setNoWrap(false);
                }
            }
        }

        // to see a background image all cells must not have any background!
        if (bean.getReportLayout().getBackgroundImage() != null) {
            cell.setBackgroundColor(null);
        }
    }
    return cell;
}

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

License:Apache License

private PdfPCell getImageCell(BandElement bandElement, byte[] imageBytes, int column, int colSpan) {
    PdfPCell cell;//from  w  ww . j  a v a2s  . c  o m
    try {
        Image pdfImage = Image.getInstance(imageBytes);
        Integer width = getImageWidth(bandElement);
        Integer height = getImageHeight(bandElement);
        if (isScaled(bandElement)) {

            // scale image (is done in postscript points)
            // if use size
            // if width is less than the cell width (with span)
            // the image is added with its size :
            // new PdfPCell(pdfImage) -> no further scale
            // if width is greater than cell width (with span)
            // the image will fit the cell :
            // cell.setImage(pdfImage); -> does a scale to fit cell
            // if do not use size
            // the image will be added with its size

            float factor = 72f * percentage / (getDPI() * 100);
            pdfImage.scaleAbsolute(width * factor, height * factor);

            int cellWidth = 0;
            for (int i = column; i < column + colSpan; i++) {
                cellWidth += headerwidths[i];
            }
            if ((width.intValue() >= cellWidth) && bean.getReportLayout().isUseSize()) {
                cell = new PdfPCell();
                cell.setImage(pdfImage); // scale to fit cell
            } else {
                cell = new PdfPCell(pdfImage); // do not scale
            }
        } else {
            cell = new PdfPCell(pdfImage);
        }

    } catch (Exception e) {
        e.printStackTrace();
        cell = new PdfPCell(new Phrase(IMAGE_NOT_LOADED));
    }

    return cell;
}

From source file:ryerson.daspub.artifact.PublishQRTagSheetTask.java

License:Open Source License

/**
 * Draw an image on the current page.// w  ww  .  jav  a 2s  .  c  om
 * @param Writer PDF writer
 * @param Img Image data
 * @param x X coordinate of bottom left corner of image
 * @param y Y coordinate of bottom left corner of image
 * @param Width Image width
 * @param Height Image height
 * @throws BadElementException
 * @throws DocumentException 
 * @throws IOException
 * @throws MalformedURLException
 */
private void drawImage(PdfWriter Writer, File Img, int x, int y, int Width, int Height)
        throws BadElementException, MalformedURLException, IOException, DocumentException {
    // resize the image
    byte[] data = ImageUtils.resizeImageToByteArray(Img, Width, Height);
    // place the image
    Image img = Image.getInstance(data);
    img.setAbsolutePosition(x, y);
    Writer.getDirectContent().addImage(img, true);
}

From source file:Sales.SalesController.java

@FXML
private void PrintReciept(MouseEvent event) {
    try {/*from   w  w  w  .j av  a2  s .com*/
        Image im = Image.getInstance("khamals.png");
        FileOutputStream sa = new FileOutputStream("Reciept.pdf");
        im.scaleAbsolute(150f, 150f);
        // im.setAbsolutePosition(25,50);
        im.setBackgroundColor(BaseColor.PINK);
        Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(doc, sa);
        PdfPTable table = new PdfPTable(6);
        String sh = "                                     Date and Time Of Sale : "
                + Calendar.getInstance().getTime().toGMTString() + "\n\n";
        String header = "                                                                 KHAMALS \n"
                + "                                              DESIGNER AND SHOWROOM EXPERT \n "
                + "                                  MOLYKO BUEA  LAST FLOOR ECKO BANK BUILDING\n ";
        String metda = "    INVOICE NUMBER :" + this.RecieptId.getText() + " \n " + "  SALES PERSON ID :"
                + this.CashierName.getText() + " \n   CUSTOMER NAME :" + this.CustomerName.getText() + "\n\n";

        PdfPCell cell = new PdfPCell(new Phrase("\nRECIEPT"));
        cell.setColspan(6);
        cell.setHorizontalAlignment(2);
        doc.open();
        doc.add(im);
        doc.add(cell);
        System.out.println(doc.leftMargin());
        doc.add(new Paragraph(header));
        doc.add(new Paragraph(sh));
        doc.add(new Paragraph(metda));
        table.addCell("S/N");
        table.addCell("PRODUCT NAME");
        table.addCell("DESCRIPTION");
        table.addCell("QUANTITY");
        table.addCell("UNIT PRICE");
        table.addCell("TOTAL PRICE");
        table.setTotalWidth(1000000);
        for (int i = 0; i < Cart.getItems().size(); i++) {
            table.addCell(this.idex.getCellData(i).toString());
            table.addCell(this.p.getCellData(i).toString());
            table.addCell(this.dsc.getCellData(i).toString());
            table.addCell(this.qt.getCellData(i).toString());
            table.addCell(this.p.getCellData(i).toString());
            table.addCell(this.tp.getCellData(i).toString());
        }

        String footer = " \n                                                                                 Total Amount:         "
                + tot.getText() + ""
                + "                                                                                   SIGNATURES \n"
                + "\nCUSTOMER                                      SALES PERSON ";

        doc.add(table);
        doc.add(new Paragraph(footer));
        doc.addCreationDate();
        doc.addAuthor(this.CashierName.getText());
        doc.close();

        Desktop.getDesktop().open(new File("Reciept.pdf"));

    } catch (Exception sd) {
        System.out.println("Error Message :" + sd.getMessage());
    } finally {

    }

}

From source file:Screens.Print.java

public void ConvertPDF() throws DocumentException, FileNotFoundException, UnsupportedEncodingException,
        IOException, ParserConfigurationException, SAXException {
    FontFactory.register("tahoma.ttf", "MY_FONT");
    Document document = new Document(PageSize.A5, 20, 20, 10, 10);
    Image image = Image.getInstance("123.jpg");
    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setBorder(0);
    //        table.setBorderColor(BaseColor.WHITE);

    PdfPTable tablefooter = new PdfPTable(3);
    tablefooter.getDefaultCell().setBorder(0);
    try {/* w  ww. ja  v a2s .c  om*/

        PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        image.setAbsolutePosition(350f, 520f);
        document.add(image);
        document.add(new Paragraph("\n\n        Telefon: " + PrintTel + "\n\n\n",
                FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(
                new Paragraph("Ad, Soyad, ID kod", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(new Paragraph(DataPrint.Ad + " " + DataPrint.Soyad + " (#" + DataPrint.idDaxilOlan + ")",
                FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(new Paragraph("Model, Marka", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(new Paragraph(DataPrint.Model + " " + DataPrint.Marka,
                FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(new Paragraph("Aksesuar", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(
                new Paragraph(DataPrint.Aksesuar, FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(new Paragraph("Problem", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(
                new Paragraph(DataPrint.Problem, FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(new Paragraph("Tarix", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(
                new Paragraph(DataPrint.DatePlan, FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(new Paragraph("Telefon", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        table.addCell(
                new Paragraph(DataPrint.Telefon, FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        document.add(table);
        document.add(
                new Paragraph(jEditorPane1.getText(), FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        //            document.add(new Paragraph(footer, FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        tablefooter.addCell(
                new Paragraph("Thvil Verdi:", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        tablefooter.addCell(new Paragraph("" + DataPrint.Ad + " " + DataPrint.Soyad + "",
                FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        tablefooter.addCell(
                new Paragraph("_____________", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 12)));
        tablefooter.addCell(new Paragraph("  ", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 12)));
        tablefooter.addCell(new Paragraph("  ", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 12)));
        tablefooter.addCell(new Paragraph("  ", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 12)));
        tablefooter.addCell(
                new Paragraph("Thvil ald:", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        tablefooter.addCell(
                new Paragraph("Elxan ?sgrli", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 10)));
        tablefooter.addCell(
                new Paragraph("_____________", FontFactory.getFont("MY_FONT", BaseFont.IDENTITY_H, 12)));
        document.add(tablefooter);
    } catch (FileNotFoundException | DocumentException e) {
    }
    document.close();
}

From source file:se.billes.pdf.renderer.process.TemplatePageRenderer.java

License:Open Source License

public void render(PdfWriter writer, Document document) throws PdfRenderException {
    writer.setPageEvent(page);// w  w w  .j  av  a  2s  . co  m
    Template template = page.getTemplate();

    try {
        PdfReader reader = new PdfReader(template.getTemplatePath());
        PdfImportedPage pageImportedPage = writer.getImportedPage(reader, template.getPage());
        Image pdfMirror;

        float width = SizeFactory.CUT_MARK;
        float height = SizeFactory.CUT_MARK;

        pdfMirror = Image.getInstance(pageImportedPage);
        pdfMirror.setAbsolutePosition(SizeFactory.millimetersToPostscriptPoints(width),
                SizeFactory.millimetersToPostscriptPoints(height));
        document.newPage();
        ImageFactory.getInstances().add(new ImageInstance(pdfMirror, reader));
        PdfContentByte cb = writer.getDirectContent();
        try {
            cb.addImage(pdfMirror);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        if (page.getBlocks() != null) {
            for (BaseElement block : page.getBlocks()) {
                block.onRender(cb);
            }
        }

    } catch (BadElementException e) {
        e.printStackTrace();
        throw new PdfRenderException(e);
    } catch (IOException e) {
        throw new PdfRenderException(e);
    }

}

From source file:se.billes.pdf.renderer.request.factory.ImageFactory.java

License:Open Source License

public ImageInstance getImageByFile(PdfContentByte cb, File file) throws IOException, BadElementException {
    Image image = null;// ww w .  ja v a  2s  . com
    ImageInstance instance = null;
    if (file.getName().toLowerCase().endsWith(".pdf")) {
        PdfReader reader = new PdfReader(file.getAbsolutePath());
        PdfImportedPage p = cb.getPdfWriter().getImportedPage(reader, 1);
        image = Image.getInstance(p);
        instance = new ImageInstance(image, reader);
    } else {
        image = Image.getInstance(file.getAbsolutePath());
        instance = new ImageInstance(image, null);
    }

    instances.add(instance);

    return instance;
}

From source file:se.inera.intyg.rehabstod.service.export.pdf.PageNumberingEventHandler.java

License:Open Source License

/**
 * Adds a header to every page./*from w  ww .ja v a  2  s.c  om*/
 *
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
 *      com.itextpdf.text.Document)
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {

    try {
        PdfPTable table = new PdfPTable(2);

        table.setTotalWidth(document.getPageSize().getWidth());

        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);

        table.addCell(new Phrase(String.valueOf(writer.getPageNumber()), PdfExportConstants.TABLE_CELL_NORMAL));
        PdfPCell cell = new PdfPCell(Image.getInstance(total));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        table.writeSelectedRows(0, -1, document.left(), document.bottom(), writer.getDirectContent());

    } catch (DocumentException de) {
        throw new ExceptionConverter(de);
    }
}