Example usage for com.itextpdf.text.pdf BaseFont createFont

List of usage examples for com.itextpdf.text.pdf BaseFont createFont

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf BaseFont createFont.

Prototype

public static BaseFont createFont(String name, String encoding, boolean embedded)
        throws DocumentException, IOException 

Source Link

Document

Creates a new font.

Usage

From source file:Compras.Formatos.java

void ordenCompraExternos(int pedido) {
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);/* www  .  j  a va 2 s.  c om*/
    session = HibernateUtil.getSessionFactory().openSession();
    //ord=(Orden)session.get(Orden.class, ord.getIdOrden());
    try {
        DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.000");
        formatoPorcentaje.setMinimumFractionDigits(2);

        session.beginTransaction().begin();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

        PDF reporte = new PDF();
        Date fecha = new Date();
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
        String valor = dateFormat.format(fecha);
        File folder = new File("reportes/externos");
        folder.mkdirs();
        reporte.Abrir(PageSize.LETTER, "cabecera", "reportes/externos/" + valor + "-orden.pdf");
        //Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD);
        Font font = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD);
        BaseColor contenido = BaseColor.WHITE;
        int centro = Element.ALIGN_CENTER;
        int izquierda = Element.ALIGN_LEFT;
        int derecha = Element.ALIGN_RIGHT;
        float tam[] = new float[] { 20, 20, 220, 40, 90, 50, 50 };
        PdfPTable tabla = reporte.crearTabla(7, tam, 100, Element.ALIGN_LEFT);

        Pedido ped = (Pedido) session.get(Pedido.class, pedido);

        //Pedido ped = (Pedido)session.get(Pedido.class, Integer.parseInt(this.no_ped));
        if (ped.getUsuarioByAutorizo() != null && ped.getUsuarioByAutorizo2() != null) {
            reporte.estatusAutoriza(ped.getUsuarioByAutorizo().getEmpleado().getNombre(),
                    ped.getUsuarioByAutorizo2().getEmpleado().getNombre());
        } else
            reporte.estatusAutoriza("", "       NO AUTORIZADO");
        if (ped.getTipoPedido().compareToIgnoreCase("Externo") == 0)
            cabeceraCompraEx(reporte, bf, tabla, ped);
        if (ped.getTipoPedido().compareToIgnoreCase("Adicional") == 0)
            cabeceraCompra(reporte, bf, tabla, ped);

        PartidaExterna[] cuentas = (PartidaExterna[]) session.createCriteria(PartidaExterna.class).
        //add(Restrictions.eq("ordenByIdOrden.idOrden", ord.getIdOrden())).
                add(Restrictions.eq("pedido.idPedido", pedido)).addOrder(Order.asc("idPartidaExterna")).list()
                .toArray(new PartidaExterna[0]);
        int ren = 0;
        double total = 0d;
        if (cuentas.length > 0) {
            for (int i = 0; i < cuentas.length; i++) {
                int r = i + 1;
                //consecutivo
                tabla.addCell(reporte.celda("" + r, font, contenido, izquierda, 0, 1, Rectangle.RECTANGLE));

                //cantidad a comprar
                tabla.addCell(reporte.celda("" + cuentas[i].getCantidad(), font, contenido, derecha, 0, 1,
                        Rectangle.RECTANGLE));

                //Descripcion
                tabla.addCell(reporte.celda(cuentas[i].getDescripcion(), font, contenido, izquierda, 0, 1,
                        Rectangle.RECTANGLE));

                //folio del articulo-partida-subpartida
                if (cuentas[i].getPartida() != null)
                    tabla.addCell(reporte.celda(cuentas[i].getPartida() + "-" + cuentas[i].getIdValuacion(),
                            font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                else
                    tabla.addCell(reporte.celda("", font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));

                tabla.addCell(reporte.celda("" + cuentas[i].getNoParte(), font, contenido, derecha, 0, 1,
                        Rectangle.RECTANGLE));

                //costo unit
                tabla.addCell(reporte.celda(formatoPorcentaje.format(cuentas[i].getCosto()), font, contenido,
                        derecha, 0, 1, Rectangle.RECTANGLE));

                double sum = cuentas[i].getCantidad() * cuentas[i].getCosto();
                total += sum;
                tabla.addCell(reporte.celda(formatoPorcentaje.format(sum), font, contenido, derecha, 0, 1,
                        Rectangle.RECTANGLE));

                /*if(ren==38)
                {
                    reporte.agregaObjeto(tabla);
                    reporte.writer.newPage();
                    tabla=reporte.crearTabla(7, tam, 100, Element.ALIGN_LEFT);
                    cabeceraCompraEx(reporte, bf, tabla, ped);
                    ren=-1;
                }*/
                ren++;
            }
        }
        if (ped.getNotas() != null)
            tabla.addCell(reporte.celda("Notas:" + ped.getNotas(), font, contenido, izquierda, 7, 1,
                    Rectangle.BOTTOM));
        else
            tabla.addCell(reporte.celda("Notas:", font, contenido, izquierda, 7, 1, Rectangle.BOTTOM));
        tabla.addCell(reporte.celda("[Los montos estan en Pesos]", font, contenido, izquierda, 3, 1,
                Rectangle.NO_BORDER));
        tabla.addCell(reporte.celda("Sub-total:", font, contenido, derecha, 3, 1, Rectangle.NO_BORDER));
        tabla.addCell(reporte.celda(formatoPorcentaje.format(total), font, contenido, derecha, 0, 1,
                Rectangle.RECTANGLE));
        tabla.addCell(reporte.celda("IVA:", font, contenido, derecha, 6, 1, Rectangle.NO_BORDER));
        double iva = total * 0.16d;
        tabla.addCell(reporte.celda(formatoPorcentaje.format(iva), font, contenido, derecha, 0, 1,
                Rectangle.RECTANGLE));
        tabla.addCell(reporte.celda("Total:", font, contenido, derecha, 6, 1, Rectangle.NO_BORDER));
        total += iva;
        tabla.addCell(reporte.celda(formatoPorcentaje.format(total), font, contenido, derecha, 0, 1,
                Rectangle.RECTANGLE));
        tabla.addCell(reporte.celda(
                "[NO SE RECIBIR? MATERIAL EN ALMACN SIN ESTA ORDEN DE COMPRA Y REMISIN O FACTURA CORRESPONDIENTE]",
                font, contenido, centro, 7, 1, Rectangle.NO_BORDER));
        tabla.setHeaderRows(1);
        session.beginTransaction().rollback();

        reporte.agregaObjeto(tabla);

        reporte.cerrar();
        reporte.visualizar("reportes/externos/" + valor + "-orden.pdf");

    } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "No se pudo realizar el reporte si el archivo esta abierto.");
    }
}

