Example usage for com.itextpdf.text.pdf PdfPTable addCell

List of usage examples for com.itextpdf.text.pdf PdfPTable addCell

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfPTable addCell.

Prototype

public void addCell(final Phrase phrase) 

Source Link

Document

Adds a cell element.

Usage

From source file:com.bdaum.zoom.email.internal.job.PdfJob.java

License:Open Source License

private void renderCaptions(int pageNo, int seqNo, int pageItem, PdfPTable table, int ni, String caption) {
    if (!caption.isEmpty()) {
        for (int j = 0; j < layout.getColumns(); j++) {
            int a = (pageNo - 1) * imagesPerPage + ni + j;
            PdfPCell cell;//from ww  w  .ja  va  2  s .co m
            if (a >= assets.size())
                cell = new PdfPCell();
            else {
                String cc = PageProcessor.computeCaption(caption, Constants.PI_ALL, assets.get(a), collection,
                        seqNo + j + 1, pageItem + j + 1);
                Paragraph p = new Paragraph(cc,
                        FontFactory.getFont(FontFactory.HELVETICA, fontSize, Font.NORMAL, BaseColor.DARK_GRAY));
                p.setSpacingBefore(0);
                cell = new PdfPCell(p);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            }
            cell.setBorderWidth(0);
            table.addCell(cell);
        }
    }
}

From source file:com.bdaum.zoom.ui.internal.dialogs.ExhibitionEditDialog.java

License:Open Source License

private void writeDocument(Document document, File targetFile) {
    boolean frame = detailTabfolder.getSelectionIndex() == 1;
    try (FileOutputStream out = new FileOutputStream(targetFile)) {
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();//  w  w  w  .  j  a  va 2s  .  com
        writer.setPageEvent(new PdfPageEventHelper() {
            int pageNo = 0;
            com.itextpdf.text.Font ffont = new com.itextpdf.text.Font(
                    com.itextpdf.text.Font.FontFamily.HELVETICA, 9, com.itextpdf.text.Font.NORMAL,
                    BaseColor.DARK_GRAY);

            @Override
            public void onEndPage(PdfWriter w, Document d) {
                PdfContentByte cb = w.getDirectContent();
                Phrase footer = new Phrase(String.valueOf(++pageNo), ffont);
                ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer,
                        (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom(), 0);
            }
        });
        String tit = NLS.bind(Messages.ExhibitionEditDialog_exhibition_name, nameField.getText());
        Paragraph p = new Paragraph(tit,
                FontFactory.getFont(FontFactory.HELVETICA, 14, com.itextpdf.text.Font.BOLD, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(8);
        document.add(p);
        String subtitle = NLS.bind(Messages.ExhibitionEditDialog_image_list, Constants.DFDT.format(new Date()),
                frame ? Messages.ExhibitionEditDialog_image_sizes : Messages.ExhibitionEditDialog_frame_sizes);
        p = new Paragraph(subtitle,
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(14);
        document.add(p);
        p = new Paragraph(descriptionField.getText(),
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(10);
        document.add(p);
        p = new Paragraph(infoField.getText(),
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(10);
        document.add(p);
        IDbManager db = Core.getCore().getDbManager();
        List<Wall> walls = current.getWall();
        Wall[] sortedWalls = walls.toArray(new Wall[walls.size()]);
        Arrays.sort(sortedWalls, new Comparator<Wall>() {
            public int compare(Wall o1, Wall o2) {
                return o1.getLocation().compareToIgnoreCase(o2.getLocation());
            }
        });
        for (Wall wall : sortedWalls) {
            p = new Paragraph(wall.getLocation(), FontFactory.getFont(FontFactory.HELVETICA, 12,
                    com.itextpdf.text.Font.BOLD, BaseColor.BLACK));
            p.setAlignment(Element.ALIGN_LEFT);
            p.setSpacingAfter(12);
            document.add(p);
            PdfPTable table = new PdfPTable(7);
            // table.setBorderWidth(1);
            // table.setBorderColor(new Color(224, 224, 224));
            // table.setPadding(5);
            // table.setSpacing(0);
            table.setWidths(new int[] { 8, 33, 13, 13, 20, 13, 20 });
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_No, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_title, Element.ALIGN_LEFT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_xpos, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_height, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_size, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_dpi, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader("", Element.ALIGN_LEFT)); //$NON-NLS-1$
            // table.endHeaders();
            List<ExhibitImpl> exhibits = new ArrayList<ExhibitImpl>();
            for (String exhibitId : wall.getExhibit()) {
                ExhibitImpl exhibit = db.obtainById(ExhibitImpl.class, exhibitId);
                if (exhibit != null)
                    exhibits.add(exhibit);
            }
            Collections.sort(exhibits, new Comparator<ExhibitImpl>() {
                public int compare(ExhibitImpl e1, ExhibitImpl e2) {
                    return ((Exhibit) e1).getX() - ((Exhibit) e2).getX();
                }
            });
            int no = 1;
            for (ExhibitImpl exhibit : exhibits) {
                int tara = computeTara(frame, exhibit);
                table.addCell(createTableCell(String.valueOf(no++), Element.ALIGN_RIGHT));
                table.addCell(createTableCell(exhibit.getTitle(), Element.ALIGN_LEFT));
                af.setMaximumFractionDigits(2);
                af.setMinimumFractionDigits(2);
                String x = af.format((exhibit.getX() - tara) / 1000d);
                table.addCell(createTableCell(NLS.bind("{0} m", x), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                String y = af.format((exhibit.getY() + tara) / 1000d);
                table.addCell(createTableCell(NLS.bind("{0} m", y), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                af.setMaximumFractionDigits(1);
                af.setMinimumFractionDigits(1);
                String h = af.format((exhibit.getHeight() + 2 * tara) / 10d);
                int width = exhibit.getWidth();
                String w = af.format((width + 2 * tara) / 10d);
                table.addCell(createTableCell(NLS.bind("{0} x {1} cm", w, h), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                AssetImpl asset = dbManager.obtainAsset(exhibit.getAsset());
                if (asset != null) {
                    int pixels = asset.getWidth();
                    double dpi = pixels * 25.4d / width;
                    table.addCell(createTableCell(String.valueOf((int) dpi), Element.ALIGN_RIGHT));
                } else
                    table.addCell(""); //$NON-NLS-1$
                table.addCell(createTableCell(exhibit.getSold() ? Messages.ExhibitionEditDialog_sold : "", //$NON-NLS-1$
                        Element.ALIGN_LEFT));
            }
            document.add(table);
        }
        document.close();
    } catch (DocumentException e) {
        UiActivator.getDefault().logError(Messages.ExhibitionEditDialog_internal_error_writing_pdf, e);
    } catch (IOException e) {
        UiActivator.getDefault().logError(Messages.ExhibitionEditDialog_io_error_writing_pdf, e);
    }
}

From source file:com.bicitools.dao.RutasDAO.java

public ArrayList obtenerRecoRuta(String usuario, String fechaIni, String fechaFin, String ruta, Document doc) {
    Ruta r = new Ruta();

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date fechaUno, fechaDos;// w ww .ja  va2 s  .c  o  m
    try {
        fechaUno = formatter.parse(fechaIni);
        fechaDos = formatter.parse(fechaFin);
    } catch (ParseException ex) {
        String inputStr = "01-01-1900 00:00:00";
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        try {
            fechaUno = dateFormat.parse(inputStr);
        } catch (Exception miex) {
            fechaUno = new java.util.Date();
        }
        fechaDos = new java.util.Date();
    }

    ArrayList res = new ArrayList();
    Query query = em.createNamedQuery("LogUsuario.findRecorridosRuta");
    query.setParameter("usuario", usuario);
    query.setParameter("fechaIni", fechaUno, TemporalType.TIMESTAMP);
    query.setParameter("fechaFin", fechaDos, TemporalType.TIMESTAMP);
    query.setParameter("rutaActual", ruta);
    Vector qresul = (Vector) query.getResultList();

    if (qresul.size() > 0) {
        try {
            int i;
            ArrayList rta = new ArrayList<>();

            PdfPTable tabla = new PdfPTable(3);

            tabla.addCell("Fecha");
            tabla.addCell("Distancia");
            tabla.addCell("Tiempo");

            for (i = 0; i < qresul.size(); i++) {
                Object[] obj = (Object[]) qresul.get(i);
                //LogUsuario datosRecorrido = (LogUsuario) qresul.get(i);

                RutaPunto puntos = new RutaPunto();
                DatosRutasJson rutaSalida = new DatosRutasJson();

                Date fechaInicio = (Date) obj[1];
                String nombreRecorrido = (String) obj[0];

                if (nombreRecorrido.isEmpty()) {
                    nombreRecorrido = "Recorrido_" + (i + 1);
                }

                rutaSalida.setNombre(nombreRecorrido);

                // Create an instance of SimpleDateFormat used for formatting
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                rutaSalida.setFechaHora(df.format(fechaInicio));

                TiempoDistanciaInfo distRecorrido = obtenerTiempoDistanciaRecorrido((String) obj[2],
                        (Date) obj[1], (String) obj[0]);
                rutaSalida.setDistancia(distRecorrido.getDistancia());
                rutaSalida.setTiempo(distRecorrido.getTiempo());

                /*ArrayList<DatosLugaresJson> lugares = obtenerPuntosRecorrido(
                 (String) obj[2],
                 (Date) obj[1],
                 (String) obj[0]);*/
                //rutaSalida.setLugares(lugares);
                rta.add(rutaSalida);

                tabla.addCell(df.format(fechaInicio));
                tabla.addCell(distRecorrido.getDistancia().replace("\"", ""));
                tabla.addCell(distRecorrido.getDistancia().replace("\"", ""));

            }
            doc.add(tabla);

            //res = ConstruyeRespuesta.construyeRespuestaOk();
            res.add(rta);
        } catch (DocumentException ex) {
            Logger.getLogger(RutasDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        res = null;
    }

    //res.setDescripcion("numero de datos devueltos " + qresul.size());
    return res;
}

From source file:com.bicitools.dao.RutasDAODecorador.java

@Override
public RespuestaJson exportarRutasUsuario(String usuario, String fechaIni, String fechaFin, String archivo) {
    Ruta r = new Ruta();

    RespuestaJson res = new RespuestaJson();
    res = getRutasDAO().exportarRutasUsuario(usuario, fechaIni, fechaFin, archivo);
    Vector qresul = null;//from ww  w  .  j  a  va  2  s  .  c  o m
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date fechaUno, fechaDos;
    try {
        fechaUno = formatter.parse(fechaIni);
        fechaDos = formatter.parse(fechaFin);
    } catch (ParseException ex) {
        String inputStr = "01-01-1900 00:00:00";
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        try {
            fechaUno = dateFormat.parse(inputStr);
        } catch (Exception miex) {
            fechaUno = new java.util.Date();
        }
        fechaDos = new java.util.Date();
    }

    try {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.bicitools_unit");
        EntityManager ema = emf.createEntityManager();

        Query query = ema.createNamedQuery("Ruta.findByUsuarioFechas");
        query.setParameter("usuario", usuario);
        query.setParameter("fechaIni", fechaUno, TemporalType.TIMESTAMP);
        query.setParameter("fechaFin", fechaDos, TemporalType.TIMESTAMP);
        qresul = (Vector) query.getResultList();

        if (qresul.size() > 0) {
            int i = 0;
            ArrayList<DatosRutasReportesJson> rta = new ArrayList<DatosRutasReportesJson>();

            // Se crea el documento
            Document documento = new Document();

            // Se crea el OutputStream para el fichero donde queremos dejar el pdf.
            FileOutputStream ficheroPdf = null;
            //ficheroPdf = new FileOutputStream("/Users/jhony/Documents/Uni Andes/Fabricas/Bicitools/bicitools/reporte.pdf");

            DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy_HHmmss");
            Date fechaReporte = new Date();

            ficheroPdf = new FileOutputStream(
                    archivo + "/Reporte_Rutas_" + usuario + "_" + dateFormat.format(fechaReporte) + ".pdf");

            // Se asocia el documento al OutputStream y se indica que el espaciado entre
            // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
            PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);

            // Se abre el documento.
            documento.open();

            documento.add(new Paragraph("Reporte de Rutas para " + usuario));
            documento.add(new Paragraph(" "));

            Date fechaSalida = fechaUno;

            // Create an instance of SimpleDateFormat used for formatting
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String reportDate = df.format(fechaSalida);
            documento.add(new Paragraph("Fecha Inicial: " + reportDate));
            fechaSalida = fechaDos;
            reportDate = df.format(fechaSalida);
            documento.add(new Paragraph("Fecha Final: " + reportDate));

            documento.add(new Paragraph(" "));
            documento.add(new Paragraph(" "));
            PdfPTable tabla = new PdfPTable(4);
            tabla.addCell("Fecha");
            tabla.addCell("Nombre Ruta");
            tabla.addCell("Tiempo");
            tabla.addCell("Distancia");

            for (i = 0; i < qresul.size(); i++) {
                Ruta miRuta = (Ruta) qresul.get(i);

                fechaSalida = miRuta.getFechaCreacion();

                // Create an instance of SimpleDateFormat used for formatting
                df = new SimpleDateFormat("yyyy-MM-dd");

                reportDate = df.format(fechaSalida);

                tabla.addCell(reportDate);

                RutaPunto puntos = new RutaPunto();
                DatosRutasReportesJson rutaSalida = new DatosRutasReportesJson();
                //ruta

                tabla.addCell(miRuta.getNombre());

                ArrayList<DatosLugaresJson> lugares = obtenerPuntosRutaUsuario(miRuta.getNombre());
                rutaSalida.setLugares(lugares);

                RutaPunto puntoUno = new RutaPunto();
                RutaPunto puntoDos = new RutaPunto();

                //ruta 1
                rutaSalida.setNombre(miRuta.getNombre());

                rutaSalida.setFechaHora(miRuta.getFechaCreacion().toString());

                //obtiene primer y ultimo punto
                puntoUno = obtenerPuntoRutaIndiceUsuario(miRuta.getNombre(), 0);
                puntoDos = obtenerPuntoRutaIndiceUsuario(miRuta.getNombre(), -1);

                if (puntoUno != null && puntoDos != null) {

                    //consumeServicio Tiempo y distancia
                    final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
                    DatosConsumoPuntoRutaJson entrada = new DatosConsumoPuntoRutaJson();

                    entrada.setLatitudOrigen(Double.parseDouble(puntoUno.getLatitud()));
                    entrada.setLongitudOrigen(Double.parseDouble(puntoUno.getLongitud()));
                    entrada.setLatitudDestino(Double.parseDouble(puntoDos.getLatitud()));
                    entrada.setLongitudDestino(Double.parseDouble(puntoDos.getLongitud()));
                    final String representacionBonita = prettyGson.toJson(entrada);

                    res = ConsumeServicios.consumeTiempoDist(representacionBonita);

                    if (res.getCodigo() == 0) {

                        ArrayList<TiempoDistanciaInfo> datos = new ArrayList<>();
                        TiempoDistanciaInfo infoRuta = new TiempoDistanciaInfo();
                        datos = res.getDatos();
                        infoRuta = (TiempoDistanciaInfo) datos.get(0);

                        tabla.addCell(infoRuta.getTiempo().replace("\"", ""));
                        tabla.addCell(infoRuta.getDistancia().replace("\"", ""));
                        //rutaSalida.setDistancia(infoRuta.getDistancia());
                        //rutaSalida.setTiempo(infoRuta.getTiempo());

                        //rta.add(rutaSalida);
                        //res.setDatos(rta);
                    }
                } else {
                    tabla.addCell("ND");
                    tabla.addCell("ND");
                }
            }

            documento.add(tabla);

            documento.add(new Paragraph(" "));
            try {
                Image foto = Image.getInstance(
                        "http://1.bp.blogspot.com/-fV-ThFg9bN0/UCr4VMFrJ-I/AAAAAAAAEYQ/-_vIDIYDLz8/s1600/dibujo-pintar-doki-bicicleta.jpg");
                foto.scaleToFit(100, 100);
                foto.setAlignment(Chunk.ALIGN_CENTER);
                documento.add(foto);
            } catch (IOException | DocumentException e) {
            }
            res = ConstruyeRespuesta.construyeRespuestaOk();

            documento.close();
        } else {
            res = ConstruyeRespuesta.construyeRespuestaFalla("no hay datos " + qresul.size());
        }

    } catch (FileNotFoundException | DocumentException | NumberFormatException ex) {
        res = ConstruyeRespuesta.construyeRespuestaFalla("error " + ex.getMessage());

    }

    //res.setDescripcion("numero de datos devueltos " + qresul.size());
    return res;
}

From source file:com.bicitools.dao.RutasDAODecorador.java

@Override
public RespuestaJson exportarRecorridosUsuario(String usuario, String fechaIni, String fechaFin,
        String archivo) {/* w w w . j av  a 2  s .  co  m*/

    RespuestaJson res = new RespuestaJson();
    res = getRutasDAO().exportarRecorridosUsuario(usuario, fechaIni, fechaFin, archivo);
    Ruta r = new Ruta();

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date fechaUno, fechaDos;
    try {
        fechaUno = formatter.parse(fechaIni);
        fechaDos = formatter.parse(fechaFin);
    } catch (ParseException ex) {
        String inputStr = "01-01-1900 00:00:00";
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        try {
            fechaUno = dateFormat.parse(inputStr);
        } catch (Exception miex) {
            fechaUno = new java.util.Date();
        }
        fechaDos = new java.util.Date();
    }

    Query query = em.createNamedQuery("LogUsuario.findRecorridos");
    query.setParameter("usuario", usuario);
    query.setParameter("fechaIni", fechaUno, TemporalType.TIMESTAMP);
    query.setParameter("fechaFin", fechaDos, TemporalType.TIMESTAMP);
    Vector qresul = (Vector) query.getResultList();

    if (qresul.size() > 0) {
        try {
            int i;
            ArrayList<DatosRutasReportesJson> rta = new ArrayList<>();

            Document documento = new Document();

            // Se crea el OutputStream para el fichero donde queremos dejar el pdf.
            FileOutputStream ficheroPdf = null;
            //ficheroPdf = new FileOutputStream("/Users/jhony/Documents/Uni Andes/Fabricas/Bicitools/bicitools/reporte.pdf");

            DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy_HHmmss");
            Date fechaReporte = new Date();

            ficheroPdf = new FileOutputStream(archivo + "/Reporte_Recorridos_" + usuario + "_"
                    + dateFormat.format(fechaReporte) + ".pdf");

            // Se asocia el documento al OutputStream y se indica que el espaciado entre
            // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
            PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);

            // Se abre el documento.
            documento.open();

            documento.add(new Paragraph("Reporte de Recorridos para " + usuario));
            documento.add(new Paragraph(" "));

            Date fechaSalida = fechaUno;

            // Create an instance of SimpleDateFormat used for formatting
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String reportDate = df.format(fechaSalida);
            documento.add(new Paragraph("Fecha Inicial: " + reportDate));
            fechaSalida = fechaDos;
            reportDate = df.format(fechaSalida);
            documento.add(new Paragraph("Fecha Final: " + reportDate));

            documento.add(new Paragraph(" "));
            documento.add(new Paragraph(" "));
            PdfPTable tabla = new PdfPTable(4);

            tabla.addCell("Fecha");
            tabla.addCell("Tiempo");
            tabla.addCell("Distancia");
            tabla.addCell("Ruta");

            for (i = 0; i < qresul.size(); i++) {
                Object[] obj = (Object[]) qresul.get(i);
                //LogUsuario datosRecorrido = (LogUsuario) qresul.get(i);

                RutaPunto puntos = new RutaPunto();
                //DatosRutasReportesJson rutaSalida = new DatosRutasReportesJson();

                Date fechaInicio = (Date) obj[1];
                String nombreRecorrido = (String) obj[0];

                if (nombreRecorrido.isEmpty()) {
                    nombreRecorrido = "Recorrido_" + (i + 1);
                }

                //rutaSalida.setNombre(nombreRecorrido);
                //rutaSalida.setFechaHora(fechaInicio.toString());
                fechaSalida = fechaInicio;
                // Create an instance of SimpleDateFormat used for formatting
                df = new SimpleDateFormat("yyyy-MM-dd");
                reportDate = df.format(fechaSalida);
                tabla.addCell(reportDate);

                TiempoDistanciaInfo distRecorrido = obtenerTiempoDistanciaRecorrido((String) obj[2],
                        (Date) obj[1], (String) obj[0]);
                //rutaSalida.setDistancia(distRecorrido.getDistancia());
                //rutaSalida.setTiempo(distRecorrido.getTiempo());

                tabla.addCell(distRecorrido.getTiempo().replace("\"", ""));
                tabla.addCell(distRecorrido.getDistancia().replace("\"", ""));
                tabla.addCell(nombreRecorrido);
                /*ArrayList<DatosLugaresJson> lugares = obtenerPuntosRecorrido(
                 (String) obj[2],
                 (Date) obj[1],
                 (String) obj[0]);
                        
                        
                 rutaSalida.setLugares(lugares);
                 rta.add(rutaSalida);*/

            }

            documento.add(tabla);
            documento.add(new Paragraph(" "));
            try {
                Image foto = Image.getInstance(
                        "http://1.bp.blogspot.com/-fV-ThFg9bN0/UCr4VMFrJ-I/AAAAAAAAEYQ/-_vIDIYDLz8/s1600/dibujo-pintar-doki-bicicleta.jpg");
                foto.scaleToFit(100, 100);
                foto.setAlignment(Chunk.ALIGN_CENTER);
                documento.add(foto);
            } catch (IOException | DocumentException e) {
            }

            res = ConstruyeRespuesta.construyeRespuestaOk();
            documento.close();

            //res.setDatos(rta);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RutasDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DocumentException ex) {
            Logger.getLogger(RutasDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        res = ConstruyeRespuesta.construyeRespuestaFalla("no hay datos " + qresul.size());
    }

    res.setDescripcion("numero de datos devueltos " + qresul.size());
    return res;

}

From source file:com.bicitools.dao.RutasDAODecorador.java

@Override
public RespuestaJson exportarRecorridosRuta(String usuario, String fechaIni, String fechaFin, String archivo) {

    Ruta r = new Ruta();
    RespuestaJson res = new RespuestaJson();
    res = getRutasDAO().exportarRecorridosRuta(usuario, fechaIni, fechaFin, archivo);
    Vector qresul = null;/*from w w  w  . j a v  a2s.c  om*/
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date fechaUno, fechaDos;
    try {
        fechaUno = formatter.parse(fechaIni);
        fechaDos = formatter.parse(fechaFin);
    } catch (ParseException ex) {
        String inputStr = "01-01-1900 00:00:00";
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        try {
            fechaUno = dateFormat.parse(inputStr);
        } catch (Exception miex) {
            fechaUno = new java.util.Date();
        }
        fechaDos = new java.util.Date();
    }

    try {

        Query query = em.createNamedQuery("Ruta.findByUsuarioFechas");
        query.setParameter("usuario", usuario);
        query.setParameter("fechaIni", fechaUno, TemporalType.TIMESTAMP);
        query.setParameter("fechaFin", fechaDos, TemporalType.TIMESTAMP);
        qresul = (Vector) query.getResultList();

        if (qresul.size() > 0) {
            int i;
            ArrayList rta = new ArrayList();

            // Se crea el documento
            Document documento = new Document();

            // Se crea el OutputStream para el fichero donde queremos dejar el pdf.
            FileOutputStream ficheroPdf = null;
            //ficheroPdf = new FileOutputStream("/Users/jhony/Documents/Uni Andes/Fabricas/Bicitools/bicitools/reporte.pdf");

            DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy_HHmmss");
            Date fechaReporte = new Date();

            ficheroPdf = new FileOutputStream(archivo + "/Reporte_RutasRecorridos_" + usuario + "_"
                    + dateFormat.format(fechaReporte) + ".pdf");

            // Se asocia el documento al OutputStream y se indica que el espaciado entre
            // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
            PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);

            // Se abre el documento.
            documento.open();

            documento.add(new Paragraph("Reporte de Recorridos por Ruta para " + usuario));
            documento.add(new Paragraph(" "));

            Date fechaSalida = fechaUno;

            // Create an instance of SimpleDateFormat used for formatting
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String reportDate = df.format(fechaSalida);
            documento.add(new Paragraph("Fecha Inicial: " + reportDate));
            fechaSalida = fechaDos;
            reportDate = df.format(fechaSalida);
            documento.add(new Paragraph("Fecha Final: " + reportDate));

            documento.add(new Paragraph(" "));
            documento.add(new Paragraph(" "));

            for (i = 0; i < qresul.size(); i++) {
                PdfPTable tabla = new PdfPTable(3);

                Ruta miRuta = (Ruta) qresul.get(i);
                RutaPunto puntos = new RutaPunto();
                DatosRutasRecorridosJson rutaSalida = new DatosRutasRecorridosJson();
                //ruta

                //ArrayList<DatosLugaresJson> lugares = obtenerPuntosRutaUsuario(miRuta.getNombre());
                //rutaSalida.setLugares(lugares);
                RutaPunto puntoUno;
                RutaPunto puntoDos;

                //ruta 1
                rutaSalida.setNombre(miRuta.getNombre());
                // Create an instance of SimpleDateFormat used for formatting 
                df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                rutaSalida.setFechaHora(df.format(miRuta.getFechaCreacion()));

                //obtiene primer y ultimo punto
                puntoUno = obtenerPuntoRutaIndiceUsuario(miRuta.getNombre(), 0);
                puntoDos = obtenerPuntoRutaIndiceUsuario(miRuta.getNombre(), -1);

                //consumeServicio Tiempo y distancia
                final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
                DatosConsumoPuntoRutaJson entrada = new DatosConsumoPuntoRutaJson();

                entrada.setLatitudOrigen(Double.parseDouble(puntoUno.getLatitud()));
                entrada.setLongitudOrigen(Double.parseDouble(puntoUno.getLongitud()));
                entrada.setLatitudDestino(Double.parseDouble(puntoDos.getLatitud()));
                entrada.setLongitudDestino(Double.parseDouble(puntoDos.getLongitud()));
                final String representacionBonita = prettyGson.toJson(entrada);

                res = ConsumeServicios.consumeTiempoDist(representacionBonita);

                if (res.getCodigo() == 0) {

                    ArrayList<TiempoDistanciaInfo> datos;
                    TiempoDistanciaInfo infoRuta;

                    datos = res.getDatos();

                    infoRuta = (TiempoDistanciaInfo) datos.get(0);

                    //rutaSalida.setDistancia(infoRuta.getDistancia().replace("\"",""));
                    //rutaSalida.setTiempo(infoRuta.getTiempo().replace("\"",""));
                    documento.add(new Paragraph("Nombre: " + miRuta.getNombre()));
                    documento.add(
                            new Paragraph("Distancia calculada: " + infoRuta.getDistancia().replace("\"", "")));
                    documento.add(new Paragraph("Tiempo estimado: " + infoRuta.getTiempo().replace("\"", "")));
                    documento.add(new Paragraph("-------Recorridos-----"));
                    documento.add(new Paragraph(" "));
                    tabla.addCell(infoRuta.getDistancia().replace("\"", ""));
                    tabla.addCell(infoRuta.getTiempo().replace("\"", ""));

                    rutaSalida.setRecorridos(obtenerRecoRuta(usuario, fechaIni, fechaFin, miRuta.getNombre()));
                    documento.add(new Paragraph("---------------------"));
                    documento.add(new Paragraph(" "));
                    rta.add(rutaSalida);
                    res = ConstruyeRespuesta.construyeRespuestaOk();
                    //res.setDatos(rta);

                    documento.add(tabla);
                }

            }
            documento.add(new Paragraph(" "));
            try {
                Image foto = Image.getInstance(
                        "http://1.bp.blogspot.com/-fV-ThFg9bN0/UCr4VMFrJ-I/AAAAAAAAEYQ/-_vIDIYDLz8/s1600/dibujo-pintar-doki-bicicleta.jpg");
                foto.scaleToFit(100, 100);
                foto.setAlignment(Chunk.ALIGN_CENTER);
                documento.add(foto);
            } catch (IOException | DocumentException e) {
            }
            documento.close();

        } else {
            res = ConstruyeRespuesta.construyeRespuestaFalla("no hay datos " + qresul.size());
        }
    } catch (Exception ex) {
        res = ConstruyeRespuesta.construyeRespuestaFalla("error " + ex.getMessage());

    }
    //res.setDescripcion("numero de datos devueltos " + qresul.size());
    return res;
}

From source file:com.bicitools.dao.RutasDAODecorador.java

@Override
public RespuestaJson exportarReporteMetricasUsuario(String usuario, String fechaIni, String fechaFin,
        String archivo) {/*from   w w w  . ja  va 2  s .com*/
    RespuestaJson res = new RespuestaJson();
    res = getRutasDAO().exportarReporteMetricasUsuario(usuario, fechaIni, fechaFin, archivo);

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date fechaUno, fechaDos;
    try {
        fechaUno = formatter.parse(fechaIni);
        fechaDos = formatter.parse(fechaFin);
    } catch (ParseException ex) {
        String inputStr = "01-01-1900 00:00:00";
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        try {
            fechaUno = dateFormat.parse(inputStr);
        } catch (Exception miex) {
            fechaUno = new java.util.Date();
        }
        fechaDos = new java.util.Date();
    }

    Query query = em.createNamedQuery("Ruta.findMetricasByUsuario");
    query.setParameter("usuario", usuario);
    query.setParameter("fechaIni", fechaUno, TemporalType.TIMESTAMP);
    query.setParameter("fechaFin", fechaDos, TemporalType.TIMESTAMP);
    List<Object[]> qresul = query.getResultList();

    if (qresul.size() > 0) {

        try {

            // Se crea el documento
            Document documento = new Document();

            // Se crea el OutputStream para el fichero donde queremos dejar el pdf.
            FileOutputStream ficheroPdf = null;
            //ficheroPdf = new FileOutputStream("/Users/jhony/Documents/Uni Andes/Fabricas/Bicitools/bicitools/reporte.pdf");

            DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy_HHmmss");
            Date fechaReporte = new Date();

            ficheroPdf = new FileOutputStream(
                    archivo + "/Reporte_" + usuario + "_" + dateFormat.format(fechaReporte) + ".pdf");

            // Se asocia el documento al OutputStream y se indica que el espaciado entre
            // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
            PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);

            // Se abre el documento.
            documento.open();

            documento.add(new Paragraph("Reporte de Actividad para " + usuario));
            documento.add(new Paragraph(" "));
            /*documento.add(new Paragraph("Este es el segundo y tiene una fuente rara",
             FontFactory.getFont("arial", // fuente
             22, // tamao
             Font.ITALIC, // estilo
             BaseColor.CYAN)));             // color
             */

            documento.add(new Paragraph("Fecha Inicial: " + fechaUno));
            documento.add(new Paragraph("Fecha Final: " + fechaDos));

            documento.add(new Paragraph(" "));
            documento.add(new Paragraph(" "));
            PdfPTable tabla = new PdfPTable(3);
            tabla.addCell("Fecha");
            tabla.addCell("Tiempo");
            tabla.addCell("Distancia");

            int distanciaTotal = 0, tiempoTotal = 0;
            ArrayList<DatosMetricasReportesJson> rta = new ArrayList<>();
            ArrayList<DatosMetricasUsuarioJson> lista = new ArrayList<>();
            DatosMetricasReportesJson salida = new DatosMetricasReportesJson();
            MetricasUsuario total = new MetricasUsuario();
            lista.clear();

            for (Object[] object : qresul) {
                Date fechaSalida = (Date) object[2];

                // Create an instance of SimpleDateFormat used for formatting
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                String reportDate = df.format(fechaSalida);

                tabla.addCell(reportDate);
                tabla.addCell((String) object[1]);
                tabla.addCell((String) object[0]);

                distanciaTotal += Integer.parseInt((String) object[0]);
                tiempoTotal += Integer.parseInt((String) object[1]);

            }

            documento.add(tabla);

            documento.add(new Paragraph(" "));

            documento.add(new Paragraph("Tiempo Total: " + tiempoTotal));
            documento.add(new Paragraph("Distancia Total: " + distanciaTotal));

            documento.add(new Paragraph(" "));
            try {
                Image foto = Image.getInstance(
                        "http://1.bp.blogspot.com/-fV-ThFg9bN0/UCr4VMFrJ-I/AAAAAAAAEYQ/-_vIDIYDLz8/s1600/dibujo-pintar-doki-bicicleta.jpg");
                foto.scaleToFit(100, 100);
                foto.setAlignment(Chunk.ALIGN_CENTER);
                documento.add(foto);
            } catch (Exception e) {
                e.printStackTrace();
            }
            res = ConstruyeRespuesta.construyeRespuestaOk();

            documento.close();
            //res.setDatos(rta);

        } catch (DocumentException ex) {
            Logger.getLogger(RutasDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RutasDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else {
        res = ConstruyeRespuesta.construyeRespuestaFalla("no hay datos " + qresul.size());
    }

    return res;
}

From source file:com.bougsid.printers.PrintMission.java

public void printMission(Mission mission) {
    Document document = new Document(PageSize.A4);
    try {//from  ww w. j  a  va  2s . c o  m
        File downloadDir = new File(msg.getMessage("application.mission.downloaddir"));
        if (!downloadDir.exists()) {
            downloadDir.mkdir();
        }
        System.out.println("Dir =" + downloadDir.getPath());
        PdfWriter.getInstance(document,
                new FileOutputStream(downloadDir.getPath() + "/" + mission.getUuid() + ".pdf"));
        document.open();
        Paragraph p = new Paragraph();
        p.setSpacingAfter(60);
        document.add(p);
        //header
        Paragraph paragraph = new Paragraph(
                msg.getMessage("mission.pdf.school") + "       " + mission.getIdMission() + "           ",
                DEFAULT_FONT);
        Phrase phrase = new Phrase(msg.getMessage("mission.pdf.city") + " "
                + LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
        paragraph.add(phrase);
        paragraph.setSpacingAfter(50);
        document.add(paragraph);
        //title
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(40);
        PdfPCell cell = new PdfPCell(new Phrase(msg.getMessage("mission.pdf.title"),
                FontFactory.getFont(FontFactory.HELVETICA, 18)));
        cell.setBorderWidth(1);
        cell.setPadding(10);

        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.setSpacingAfter(40);
        document.add(table);

        //content
        table = new PdfPTable(2);
        table.setWidthPercentage(100);

        //line 1
        cell = new PdfPCell(new Paragraph(mission.getEmploye().getCivilite().getLabel(), DEFAULT_FONT_BOLD));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(": " + mission.getEmploye().getFullName(), DEFAULT_FONT));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);

        //line 2
        cell = new PdfPCell(new Paragraph(msg.getMessage("mission.pdf.matricule"), DEFAULT_FONT_BOLD));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(": " + mission.getEmploye().getMatricule(), DEFAULT_FONT));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);

        //line 3
        cell = new PdfPCell(new Paragraph(msg.getMessage("mission.pdf.grade"), DEFAULT_FONT_BOLD));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(": " + mission.getEmploye().getFonction(), DEFAULT_FONT));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);

        if (mission.getEntreprise() != null) {
            //line 4
            cell = new PdfPCell(new Paragraph(msg.getMessage("mission.pdf.text_1"), DEFAULT_FONT_BOLD));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setPaddingTop(20);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(msg.getMessage("mission.pdf.text_1_2"), DEFAULT_FONT_BOLD));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setPaddingTop(20);
            table.addCell(cell);

            //line 5
            cell = new PdfPCell(new Paragraph(" ", DEFAULT_FONT_BOLD));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setPaddingTop(20);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(" - " + mission.getEntreprise().getNom(), DEFAULT_FONT));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setPaddingTop(20);
            table.addCell(cell);
        }

        //line 6
        cell = new PdfPCell(new Paragraph(msg.getMessage("mission.pdf.lieu"), DEFAULT_FONT_BOLD));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);
        p = new Paragraph();
        p.setFont(DEFAULT_FONT);
        for (Ville ville : mission.getVilles()) {
            p.add(ville.getNom() + "\n");
        }
        cell = new PdfPCell(p);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);

        //line 7
        cell = new PdfPCell(new Paragraph(msg.getMessage("mission.pdf.startdate"), DEFAULT_FONT_BOLD));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(
                ": " + mission.getStartDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "    Heure : "
                        + mission.getStartDate().format(DateTimeFormatter.ofPattern("HH:mm")),
                DEFAULT_FONT));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);

        //line 8
        cell = new PdfPCell(new Paragraph(msg.getMessage("mission.pdf.enddate"), DEFAULT_FONT_BOLD));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(
                ": " + mission.getEndDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "    Heure : "
                        + mission.getEndDate().format(DateTimeFormatter.ofPattern("HH:mm")),
                DEFAULT_FONT));

        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);

        //line 9
        cell = new PdfPCell(new Paragraph(msg.getMessage("mission.pdf.transport"), DEFAULT_FONT_BOLD));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);
        switch (mission.getTransportType()) {
        case PERSONNEL:
            cell = new PdfPCell(new Paragraph(": " + msg.getMessage("mission.pdf.perso") + " "
                    + mission.getEmploye().getVehicule().getMarque() + " " + msg.getMessage("mission.pdf.mat")
                    + " " + mission.getEmploye().getVehicule().getMatricule() + " ", DEFAULT_FONT));
            break;
        case Accompagnement:
            cell = new PdfPCell(new Paragraph(": " + msg.getMessage("mission.pdf.accomp") + " "
                    + mission.getAccompEmploye().getCivilite() + " " + mission.getAccompEmploye().getFullName()
                    + " " + msg.getMessage("mission.pdf.accomp.voitue") + " "
                    + mission.getAccompEmploye().getVehicule().getMarque() + " "
                    + msg.getMessage("mission.pdf.mat") + " "
                    + mission.getAccompEmploye().getVehicule().getMatricule() + " ", DEFAULT_FONT));
            break;
        case Service:
            cell = new PdfPCell(new Paragraph(": " + msg.getMessage("mission.pdf.service") + " "
                    + mission.getEmploye().getVehicule().getMarque() + " " + msg.getMessage("mission.pdf.mat")
                    + " " + mission.getEmploye().getVehicule().getMatricule() + " ", DEFAULT_FONT));
            break;
        default: {
            cell = new PdfPCell(new Paragraph(
                    ": " + mission.getTransportType().getLabel() + " " + msg.getMessage("mission.pdf.taxi"),
                    DEFAULT_FONT));
        }
        }
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(20);
        table.addCell(cell);

        table.setSpacingAfter(40);
        document.add(table);

        //note
        document.add(new Paragraph(msg.getMessage("mission.pdf.TEXT_2"), DEFAULT_FONT));

        //signature
        if (mission.getEmploye().getGrade().getType() == GradeType.DG) {

        } else {
            Employe dir = employeService.getDG();
            if (dir != null)
                paragraph = new Paragraph(dir.getFullName(), DEFAULT_FONT);
            paragraph.setAlignment(Element.ALIGN_RIGHT);
            paragraph.setSpacingBefore(40);
            document.add(paragraph);
            paragraph = new Paragraph(msg.getMessage("mission.pdf.DG"), DEFAULT_FONT);
            paragraph.setAlignment(Element.ALIGN_RIGHT);
            document.add(paragraph);
        }

    } catch (DocumentException ex) {
        ex.printStackTrace();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
    document.close();
    //        try {
    //            Desktop.getDesktop().open(new File("./order.pdf"));
    //        } catch (IOException ex) {
    //            JOptionPane.showMessageDialog(null, "Fichier gner mais ne peut pas etre ouvert vrifier le dossier");
    //        }
}