From source file:Compras.Formatos.java

public void factura() {
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);//from w ww  . j a  v a 2  s. co  m
    session = HibernateUtil.getSessionFactory().openSession();
    factura = (Factura) session.get(Factura.class, factura.getIdFactura());

    String ruta = "";
    try {
        ruta = "";
        FileReader f = new FileReader("config.txt");
        BufferedReader b = new BufferedReader(f);
        if ((ruta = b.readLine()) == null)
            ruta = "";
        b.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.000");
        formatoPorcentaje.setMinimumFractionDigits(2);
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

        PDF reporte = new PDF();
        Date fecha = new Date();
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
        String valor = dateFormat.format(fecha);
        File folder = new File(ruta + "xml-timbrados/");
        folder.mkdirs();
        String fi = "xml-timbrados/" + factura.getRfcEmisor() + "_" + factura.getSerie() + "_"
                + factura.getFolio() + "_" + factura.getRfcReceptor() + ".pdf";
        reporte.Abrir(PageSize.LETTER, "Pedido", "xml-timbrados/" + factura.getRfcEmisor() + "_"
                + factura.getSerie() + "_" + factura.getFolio() + "_" + factura.getRfcReceptor() + ".pdf");
        Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD);
        BaseColor contenido = BaseColor.WHITE;
        int centro = Element.ALIGN_CENTER;
        int izquierda = Element.ALIGN_LEFT;
        int derecha = Element.ALIGN_RIGHT;
        float tam[] = new float[] { 40, 40, 350, 70, 70 };
        PdfPTable tabla = reporte.crearTabla(5, tam, 100, Element.ALIGN_LEFT);

        this.cabeceraFac(reporte, bf, tabla, factura);

        Concepto[] concepto = (Concepto[]) session.createCriteria(Concepto.class)
                .add(Restrictions.eq("factura.idFactura", factura.getIdFactura()))
                .addOrder(Order.asc("idConcepto")).list().toArray(new Concepto[0]);

        int ren = 0;
        double total = 0.0;
        if (concepto.length > 0) {
            for (int i = 0; i < concepto.length; i++) {
                tabla.addCell(
                        reporte.celda("" + concepto[i].getCantidad(), font, contenido, derecha, 0, 1, 12));
                tabla.addCell(reporte.celda(concepto[i].getMedida(), font, contenido, izquierda, 0, 1, 12));
                tabla.addCell(reporte.celda(concepto[i].getDescripcion().toUpperCase(), font, contenido,
                        izquierda, 0, 1, 12));
                tabla.addCell(reporte.celda("" + formatoPorcentaje.format(concepto[i].getPrecio()), font,
                        contenido, derecha, 0, 1, 12));
                double tot = concepto[i].getPrecio() * concepto[i].getCantidad();
                total += tot;
                tabla.addCell(
                        reporte.celda("" + formatoPorcentaje.format(tot), font, contenido, derecha, 0, 1, 12));
            }
        }
        PdfPTable tabla1 = reporte.crearTabla(5, tam, 100, Element.ALIGN_LEFT);
        tabla1.addCell(reporte.celda("Metodo de Pago:" + factura.getMetodoPago(), font, contenido, izquierda, 3,
                1, Rectangle.TOP));
        tabla1.addCell(reporte.celda("SUB-TOTAL:", font, contenido, derecha, 0, 1,
                Rectangle.TOP + Rectangle.BOTTOM + 12));
        tabla1.addCell(reporte.celda(formatoPorcentaje.format(total), font, contenido, derecha, 0, 1,
                Rectangle.TOP + Rectangle.BOTTOM + 12));
        tabla1.addCell(reporte.celda(
                "Lugar de Expedicin: " + factura.getMunicipioEmisor() + ", " + factura.getEstadoEmisor(),
                font, contenido, izquierda, 3, 1, Rectangle.NO_BORDER));
        tabla1.addCell(reporte.celda("IVA:", font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
        Configuracion con = (Configuracion) session.get(Configuracion.class, 1);
        double iva = total * (con.getIva() * 0.01);
        tabla1.addCell(reporte.celda(formatoPorcentaje.format(iva), font, contenido, derecha, 0, 1,
                Rectangle.RECTANGLE));
        tabla1.addCell(
                reporte.celda("(CANTIDAD CON LETRA)", font, contenido, izquierda, 3, 2, Rectangle.NO_BORDER));
        tabla1.addCell(reporte.celda("DEDUCIBLE:", font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
        tabla1.addCell(reporte.celda("" + factura.getDeducible(), font, contenido, derecha, 0, 1,
                Rectangle.RECTANGLE));
        tabla1.addCell(reporte.celda("TOTAL:", font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
        total += iva;
        tabla1.addCell(reporte.celda(formatoPorcentaje.format(total), font, contenido, derecha, 0, 1,
                Rectangle.RECTANGLE));
        tabla1.addCell(reporte.celda("PAGO EN UNA SOLA EXHIBICIN", font, contenido, izquierda, 3, 1,
                Rectangle.NO_BORDER));
        tabla1.addCell(
                reporte.celda("EFECTOS FISCALES AL PAGO", font, contenido, centro, 2, 1, Rectangle.NO_BORDER));
        session.beginTransaction().rollback();

        tabla.setHeaderRows(2);
        reporte.agregaObjeto(tabla);
        float tam1[] = new float[] { 180, 180, 180, 180 };
        PdfPTable tabla2 = reporte.crearTabla(4, tam1, 100, Element.ALIGN_LEFT);
        tabla2.addCell(
                reporte.celda(reporte.Imagen("imagenes/rq.png"), contenido, centro, 0, 8, Rectangle.NO_BORDER));
        tabla2.addCell(reporte.celda("Regimen Fiscal:REGIMEN GENERAL DE LEY DE PERSONAS MORALES", font,
                contenido, centro, 3, 1, Rectangle.BOTTOM));
        tabla2.addCell(reporte.celda("Sello Digital del SAT:", font, contenido, izquierda, 3, 1, 12));
        tabla2.addCell(reporte.celda(" ", font, contenido, izquierda, 3, 1, 12));
        tabla2.addCell(reporte.celda("Sello Digital del Emisor:", font, contenido, izquierda, 3, 1, 12));
        tabla2.addCell(reporte.celda(" ", font, contenido, izquierda, 3, 1, 12));
        tabla2.addCell(reporte.celda("Cadena original del complemento de certificacin digital del SAT:", font,
                contenido, izquierda, 3, 1, 12));
        tabla2.addCell(reporte.celda(" ", font, contenido, izquierda, 3, 1, 12));
        tabla2.addCell(reporte.celda("Este documento es una representacin impresa de un CFDI", font,
                contenido, izquierda, 3, 1, Rectangle.TOP));

        reporte.agregaObjeto(tabla1);
        reporte.agregaObjeto(tabla2);
        reporte.cerrar();
        reporte.visualizar(fi);

    } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "No se pudo realizar el reporte si el archivo esta abierto.");
    }
}

From source file:Compras.reportePedidos.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);//from w  w  w.jav  a2 s  .c  om
    if (t_datos.getRowCount() > 0) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
        jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.pdf)", new String[] { "pdf" }));
        String ruta = null;
        if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
            ruta = jF1.getSelectedFile().getAbsolutePath();
            if (ruta != null) {
                try {
                    DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.00");
                    formatoPorcentaje.setMinimumFractionDigits(2);
                    session.beginTransaction().begin();
                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
                            BaseFont.NOT_EMBEDDED);
                    //Orden ord=buscaApertura();
                    PDF reporte = new PDF();
                    Date fecha = new Date();
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
                    String valor = dateFormat.format(fecha);

                    reporte.Abrir2(PageSize.LETTER.rotate(), "Reporte", ruta + ".pdf");
                    Font font = new Font(Font.FontFamily.HELVETICA, 5, Font.BOLD);
                    BaseColor contenido = BaseColor.WHITE;
                    int centro = Element.ALIGN_CENTER;
                    int izquierda = Element.ALIGN_LEFT;
                    int derecha = Element.ALIGN_RIGHT;
                    float[] tam_pdf = new float[] { 10, 25, 13, 18, 10, 50, 50, 60, 18, 18, 15 };

                    PdfPTable tabla = reporte.crearTabla(tam_pdf.length, tam_pdf, 100, Element.ALIGN_LEFT);

                    cabecera(reporte, bf, tabla);
                    int ren = 0;
                    double dm = 0d, cam = 0d, min = 0d, med = 0d, max = 0d, pin = 0d, tot = 0d;
                    for (int i = 0; i < t_datos.getRowCount(); i++) {
                        for (int j = 0; j < t_datos.getColumnCount(); j++) {
                            if (t_datos.getColumnName(j).compareTo("Monto tot.") == 0) {
                                if (t_datos.getValueAt(i, j) != null)
                                    tabla.addCell(
                                            reporte.celda(formatoPorcentaje.format(t_datos.getValueAt(i, j)),
                                                    font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                                else
                                    tabla.addCell(reporte.celda("0.00", font, contenido, derecha, 0, 1,
                                            Rectangle.RECTANGLE));
                            } else {
                                if (t_datos.getValueAt(i, j) != null)
                                    tabla.addCell(reporte.celda("" + t_datos.getValueAt(i, j), font, contenido,
                                            izquierda, 0, 1, Rectangle.RECTANGLE));
                                else
                                    tabla.addCell(reporte.celda("", font, contenido, izquierda, 0, 1,
                                            Rectangle.RECTANGLE));
                            }
                        }
                        /*if(ren==38)
                        {
                        reporte.agregaObjeto(tabla);
                        reporte.writer.newPage();
                        tabla=reporte.crearTabla(tam_pdf.length, tam_pdf, 100, Element.ALIGN_LEFT);
                        cabecera(reporte, bf, tabla);
                        ren=-1;
                        }
                        ren++;*/
                    }
                    tabla.setHeaderRows(1);
                    reporte.agregaObjeto(tabla);
                    reporte.cerrar();
                    reporte.visualizar2(ruta + ".pdf");
                } catch (Exception e) {
                    System.out.println(e);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "No se pudo realizar el reporte si el archivo esta abierto.");
                } finally {
                    if (session != null)
                        if (session.isOpen())
                            session.close();
                }
            }
        }
    }
}