From source file:com.carfinance.module.common.controller.DocumentDownloadController.java

/**
 * ??// w ww  .  java 2 s. c  o  m
 * @param model
 * @param request
 * @param response
 */
@RequestMapping(value = "/pdfhunchecontrace", method = RequestMethod.GET)
public void pdfHuncheContrace(Model model, HttpServletRequest request, HttpServletResponse response) {
    String contrace_id_str = request.getParameter("contrace_id");

    String org_id = "";
    String contrace_no = "";
    String customer_name = "";
    String vehicle_id = "";
    String daily_available_km = "";

    VehicleContraceInfo vehicleContraceInfo = this.vehicleServiceManageService
            .getVehicleContraceInfoById(Long.valueOf(contrace_id_str));
    if (vehicleContraceInfo != null) {
        org_id = String.valueOf(vehicleContraceInfo.getOrg_id());
        contrace_no = vehicleContraceInfo.getContrace_no();
        customer_name = vehicleContraceInfo.getCustomer_name();
        daily_available_km = vehicleContraceInfo.getDaily_available_km() + "";
    } else {
        PropertyContraceInfo propertyContraceInfo = this.vehicleServiceManageService
                .getPropertyContraceInfoById(Long.valueOf(contrace_id_str));
        if (propertyContraceInfo != null) {
            org_id = String.valueOf(propertyContraceInfo.getOrg_id());
            contrace_no = propertyContraceInfo.getContrace_no();
            customer_name = propertyContraceInfo.getCustomer_name();
        }
    }

    List<VehicleContraceVehsInfo> vehicleContraceVehsInfoList = this.vehicleServiceManageService
            .getVehicleContraceVehsListByContraceId(Long.valueOf(contrace_id_str));

    //1.ContentType
    response.setContentType("multipart/form-data");
    //2.????(??a.pdf)
    response.setHeader("Content-Disposition", "attachment;fileName=" + contrace_no + ".pdf");

    Document pdfDoc = new Document(PageSize.A4, 50, 50, 50, 50);
    // ?? pdf ?
    try {
        BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);

        Font bold_fontChinese = new Font(bfChinese, 18, Font.BOLD, BaseColor.BLACK);
        Font normal_fontChinese = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK);
        Font normal_desc_fontChinese = new Font(bfChinese, 6, Font.NORMAL, BaseColor.BLACK);

        FileOutputStream pdfFile = new FileOutputStream(
                new File(appProps.get("hunche.contrace.download.path") + contrace_no + ".pdf"));
        // pdf ?
        Paragraph paragraph1 = new Paragraph("???", bold_fontChinese);
        paragraph1.setAlignment(Element.ALIGN_CENTER);

        Paragraph paragraph2 = new Paragraph(
                "???", normal_fontChinese);
        Paragraph paragraph3 = new Paragraph("" + customer_name + " (",
                normal_fontChinese);
        Paragraph paragraph4 = new Paragraph(
                "?????________________???",
                normal_fontChinese);
        Paragraph paragraph5 = new Paragraph("??????",
                normal_fontChinese);
        // table
        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100);
        table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        PdfPCell cell = new PdfPCell();
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        // 
        cell.setPhrase(new Paragraph("?", normal_fontChinese));
        table.addCell(cell);
        cell.setPhrase(new Paragraph("", normal_fontChinese));
        table.addCell(cell);
        cell.setPhrase(new Paragraph("?/", normal_fontChinese));
        table.addCell(cell);
        cell.setPhrase(new Paragraph("?", normal_fontChinese));
        table.addCell(cell);
        // ?
        for (VehicleContraceVehsInfo v : vehicleContraceVehsInfoList) {

            PdfPCell newcell = new PdfPCell();
            newcell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            newcell.setPhrase(new Paragraph("1", normal_fontChinese));
            table.addCell(newcell);
            newcell.setPhrase(new Paragraph(v.getModel(), normal_fontChinese));
            table.addCell(newcell);
            newcell.setPhrase(new Paragraph(v.getDaily_price() + "", normal_fontChinese));
            table.addCell(newcell);
            newcell.setPhrase(new Paragraph(daily_available_km, normal_fontChinese));
            table.addCell(newcell);
        }

        Paragraph paragraph6 = new Paragraph(
                "??_________________________________________________________________",
                normal_fontChinese);
        Paragraph paragraph7 = new Paragraph(
                "____________________________?______",
                normal_fontChinese);
        Paragraph paragraph8 = new Paragraph("????", normal_fontChinese);
        Paragraph paragraph9 = new Paragraph(
                "???________________________???________________________",
                normal_fontChinese);
        Paragraph paragraph10 = new Paragraph("?", normal_fontChinese);
        Paragraph paragraph11 = new Paragraph(
                "???????????????",
                normal_fontChinese);
        Paragraph paragraph12 = new Paragraph("?", normal_fontChinese);
        Paragraph paragraph13 = new Paragraph(
                "??????????????",
                normal_fontChinese);
        Paragraph paragraph14 = new Paragraph(
                "?????????",
                normal_fontChinese);
        Paragraph paragraph15 = new Paragraph("?????",
                normal_fontChinese);
        Paragraph paragraph16 = new Paragraph(
                "(/)                                       (/)",
                normal_fontChinese);
        Paragraph paragraph17 = new Paragraph(
                "                                                      ??", normal_fontChinese);
        Paragraph paragraph18 = new Paragraph(
                "??                                               ??  ",
                normal_fontChinese);
        Paragraph paragraph19 = new Paragraph(
                "                                                      201          ",
                normal_fontChinese);

        //  Document ?File  PdfWriter ?
        PdfWriter.getInstance(pdfDoc, pdfFile);
        pdfDoc.open(); //  Document 

        // ??
        pdfDoc.add(paragraph1);
        pdfDoc.add(new Chunk("\n\n"));
        pdfDoc.add(paragraph2);
        pdfDoc.add(paragraph3);
        pdfDoc.add(paragraph4);
        pdfDoc.add(paragraph5);
        pdfDoc.add(table);
        pdfDoc.add(paragraph6);
        pdfDoc.add(paragraph7);
        pdfDoc.add(paragraph8);
        pdfDoc.add(paragraph9);
        pdfDoc.add(paragraph10);
        pdfDoc.add(paragraph11);
        pdfDoc.add(paragraph12);
        pdfDoc.add(paragraph13);
        pdfDoc.add(paragraph14);
        pdfDoc.add(paragraph15);
        pdfDoc.add(paragraph16);
        pdfDoc.add(paragraph17);
        pdfDoc.add(paragraph18);
        pdfDoc.add(paragraph19);

        pdfDoc.close();

        ServletOutputStream out;
        //File(?download.pdf)
        File file = new File(appProps.get("hunche.contrace.download.path") + contrace_no + ".pdf");

        try {
            FileInputStream inputStream = new FileInputStream(file);
            //3.response?ServletOutputStream(out)
            out = response.getOutputStream();
            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1) {
                b = inputStream.read(buffer);
                //4.?(out)
                out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cib.statementstamper.windows.StatementStamperMainWindow.java

License:Open Source License

protected PdfPTable getFooterTable(int x, int y) {
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(537);//from  w w  w.jav  a2 s  .co  m
    table.setLockedWidth(true);
    table.getDefaultCell().setFixedHeight(40);
    table.getDefaultCell().setBorder(Rectangle.TOP);
    table.getDefaultCell().setBorderColor(new BaseColor(221, 72, 20));
    table.getDefaultCell().setBorderWidth(1);
    table.getDefaultCell().setPaddingLeft(0);
    table.getDefaultCell().setPaddingRight(0);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
    Phrase phrase = new Phrase();
    phrase.add(new Chunk(bottomChunk1, bottomFontBold));
    phrase.add(new Chunk(bottomChunk2, bottomFont));
    table.addCell(phrase);
    return table;
}