From source file:Compras.reportePedidos.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);/*w w w  .j a  va2 s . co m*/
    if (t_datos.getRowCount() > 0) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
        jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.pdf)", new String[] { "pdf" }));
        String ruta = null;
        if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
            ruta = jF1.getSelectedFile().getAbsolutePath();
            if (ruta != null) {
                try {
                    DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.00");
                    formatoPorcentaje.setMinimumFractionDigits(2);
                    session.beginTransaction().begin();
                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
                            BaseFont.NOT_EMBEDDED);
                    PDF reporte = new PDF();
                    Date fecha = new Date();
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
                    String valor = dateFormat.format(fecha);

                    reporte.Abrir2(PageSize.LETTER.rotate(), "Reporte", ruta + ".pdf");
                    Font font = new Font(Font.FontFamily.HELVETICA, 8, Font.NORMAL);
                    BaseColor contenido = BaseColor.WHITE;
                    int centro = Element.ALIGN_CENTER;
                    int izquierda = Element.ALIGN_LEFT;
                    int derecha = Element.ALIGN_RIGHT;
                    float[] tam_pdf = new float[] { 15, 40, 130, 20, 15, 30, 20, 15 };

                    PdfPTable tabla = reporte.crearTabla(tam_pdf.length, tam_pdf, 100, Element.ALIGN_LEFT);

                    cabeceraReporte(reporte, bf, tabla);
                    Object no[];
                    int ren[];
                    if (t_datos.getSelectedRows().length > 0) {
                        no = new Object[t_datos.getSelectedRows().length];
                        ren = t_datos.getSelectedRows();
                        for (int x = 0; x < t_datos.getSelectedRows().length; x++) {
                            no[x] = (int) t_datos.getValueAt(ren[x], 0);
                        }
                    } else {
                        no = new Object[t_datos.getRowCount()];
                        //ren =new int[t_datos.getRowCount()];
                        for (int x = 0; x < t_datos.getRowCount(); x++) {
                            no[x] = (int) t_datos.getValueAt(x, 0);
                        }
                    }
                    Pedido[] pedidos;
                    if (autorizado.isSelected() == true) {
                        pedidos = (Pedido[]) session.createCriteria(Pedido.class)
                                .add(Restrictions.and(
                                        Restrictions.and(Restrictions.isNotNull("usuarioByAutorizo"),
                                                Restrictions.isNotNull("usuarioByAutorizo2")),
                                        Restrictions.in("idPedido", no)))
                                .list().toArray(new Pedido[0]);
                    } else {
                        pedidos = (Pedido[]) session.createCriteria(Pedido.class)
                                .add(Restrictions.in("idPedido", no)).list().toArray(new Pedido[0]);
                    }
                    if (pedidos.length > 0) {
                        ArrayList ordena = new ArrayList();
                        for (int a = 0; a < pedidos.length; a++) {
                            Pedido aux = pedidos[a];
                            if (aux.getTipoPedido().compareTo("Interno") == 0) {
                                Partida[] par = (Partida[]) aux.getPartidas().toArray(new Partida[0]);
                                for (int b = 0; b < par.length; b++) {
                                    Partida ren1 = par[b];
                                    Renglon nuevo;
                                    if (ren1.getEjemplar() != null)
                                        nuevo = new Renglon("" + aux.getIdPedido(),
                                                ren1.getEjemplar().getIdParte(), ren1.getCatalogo().getNombre(),
                                                ren1.getCantPcp(), ren1.getMed(), ren1.getPcp(),
                                                "" + ren1.getOrdenByIdOrden().getIdOrden(),
                                                "" + ren1.getIdEvaluacion() + "-" + ren1.getSubPartida());
                                    else
                                        nuevo = new Renglon("" + aux.getIdPedido(), "",
                                                ren1.getCatalogo().getNombre(), ren1.getCantPcp(),
                                                ren1.getMed(), ren1.getPcp(),
                                                "" + ren1.getOrdenByIdOrden().getIdOrden(),
                                                "" + ren1.getIdEvaluacion() + "-" + ren1.getSubPartida());
                                    ordena.add(nuevo);
                                }
                            }

                            if (aux.getTipoPedido().compareTo("Externo") == 0) {
                                PartidaExterna[] par = (PartidaExterna[]) aux.getPartidaExternas()
                                        .toArray(new PartidaExterna[0]);
                                for (int b = 0; b < par.length; b++) {
                                    PartidaExterna ren2 = par[b];
                                    Renglon nuevo;
                                    nuevo = new Renglon("" + aux.getIdPedido(), ren2.getNoParte(),
                                            ren2.getDescripcion(), ren2.getCantidad(), ren2.getUnidad(),
                                            ren2.getCosto(), "", "" + "Ext");
                                    ordena.add(nuevo);
                                }
                            }

                            if (aux.getTipoPedido().compareTo("Adicional") == 0) {
                                PartidaExterna[] par = (PartidaExterna[]) aux.getPartidaExternas()
                                        .toArray(new PartidaExterna[0]);
                                for (int b = 0; b < par.length; b++) {
                                    PartidaExterna ren2 = par[b];
                                    Renglon nuevo;
                                    nuevo = new Renglon("" + aux.getIdPedido(), ren2.getNoParte(),
                                            ren2.getDescripcion(), ren2.getCantidad(), ren2.getUnidad(),
                                            ren2.getCosto(), "" + aux.getOrden().getIdOrden(), "ADI");
                                    ordena.add(nuevo);
                                }
                            }
                        }

                        Collections.sort(ordena, new Comparator() {
                            @Override
                            public int compare(Object o1, Object o2) {
                                Renglon p1 = (Renglon) o1;
                                Renglon p2 = (Renglon) o2;
                                return new String(p1.np + p1.descripcion)
                                        .compareTo(new String(p2.np + p2.descripcion));
                            }
                        });

                        for (int c = 0; c < ordena.size(); c++) {
                            Renglon r1 = (Renglon) ordena.get(c);
                            tabla.addCell(reporte.celda(r1.pedido, font, contenido, derecha, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(
                                    reporte.celda(r1.np, font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(r1.descripcion, font, contenido, izquierda, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(formatoPorcentaje.format(r1.cant), font, contenido,
                                    derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(
                                    reporte.celda(r1.med, font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(formatoPorcentaje.format(r1.precio), font, contenido,
                                    derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda("" + r1.orden, font, contenido, centro, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(r1.partida, font, contenido, derecha, 0, 1,
                                    Rectangle.RECTANGLE));
                        }
                    }

                    tabla.setHeaderRows(2);
                    reporte.agregaObjeto(tabla);
                    reporte.cerrar();
                    reporte.visualizar2(ruta + ".pdf");
                } catch (Exception e) {
                    System.out.println(e);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "No se pudo realizar el reporte si el archivo esta abierto.");
                } finally {
                    if (session != null)
                        if (session.isOpen())
                            session.close();
                }
            }
        }
    }
}

From source file:Contabilidad.RCuentas.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    // TODO add your handling code here:
    if (t_datos.getRowCount() > 0) {
        javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
        jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.pdf)", new String[] { "pdf" }));
        String ruta = null;//from ww w .  j a  va  2  s  .c  om
        if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
            ruta = jF1.getSelectedFile().getAbsolutePath();
            if (ruta != null) {
                Session session = HibernateUtil.getSessionFactory().openSession();
                try {
                    DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.00");
                    formatoPorcentaje.setMinimumFractionDigits(2);
                    session.beginTransaction().begin();
                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
                            BaseFont.NOT_EMBEDDED);
                    //Orden ord=buscaApertura();
                    PDF reporte = new PDF();
                    Date fecha = new Date();
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
                    String valor = dateFormat.format(fecha);

                    reporte.Abrir2(PageSize.LETTER.rotate(), "Reporte Contabilidad", ruta + ".pdf");
                    Font font = new Font(Font.FontFamily.HELVETICA, 7, Font.NORMAL);
                    BaseColor contenido = BaseColor.WHITE;
                    int centro = Element.ALIGN_CENTER;
                    int izquierda = Element.ALIGN_LEFT;
                    int derecha = Element.ALIGN_RIGHT;
                    float[] nuevos = new float[] { 36, 75, 95, 250, 145, 36, 47, 65, 90, 70, 140 };

                    PdfPTable tabla = reporte.crearTabla(nuevos.length, nuevos, 100, Element.ALIGN_LEFT);

                    cabecera(reporte, bf, tabla, "Reporte de Cuentas por Cobrar", 1);
                    for (int ren = 0; ren < t_datos.getRowCount(); ren++) {
                        for (int col = 0; col < t_datos.getColumnCount(); col++) {
                            try {
                                if (col == 1) {
                                    String[] vec = t_datos.getValueAt(ren, col).toString().split("T");
                                    if (vec.length > 0)
                                        tabla.addCell(reporte.celda(vec[0], font, contenido, derecha, 0, 1,
                                                Rectangle.RECTANGLE));
                                    else
                                        tabla.addCell(reporte.celda("", font, contenido, derecha, 0, 1,
                                                Rectangle.RECTANGLE));
                                } else {
                                    if (col == 7)
                                        tabla.addCell(reporte.celda(
                                                formatoPorcentaje.format(t_datos.getValueAt(ren, col)), font,
                                                contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                                    else
                                        tabla.addCell(reporte.celda(t_datos.getValueAt(ren, col).toString(),
                                                font, contenido, izquierda, 0, 1, Rectangle.RECTANGLE));
                                }
                            } catch (Exception e) {
                                tabla.addCell(reporte.celda("", font, contenido, izquierda, 0, 1,
                                        Rectangle.RECTANGLE));
                            }
                        }
                    }
                    tabla.setHeaderRows(1);
                    reporte.agregaObjeto(tabla);
                    reporte.cerrar();
                    reporte.visualizar2(ruta + ".pdf");
                } catch (Exception e) {
                    System.out.println(e);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "No se pudo realizar el reporte si el archivo esta abierto.");
                }
                if (session != null)
                    if (session.isOpen())
                        session.close();
            }
        }
    }
}

From source file:Controlador.ControladorCrearPase.java

private static void absText(PdfWriter writer, String text, int x, int y) throws DocumentException, IOException {

    PdfContentByte cb = writer.getDirectContent();
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.saveState();/*from   ww  w  . j  av a  2s .  com*/
    cb.beginText();
    cb.moveText(x, y);
    cb.setFontAndSize(bf, 12);
    cb.showText(text);
    cb.endText();
    cb.restoreState();

}

From source file:Controller.app.ConsultaController.java

private File createPDF(TblServicioFactura factura) throws IOException {
    String data = factura.getTesPagoResponse();
    JSONObject obj = new JSONObject(data);
    JSONArray content = obj.getJSONArray("lineaFactura");
    String temp = "";
    File _file = null;//from   w  w w .  j av a 2 s .com
    Document doc = null;
    OutputStream file = null;
    int page = 0;
    try {
        _file = File.createTempFile("temp_file", ".pdf");
        TblServicioServicio servicio = servicios.search(factura.getTesCodigoSintesisBi().toString());
        file = new FileOutputStream(_file);
        doc = new Document(PageSize.LETTER);
        doc.setMargins(servicio.getMarginLeft().floatValue(), servicio.getMarginRight().floatValue(),
                servicio.getMarginTop().floatValue(), servicio.getMarginBottom().floatValue());
        PdfWriter.getInstance(doc, file);
        doc.open();
        //            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        ClassLoader classloader = getClass().getClassLoader();
        URL url = classloader.getResource("cour.ttf");
        BaseFont base = null;
        if (url == null) {
            base = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } else {
            String path = url.getPath();
            if ("/".equals(path.substring(0, 1))) {
                path = path.substring(1);
            }
            Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, path);
            base = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
        Font f = new Font(base, servicio.getFontSize(), Font.NORMAL, BaseColor.BLACK);
        String qr = "";
        float line = 0;
        for (Object item : content) {
            Paragraph paragraph = new Paragraph(item.toString(), f);
            if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) {
                if (item.toString().contains("P X#X&$#&K##")) {
                    paragraph = new Paragraph(" ", f);
                    doc.add(paragraph);
                    doc.add(paragraph);
                    paragraph = new Paragraph(item.toString(), f);
                }
            }
            if (item.toString().contains("<b>")) {
                Font bold = new Font(base, 7.0f, Font.BOLD, BaseColor.BLACK);
                paragraph = new Paragraph(item.toString().replace("<b>", ""), bold);
            }
            if (item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>")) {
                qr = item.toString().replaceAll("<QR>", "");
                qr = item.toString().replaceAll("<QR_ENT_G>", "");
                Image image = QR.create(qr);
                image.scaleAbsolute(servicio.getQrScale().floatValue(), servicio.getQrScale().floatValue());
                if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO TELECEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) {
                    float y = (doc.getPageSize().getHeight() - (paragraph.getLeading() * (line + 1)));
                    float x = 0;
                    if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) {
                        image.setAlignment(Image.ALIGN_RIGHT);
                        x = doc.getPageSize().getWidth() - (110 - servicio.getMarginLeft().floatValue());
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO TELECEL")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = 30;
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading() * 2));
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue());
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading()));
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue());
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading()));
                    }
                    image.setAbsolutePosition(x, y);
                }
                doc.add(image);
            }
            if (servicio.getDelimitador().equals(item.toString().trim())) {
                line = 0;
                page++;
                doc.newPage();
            } else {
                line += 1f;
                if (!(item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>"))) {
                    doc.add(paragraph);
                }
            }
            temp += item.toString();
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex);
    } catch (DocumentException | IOException ex) {
        Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex);
    }
    doc.close();
    file.close();
    return _file;
}

From source file:Controller.PrintOrderManagedBean.java

public void executePDF(String maDH) {
    try {/*w w  w  . j av  a 2  s .  co  m*/

        DonHang donhang = new DonHang();
        donhang.init(maDH);
        float CONVERT = 28.346457f;// 1 cm
        FacesContext faces = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        //response.setHeader("Content-disposition","inline; filename=kiran.pdf");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        //response.setHeader("Content-Disposition", "attachment;filename=\"ContactList.pdf\"");
        response.addHeader("Content-disposition", "attachment;filename=\"DataListBean.pdf\"");
        //step 1: creation of a document-object
        Document document = new Document(PageSize.A4, 0.5f * CONVERT, 0.5f * CONVERT, 1.0f * CONVERT,
                1.0f * CONVERT);
        //step 2: we create a writer that listens to the document
        // and directs a PDF-stream to a temporary buffer
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);
        Font font = new Font(bf, 18, Font.BOLD);
        Font font11 = new Font(bf, 11, Font.NORMAL);
        Font font11_bo = new Font(bf, 11, Font.BOLD);
        Font font12 = new Font(bf, 12, Font.NORMAL);
        Font font10 = new Font(bf, 10, Font.NORMAL);
        Font font9 = new Font(bf, 9, Font.NORMAL);
        //step 3: we open the document
        document.open();

        PdfPTable tab_Header1;
        tab_Header1 = new PdfPTable(1);
        tab_Header1.setWidthPercentage(100);

        tab_Header1.setHorizontalAlignment(Element.ALIGN_CENTER);

        PdfPCell cell1;
        cell1 = new PdfPCell(new Phrase("CNG TY TNHH ABC FASHION", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(
                new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S?T: 0909465621", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?N GIAO HNG", font12));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Bn:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn: CNG TY TNHH ABC FASHION", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(
                new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi: 0909465621", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Mua:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn: " + donhang.getTenKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?a ch: " + donhang.getDiaChiKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi: " + donhang.getSoDTKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Vn chuyn:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn:....................................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?a ch:...............................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi:...............................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Danh sch hng ha:", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);
        ///////////////////////////////bn sn phm
        float[] crDonHang = { 1.0f * CONVERT, 4.0f * CONVERT, 1.0f * CONVERT, 2.0f * CONVERT, 2.0f * CONVERT };

        PdfPTable tab_Header2;
        tab_Header2 = new PdfPTable(crDonHang.length);
        tab_Header2.setWidthPercentage(100);
        tab_Header2.setWidths(crDonHang);
        tab_Header2.setHorizontalAlignment(Element.ALIGN_CENTER);
        NumberFormat formatter = new DecimalFormat("#,###,###");

        String[] crheader = { "STT", "Tn Hng", "S Lng", "Gi Bn(VN?)", "Thnh Ti?n(VN?)" };

        for (int i = 0; i < crheader.length; i++) {
            PdfPCell cell = new PdfPCell(new Phrase(crheader[i], font11));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            tab_Header2.addCell(cell);
        }
        int stt = 1;
        for (SanPhamDH sp : donhang.getListSP()) {

            PdfPCell cell = new PdfPCell(new Phrase(String.valueOf(stt), font11));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(sp.getTenSP(), font11));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(sp.getSoluong(), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getGiaSP())), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getThanhTien())), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            stt++;
        }
        cell1 = new PdfPCell(tab_Header2);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n hng:   "
                + formatter.format(
                        Double.parseDouble(donhang.getTienTamTinh() == null ? "0" : donhang.getTienTamTinh()))
                + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n vn chuyn:   "
                + formatter.format(Double
                        .parseDouble(donhang.getTienVanChuyen() == null ? "0" : donhang.getTienVanChuyen()))
                + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n thanh ton:   "
                + formatter.format(Double.parseDouble(donhang.getTongTien())) + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S ti?n thanh ton bng ch: "
                + DocTien.doctien(donhang.getTongTien().replaceAll(" ", "")) + "ng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase(" ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("TP H Ch Minh, ngy      thng       nm       ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingRight(1.0f * CONVERT);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase(" ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        PdfPTable tab_Header3;
        tab_Header3 = new PdfPTable(3);
        tab_Header3.setWidthPercentage(100);

        tab_Header3.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell1 = new PdfPCell(new Phrase("Ng?i nhn hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Ng?i giao hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Ng?i bn hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(tab_Header3);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        document.add(tab_Header1);

        document.close();
        //step 6: we output the writer as bytes to the response output
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        baos.flush();
        faces.responseComplete();

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

From source file:Controllers.ExportController.java

public static void exportExam(String path) {
    model = (DefaultTableModel) tableExam.getModel();
    int selectRow = tableExam.getSelectedRow();

    if (selectRow != -1) {
        int idExam = (int) model.getValueAt(selectRow, 0) - 1;
        exams = ExamModel.readExam();//from  ww w .j  av a2 s .  c o m
        Exam ex = exams.getExam(idExam);

        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(path));
            document.open();
            BaseFont f = BaseFont.createFont("/font/vuArial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font titleExamFont = new Font(f, 25.0f, Font.BOLD);
            Font titlePartFont = new Font(f, 18.0f, Font.BOLD);
            Font headFont = new Font(f, 13.0f, Font.BOLD);
            Font suggestionFont = new Font(f, 13.0f, Font.ITALIC);
            Font contentFont = new Font(f, 13.0f, Font.NORMAL);
            Paragraph align = new Paragraph(" ");
            Paragraph title = new Paragraph(ex.getNameExam(), titleExamFont);
            title.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(title);
            document.add(align);

            ArrayList<Question> question = ex.getQuestions();

            boolean haveMultipleChoice = false;
            boolean haveEssay = false;
            // Kim tra xem c phn t lun khng
            for (Question q : question) {
                if (q instanceof Essay) {
                    haveEssay = true;
                }
                // Kim tra xem c phn trc nghim khng}
                else {
                    haveMultipleChoice = true;
                }
                if (haveEssay && haveMultipleChoice)
                    break;
            }

            int count;
            if (haveMultipleChoice) {
                count = 0;
                Paragraph titlePart = new Paragraph("Trc nghim", titlePartFont);
                document.add(align);
                document.add(titlePart);
                document.add(align);
                for (Question q : question)
                    if (q instanceof MultipleChoice) {
                        count++;
                        Phrase numberQuestion = new Phrase("Cu " + count + ": ", headFont);
                        Phrase contentQuestion = new Phrase(q.getContentQuestion(), contentFont);
                        Paragraph questionParagraph = new Paragraph();
                        questionParagraph.add(numberQuestion);
                        questionParagraph.add(contentQuestion);
                        document.add(questionParagraph);

                        MultipleChoice mc = (MultipleChoice) q;
                        ArrayList<Answer> answers = mc.getAnswers();

                        boolean ok = true;
                        for (int i = 0; i < answers.size(); ++i) {
                            Answer answer = answers.get(i);
                            if (answer.getContentAnswer().length() > 30)
                                ok = false;
                        }

                        if (ok == true) {
                            PdfPTable table = new PdfPTable(2);
                            for (int i = 0; i < answers.size(); ++i) {
                                Answer answer = answers.get(i);
                                PdfPCell answerParagraph = new PdfPCell(new Paragraph(
                                        (char) (65 + i) + ". " + answer.getContentAnswer(), contentFont));
                                answerParagraph.setBorder(Rectangle.NO_BORDER);
                                table.addCell(answerParagraph);
                            }
                            document.add(table);
                        } else {
                            PdfPTable table = new PdfPTable(1);
                            for (int i = 0; i < answers.size(); ++i) {
                                Answer answer = answers.get(i);
                                PdfPCell answerParagraph = new PdfPCell(new Paragraph(
                                        (char) (65 + i) + ". " + answer.getContentAnswer(), contentFont));
                                answerParagraph.setBorder(Rectangle.NO_BORDER);
                                table.addCell(answerParagraph);
                            }
                            document.add(table);
                        }
                    }
            }

            if (haveEssay) {
                count = 0;
                Paragraph titlePart = new Paragraph("T Lun", titlePartFont);
                document.add(align);
                document.add(titlePart);
                document.add(align);
                for (Question q : question)
                    if (q instanceof Essay) {
                        count++;
                        Phrase numberQuestion = new Phrase("Cu " + count + ": ", headFont);
                        Phrase contentQuestion = new Phrase(q.getContentQuestion(), contentFont);
                        Paragraph questionParagraph = new Paragraph();
                        questionParagraph.add(numberQuestion);
                        questionParagraph.add(contentQuestion);

                        Essay es = (Essay) q;
                        Phrase headerSuggestion = new Phrase("Gi : ", suggestionFont);
                        Phrase contentSuggestion = new Phrase(es.getSuggest(), contentFont);
                        Paragraph suggestion = new Paragraph();
                        suggestion.add(headerSuggestion);
                        suggestion.add(contentSuggestion);
                        document.add(questionParagraph);
                        document.add(suggestion);
                    }
            }

            document.close();
        } catch (FileNotFoundException exp) {
            exp.printStackTrace();
        } catch (DocumentException exp) {
            exp.printStackTrace();
        } catch (IOException exp) {
            exp.printStackTrace();
        }
    }
}

From source file:de.aidger.utils.pdf.ActivityReportConverter.java

License:Open Source License

/**
 * Adds the specific values to the fields in the template.
 *///from w ww. ja v  a  2 s.c  o m
private void stampFields() {
    form = stamper.getAcroFields();
    try {
        Calendar calendar = Calendar.getInstance();
        BaseFont fieldFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
        BaseFont fatFieldFont = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false);
        form.setFieldProperty("CreatorName", "textfont", fieldFont, null);
        form.setFieldProperty("CreatorName", "textsize", 12.0f, null);
        form.setFieldProperty("CreatorName", "textcolor", BaseColor.BLACK, null);
        form.setField("CreatorName", Runtime.getInstance().getOption("name"));
        form.setFieldProperty("AssistantName", "textfont", fatFieldFont, null);
        form.setFieldProperty("AssistantName", "textsize", 12.0f, null);
        form.setFieldProperty("AssistantName", "textcolor", BaseColor.BLACK, null);
        form.setField("AssistantName", assistant);
        form.setFieldProperty("Date", "textfont", fieldFont, null);
        form.setFieldProperty("Date", "textsize", 12.0f, null);
        form.setFieldProperty("Date", "textcolor", BaseColor.BLACK, null);
        form.setField("Date", DateUtils.formatDate(calendar.getTime()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}