Example usage for com.itextpdf.text.pdf PdfWriter setInitialLeading

List of usage examples for com.itextpdf.text.pdf PdfWriter setInitialLeading

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter setInitialLeading.

Prototype

public void setInitialLeading(final float leading) throws DocumentException 

Source Link

Document

Sets the initial leading for the PDF document.

Usage

From source file:comisionesafis.informes.CintaComisiones.java

public boolean generar() {

    // Abrimos el fichero de comisiones
    String sSQL = "";
    Statement stmt;//  ww w  .j a v  a  2 s  .c o  m
    ResultSet rsComisiones;
    ResultSet rsBanco;
    String cuenta;

    // Generamos la sentencia de Seleccin de Datos
    try {

        // Generamos el PDF
        Document documento = new Document(PageSize.A4, 80, 80, 50, 50);
        FileOutputStream salida = new FileOutputStream(FICHERO_PDF);
        PdfWriter writer = PdfWriter.getInstance(documento, salida);
        writer.setInitialLeading(0);

        //  Obtenemos una instancia de nuestro manejador de eventos
        CintaComisionesPie pie = new CintaComisionesPie();
        //Asignamos el manejador de eventos al escritor.
        writer.setPageEvent(pie);

        // Abrimos el Documento
        documento.open();

        sSQL = "SELECT * ";
        sSQL += "  FROM ResumenComisiones";
        sSQL += " ORDER BY CodAgente";
        stmt = conexion.createStatement();
        rsComisiones = stmt.executeQuery(sSQL);

        Paragraph Titulo = new Paragraph();
        Titulo.setAlignment(Element.ALIGN_CENTER);
        Titulo.add("CINTA COMISIONES");

        float[] anchuras = { 1f, 1.5f, 3f, 4f, 1f, 1.5f };
        PdfPTable table = new PdfPTable(anchuras);
        table.setWidthPercentage(100);
        table.setSpacingBefore(15f);
        table.setSpacingAfter(10f);
        PdfPCell celda;

        // Tipo de letra para la tabla
        Font font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);

        celda = new PdfPCell(new Phrase("Agente", font));
        celda.setBorder(Rectangle.NO_BORDER);
        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(celda);
        celda = new PdfPCell(new Phrase("Importe", font));
        celda.setBorder(Rectangle.NO_BORDER);
        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(celda);
        celda = new PdfPCell(new Phrase("Cuenta Bancaria", font));
        celda.setBorder(Rectangle.NO_BORDER);
        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(celda);
        celda = new PdfPCell(new Phrase("Nombre", font));
        celda.setBorder(Rectangle.NO_BORDER);
        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(celda);
        celda = new PdfPCell(new Phrase("Irpf", font));
        celda.setBorder(Rectangle.NO_BORDER);
        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(celda);
        celda = new PdfPCell(new Phrase("Total", font));
        celda.setBorder(Rectangle.NO_BORDER);
        celda.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(celda);

        while (rsComisiones.next()) {

            // Buscamos la Cuenta Bancaria
            sSQL = "SELECT * ";
            sSQL += "  FROM Agentes";
            sSQL += " WHERE CodAgente='" + rsComisiones.getString("CodAgente") + "'";
            stmt = conexion.createStatement();
            rsBanco = stmt.executeQuery(sSQL);
            if (!rsBanco.next()) {
                cuenta = "                    ";
            } else {
                cuenta = rsBanco.getString("Banco");
                cuenta += rsBanco.getString("Sucursal");
                cuenta += rsBanco.getString("DC");
                cuenta += rsBanco.getString("Cuenta");
            }

            // Datos del agente
            celda = new PdfPCell(new Phrase(rsComisiones.getString("CodAgente"), font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(
                    Numeros.formateaDosDecimales(Double.parseDouble(rsComisiones.getString("TotalComisiones"))),
                    font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(cuenta, font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(rsComisiones.getString("Nombre"), font));
            celda.setBorder(Rectangle.NO_BORDER);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(
                    Numeros.formateaDosDecimales(Double.parseDouble(rsComisiones.getString("TotalRetencion"))),
                    font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(
                    Numeros.formateaDosDecimales(Double.parseDouble(rsComisiones.getString("TotalPagar"))),
                    font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

        }

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

        // Agregamos la tabla al documento            
        documento.add(table);

        documento.close();

        return true;

    } catch (Exception e) {
        return false;
    }
}

From source file:comisionesafis.informes.FacturasComisionesAgentes.java

public boolean generar() {

    // Abrimos el fichero de comisiones
    Periodos periodos = new Periodos(pb.getFicheroComisiones());
    String sSQL = "";
    Statement stmt;//from   w  w  w.  j ava 2s .com
    ResultSet rsComisiones;
    String sFactura1;
    String sFactura2;

    // Generamos la sentencia de Seleccin de Datos
    try {

        // Generamos el PDF
        Document documento = new Document(PageSize.A4, 80, 80, 50, 50);
        FileOutputStream salida = new FileOutputStream("FacturasComisionesAgentes.pdf");
        PdfWriter writer = PdfWriter.getInstance(documento, salida);
        writer.setInitialLeading(0);

        //  Obtenemos una instancia de nuestro manejador de eventos
        FacturasComisionesAgentesPie pie = new FacturasComisionesAgentesPie();
        //Asignamos el manejador de eventos al escritor.
        writer.setPageEvent(pie);

        // Abrimos el Documento
        documento.open();

        sSQL = "SELECT * ";
        sSQL += "  FROM ResumenComisiones";
        sSQL += " ORDER BY CodAgente";
        stmt = conexion.createStatement();
        rsComisiones = stmt.executeQuery(sSQL);

        while (rsComisiones.next()) {

            // Generamos los prrafos
            // Datos del agente
            Paragraph pAgente[] = new Paragraph[5];
            pAgente[0] = new Paragraph();
            pAgente[0].add(rsComisiones.getString("Nombre"));
            pAgente[0].setAlignment(Paragraph.ALIGN_LEFT);
            pAgente[1] = new Paragraph();
            pAgente[1].add(rsComisiones.getString("Direccion"));
            pAgente[1].setAlignment(Paragraph.ALIGN_LEFT);
            pAgente[2] = new Paragraph();
            pAgente[2].add(rsComisiones.getString("CodPostal") + "  " + rsComisiones.getString("Poblacion"));
            pAgente[2].setAlignment(Paragraph.ALIGN_LEFT);
            pAgente[3] = new Paragraph();
            pAgente[3].add(rsComisiones.getString("Provincia"));
            pAgente[3].setAlignment(Paragraph.ALIGN_LEFT);
            pAgente[4] = new Paragraph();
            pAgente[4].add(rsComisiones.getString("NIF"));
            pAgente[4].setAlignment(Paragraph.ALIGN_LEFT);

            // creating separators
            LineSeparator separador = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);

            // Datos fijos
            Paragraph pPelayo[] = new Paragraph[5];
            pPelayo[0] = new Paragraph();
            pPelayo[0].add("PELAYO VIDA");
            pPelayo[0].setAlignment(Paragraph.ALIGN_RIGHT);
            pPelayo[1] = new Paragraph();
            pPelayo[1].add("CL SANTA ENGRACIA 69");
            pPelayo[1].setAlignment(Paragraph.ALIGN_RIGHT);
            pPelayo[2] = new Paragraph();
            pPelayo[2].add("28010  MADRID");
            pPelayo[2].setAlignment(Paragraph.ALIGN_RIGHT);
            pPelayo[3] = new Paragraph();
            pPelayo[3].add("MADRID");
            pPelayo[3].setAlignment(Paragraph.ALIGN_RIGHT);
            pPelayo[4] = new Paragraph();
            pPelayo[4].add("06422");
            pPelayo[4].setAlignment(Paragraph.ALIGN_RIGHT);

            // Fecha
            Paragraph pFecha = new Paragraph();
            pFecha = new Paragraph("Madrid, a " + periodos.extraeFechaLarga());
            pFecha.setAlignment(Paragraph.ALIGN_RIGHT);

            // Lnea 1 de FACTURA
            Paragraph pFactura1 = new Paragraph();
            sFactura1 = "FACTURA: n factura ";
            sFactura1 += rsComisiones.getString("CodAgente") + " - ";
            sFactura1 += periodos.extraePeriodoMY("MM-YYYY");
            pFactura1 = new Paragraph(sFactura1);

            // Lnea 2 de FACTURA
            Paragraph pFactura2 = new Paragraph();
            sFactura2 = "Factura por la prestacin de servicios relativos a las operaciones ";
            sFactura2 += "de intermediacin de seguros realizadas para su entidad del mes de ";
            sFactura2 += periodos.extraePeriodoMY("MM YYYY");
            ;
            pFactura2 = new Paragraph(sFactura2);

            // Datos Econmicos
            float[] anchuras = { 5f, 2f };
            PdfPTable table = new PdfPTable(anchuras);
            table.getDefaultCell().setBorder(0);

            // Tipo de letra para la tabla
            Font font = new Font(Font.FontFamily.COURIER, 11, Font.NORMAL);

            PdfPCell celda = new PdfPCell();

            celda = new PdfPCell(new Phrase("Comisiones pagadas", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            celda = new PdfPCell(
                    new Phrase(Double.toString(rsComisiones.getDouble("TotalComisiones")) + " ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase("Otros conceptos", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(" ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(
                    "Retencin (" + Double.toString(rsComisiones.getDouble("RetencionPorcentaje")) + "%)",
                    font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            Double dblRetencion = rsComisiones.getDouble("TotalComisiones")
                    * (rsComisiones.getDouble("RetencionPorcentaje") / 100);
            celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(dblRetencion) + " ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase("Conceptos no sujetos", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase(" ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            celda = new PdfPCell(new Phrase("Total a pagar", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(celda);

            Double dblTotalPagar = rsComisiones.getDouble("TotalComisiones") - dblRetencion;
            celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(dblTotalPagar) + " ", font));
            celda.setBorder(Rectangle.NO_BORDER);
            celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(celda);

            // Literal: Operacin exenta de IVA
            Paragraph pColetilla = new Paragraph();
            pColetilla.add("Operacin exenta de IVA");

            // Aadimos los prrafos al Documento
            for (int i = 0; i < 5; i++)
                documento.add(pAgente[i]);

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

            for (int i = 0; i < 5; i++)
                documento.add(pPelayo[i]);

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

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

            documento.add(pFactura1);
            documento.add(separador);
            documento.add(pFactura2);

            // Agregamos la tabla al documento    
            documento.add(new Paragraph(" "));
            documento.add(table);

            documento.add(new Paragraph(" "));
            documento.add(new Paragraph(" "));
            documento.add(pColetilla);
            documento.newPage();
        }
        documento.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:comisionesafis.informes.LiquidacionComisiones.java

public boolean generar() {

    // Abrimos el fichero de comisiones
    String sSQL = "";
    Statement stmt;//from   w w w . j  a v  a  2s. co m
    ResultSet rsAgentes;
    ResultSet rsRecibos;
    PdfPCell celda;
    boolean cabeceraColumnas;
    int filasPorPagina = 0;
    int fila = 0;
    PdfPTable table;
    Double dblTotal = 0.0;

    // Generamos la sentencia de Seleccin de Datos
    try {

        // Generamos el PDF
        Document documento = new Document(PageSize.A4, 80, 80, 50, 50);
        FileOutputStream salida = new FileOutputStream("LiquidacionComisiones.pdf");
        PdfWriter writer = PdfWriter.getInstance(documento, salida);
        writer.setInitialLeading(0);

        //  Obtenemos una instancia de nuestro manejador de eventos
        LiquidacionComisionesPie pie = new LiquidacionComisionesPie();
        //Asignamos el manejador de eventos al escritor.
        writer.setPageEvent(pie);

        // Abrimos el Documento
        documento.open();

        // SELECT para extraer todos los cdigos de los agentes con Recibos
        sSQL = "SELECT DISTINCT (CodAgente) AS Agente ";
        sSQL += "  FROM ResumenComisiones";
        sSQL += " ORDER BY CodAgente";
        stmt = conexion.createStatement();
        rsAgentes = stmt.executeQuery(sSQL);

        while (rsAgentes.next()) {

            if (sumaComisiones(rsAgentes.getString("Agente")) != 0) {
                paginaNum = 0;
                printCabecera1(documento);
                printCabeceraPelayo(documento);
                printCabecera2(documento, rsAgentes);

                // SELECT para extraer todos los Recibos de un agente
                sSQL = "SELECT * ";
                sSQL += "  FROM Recibos";
                sSQL += " WHERE CodAgente = '" + rsAgentes.getString("Agente") + "'";
                stmt = conexion.createStatement();
                rsRecibos = stmt.executeQuery(sSQL);

                //                if(rsAgentes.getString("Agente").equals("10803")){
                //                    System.out.println("");
                //                }

                // Creamos la tabla formateada
                table = creaTabla();

                cabeceraColumnas = true;
                filasPorPagina = 42;
                dblTotal = 0.0;
                while (rsRecibos.next()) {
                    if (Double.parseDouble(rsRecibos.getString("ImpComision")) != 0) {
                        if (fila >= filasPorPagina) {
                            // Salto de pgina
                            // Imprimimos el contenido de la tabla
                            documento.add(table);
                            documento.newPage();
                            table = creaTabla();
                            saltoDePagina(documento, table, rsAgentes);
                            fila = 1;
                            filasPorPagina = 47;
                        } else if (cabeceraColumnas) {
                            // Primera pgina
                            printCabeceraColumnas(table);
                            cabeceraColumnas = false;
                            fila = 1;
                        }
                        Font font = new Font(Font.FontFamily.COURIER, 8, Font.NORMAL);
                        celda = new PdfPCell(new Phrase(rsRecibos.getString("NPoliza"), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
                        table.addCell(celda);
                        celda = new PdfPCell(
                                new Phrase(Fechas.fechaVencimiento(rsRecibos.getString("Fecha")), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
                        table.addCell(celda);
                        celda = new PdfPCell(new Phrase(fondoRecibo(rsRecibos.getString("Descripcion")), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_LEFT);
                        table.addCell(celda);
                        celda = new PdfPCell(new Phrase(rsRecibos.getString("Importe"), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
                        table.addCell(celda);
                        celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(
                                Double.parseDouble(rsRecibos.getString("ImpComision"))), font));
                        celda.setBorder(Rectangle.NO_BORDER);
                        celda.setHorizontalAlignment(Element.ALIGN_RIGHT);
                        table.addCell(celda);
                        dblTotal += Double.parseDouble(rsRecibos.getString("ImpComision"));
                        fila++;
                    }
                }
                if (fila >= filasPorPagina - 5) {
                    documento.add(table);
                    documento.newPage();
                    table = creaTabla();
                }
                printResumenContable(table, dblTotal, rsAgentes.getString("Agente"));
                documento.add(table);
                documento.newPage();
            }
        }
        documento.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:contabilidad.Capital.java

public Capital() {
    jFrame = new JFrame("Capital");
    jFrame.setDefaultCloseOperation(jFrame.DISPOSE_ON_CLOSE);
    jFrame.setSize(800, 600);//from w  w  w . j  ava 2  s  .  c  o m
    jFrame.setLocationRelativeTo(null);
    jFrame.setIconImage(new ImageIcon(getClass().getResource("../imagenes/rana.jpg")).getImage());
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    System.out.println("X:" + screenSize.width + " Y:" + screenSize.height);
    int x = (screenSize.width / 2) - (jFrame.getSize().width / 2);
    int y = (screenSize.height / 2) - (jFrame.getSize().height / 2);
    jFrame.setLocation(x, y);

    JPanel jPanel = new JPanel();
    jPanel.setLayout(null);

    JLabel capitalC = new JLabel("Capital Social: ");
    capitalC.setBounds(50, 90, 90, 20);
    jPanel.add(capitalC);

    JLabel cs = new JLabel("5000");
    cs.setBounds(140, 90, 90, 20);
    jPanel.add(cs);

    JLabel resultado = new JLabel("Resultado de ejercicio: ");
    resultado.setBounds(100, 130, 150, 20);
    jPanel.add(resultado);

    JLabel er = new JLabel("prueba");
    er.setBounds(250, 130, 90, 20);
    jPanel.add(er);

    JLabel capitalCT = new JLabel("Total Capital: ");
    capitalCT.setBounds(170, 170, 90, 20);
    jPanel.add(capitalCT);

    JLabel toc = new JLabel("prueba");
    toc.setBounds(270, 170, 90, 20);
    jPanel.add(toc);

    JMenuBar jMenuBar = new JMenuBar();
    JMenu jMenu = new JMenu("Inicio");
    JMenu jMenu2 = new JMenu("Reportes");
    JMenu jMenu3 = new JMenu("Ayuda");

    jMenuBar.add(jMenu);
    jMenuBar.add(jMenu2);
    jMenuBar.add(jMenu3);

    JMenuItem jMenuItem2 = new JMenuItem("Reporte PDF");
    jMenuItem2.addActionListener(new MenuListener(jFrame));
    jMenuItem2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            selecto = new JFileChooser();
            int op = selecto.showSaveDialog(null);
            if (op == JFileChooser.APPROVE_OPTION) {
                try {
                    OutputStream archivo = new FileOutputStream(selecto.getSelectedFile() + ".pdf");
                    Document document = new Document();
                    document.addAuthor("Contabilidad");
                    document.addTitle("Capital");

                    PdfWriter writer = PdfWriter.getInstance(document,
                            new FileOutputStream(selecto.getSelectedFile() + ".pdf"));
                    writer.setInitialLeading(16);
                    Rectangle rct = new Rectangle(80, 104, 500, 688);
                    writer.setBoxSize("art", rct);
                    HeaderFooter event = new HeaderFooter();
                    writer.setPageEvent(event);

                    document.open();
                    document.add(new Paragraph("Capital"));
                    document.add(new Paragraph(" "));
                    Paragraph parrafo3 = new Paragraph("Fecha: 25/5/42");
                    parrafo3.setAlignment(2);//el 1 es para centrar
                    document.add(parrafo3);
                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));
                    Paragraph parrafo2 = new Paragraph("Capital Social :  5000 ");
                    parrafo2.setAlignment(6);//el 1 es para centrar
                    document.add(parrafo2);
                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));

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

                    Paragraph parrafo5 = new Paragraph("Estado de resultados: ");
                    parrafo5.setAlignment(6);//el 1 es para centrar
                    document.add(parrafo5);

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

                    document.close();
                    archivo.close();
                    Runtime.getRuntime().exec("cmd /c start " + selecto.getSelectedFile() + ".pdf");
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Capital.class.getName()).log(Level.SEVERE, null, ex);
                } catch (DocumentException ex) {
                    Logger.getLogger(Capital.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Capital.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

        }
    });

    JMenuItem jMenuItem3 = new JMenuItem("Salir");
    jMenuItem3.addActionListener(new MenuListener(jFrame));
    jMenuItem3.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            VentanaGeneral es = new VentanaGeneral();
            jFrame.dispose();
        }
    });

    JMenuItem jMenuItem7 = new JMenuItem("Acerca de");
    jMenuItem7.addActionListener(new MenuListener(jFrame));

    jMenu.add(jMenuItem3);
    jMenu2.add(jMenuItem2);
    jMenu3.add(jMenuItem7);

    jFrame.setJMenuBar(jMenuBar);

    JButton botonac = new JButton("Aceptar");
    botonac.setBounds(300, 300, 150, 30);
    botonac.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Reportes es = new Reportes();
            jFrame.dispose();
        }
    });
    jPanel.add(botonac);

    jFrame.add(jPanel);
    jFrame.setVisible(true);
}

From source file:direccion.GeneradorFormato.java

public static void main(String[] args) {

    try {//w  w w .j  a  va  2s. c  om
        Document document = new Document(PageSize.LETTER, 50, 50, 85, 50);
        document.addAuthor("Direccin");
        document.addTitle("Reporte de algo");

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Reporte prueba.pdf"));
        writer.setInitialLeading(16);
        Rectangle rct = new Rectangle(80, 104, 500, 688);
        writer.setBoxSize("art", rct);
        GeneradorFormato event = new GeneradorFormato();
        writer.setPageEvent(event);

        document.open();
        Paragraph parrafo2 = new Paragraph(
                "De aqui en adelante el contenido, ya se pone en automatico el encabezado en cada pgina y el nmero",
                FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED));
        parrafo2.setAlignment(0);
        document.add(parrafo2);

        document.add(Chunk.NEWLINE);

        document.close();
    } catch (FileNotFoundException | DocumentException ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:edu.chl.proton.control.MarkdownTabController.java

License:Open Source License

/**
 * Generates a PDF from the HTML String that getHTML() in IDocumentHandler returns.
 * @throws IOException if typecasting to WebView fails.
 * @throws DocumentException if the PDF cannot be created.
 *//*from w  ww.j a  va2  s  .  c o m*/
@FXML
public void onClickGeneratePDF() throws IOException, DocumentException {
    String path = file.getCurrentDirectory().getPath() + "/untitled.pdf";
    String title = "Output filepath";
    TextPrompt prompt = new TextPrompt(stage.getStage(), title, path);
    if ((path = prompt.getResult()) != null) {
        com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(path));
        writer.setInitialLeading(12);
        doc.open();
        XMLWorkerHelper.getInstance().parseXHtml(writer, doc,
                new ByteArrayInputStream(document.getHTML().getBytes()));
        doc.close();
    }
}

From source file:Facturacion.Factura.java

public void Generar(String numero, int cantidad, int total, Cliente c)
        throws FileNotFoundException, DocumentException {
    com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream("FACTURA" + numero + ".pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);
    PdfPTable table = new PdfPTable(6);
    table.addCell("CANTIDAD");
    table.addCell("CODIGO");
    table.addCell("NOMBRE");
    table.addCell("DESCRIPCION");
    table.addCell("PRECIO");
    table.addCell("TOTAL");
    for (int i = 0; i < producto.size(); i++) {
        table.addCell(String.valueOf(cantidad));
        table.addCell(String.valueOf(producto.get(i).getCodigo()));
        table.addCell(producto.get(i).getNombreP());
        table.addCell(producto.get(i).getDescripcion());
        table.addCell(String.valueOf(producto.get(i).getPrecio()));
        table.addCell(String.valueOf(total));
    }/*from  w w  w  . j  a  v  a 2s . c  om*/
    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");//dd/MM/yyyy
    Date now = new Date();
    String strDate = sdfDate.format(now);
    document.open();
    Paragraph paragraph = new Paragraph();
    Paragraph paragraph1 = new Paragraph();
    paragraph.add("DIMASPORT CIA. LTDA.\n\nFACTURA N" + numero);
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);
    paragraph1.add("\n\nNOMBRE: " + c.getNombre() + " " + c.getApellido() + "\nCEDULA: " + c.getCedula()
            + "\nDIRECCION: " + c.getDireccion() + "\nCORREO: " + c.getCorreo() + "\nTELEFONO: "
            + c.getTelefono() + "\nFECHA: " + strDate + "\n\n");
    paragraph.setAlignment(Paragraph.ALIGN_LEFT);
    document.add(paragraph);
    document.add(paragraph1);
    document.add(table);
    document.close();
}

From source file:Inventario.Inventario2.java

public void createDocument(String filename, String extension) throws DocumentException, FileNotFoundException {
        try {/* ww w.  j  a  va  2s . c om*/

            Document document = new Document(PageSize.LETTER, 50, 50, 85, 50);
            document.addAuthor("Inventario");
            document.addTitle("Reporte de Inventario Compra-Venta");

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
            writer.setInitialLeading(16);
            Rectangle rct = new Rectangle(80, 104, 500, 688);
            writer.setBoxSize("art", rct);
            HeaderFooter event = new HeaderFooter();
            writer.setPageEvent(event);

            document.open();
            Paragraph parrafo2 = new Paragraph("Reportes de Inventario",
                    FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.GRAY));
            parrafo2.setAlignment(0);
            document.add(parrafo2);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.close();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

From source file:modelo.plantillaPDF.java

public void pdf(int tiquet, int idOrden, String codOrden) {
    try {// w w w. ja  v  a 2 s .  c  o  m

        String sql = "Select * from tiquet where idorden = '" + idOrden + "' and tiquet='" + tiquet + "'";
        rs = Consultar(sql);
        int id = 0;
        int numTiquet = 0;
        String ob = "";
        tiquet verTiquet = new tiquet();
        colores verColor = new colores();
        String colorUno = "";
        String colorDos = "";
        System.out.print("id de la orden en el tiquet:" + idOrden);
        ArrayList<String> lista = new ArrayList<String>();
        int c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0, c9 = 0, c10 = 0, c11 = 0, c12 = 0,
                c13 = 0, c14 = 0, c15 = 0;
        int c16 = 0, c17 = 0, c18 = 0, c19 = 0, c20 = 0, c21 = 0, c22 = 0, c23 = 0, c24 = 0, c25 = 0, c26 = 0,
                c27 = 0, c28 = 0, c29 = 0;
        int c30 = 0, c31 = 0, c32 = 0;
        //rs.last();
        int cuantos = rs.getRow();
        //System.out.print("puestos:" + cuantos+ "orden: " + codOrden + "tiquet: " + tiquet);

        //Fecha actual en formato completo:
        //Tue Sep 23 01:18:48 CEST 2014
        Date fechaActual = new Date();
        // System.out.println(fechaActual);
        // System.out.println("---------------------------------------------");

        //Formateando la fecha:
        DateFormat formatoHora = new SimpleDateFormat("HH-mm-ss");
        DateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat Fecha = new SimpleDateFormat("dd/MM/yyyy");
        //  System.out.println("Fecha: "+formatoFecha.format(fechaActual)+" Son las: "+formatoHora.format(fechaActual));

        //Directorio destino para las descargas
        File folder = new File("c:\\seiya\\tiquets");

        //Crea el directorio de destino en caso de que no exista
        folder.mkdirs();
        String fe = Fecha.format(fechaActual);

        int numeroAleatorio = (int) (Math.random() * 2500 + 1);
        //Nombre del fichero <strong>PDF</strong> Resultante de la ejecucion
        String dir = "C:\\seiya\\tiquets\\Tiquet_" + tiquet + ".pdf";
        ;
        // El archivo pdf que vamos a generar
        FileOutputStream fileOutputStream = new FileOutputStream(dir);

        //Creacion del documento con un tamao y unos margenes predeterminados
        Document document = new Document(PageSize.LETTER, 10, 10, 10, 1);

        //A DocWriter class for PDF con Java.
        //When this PdfWriter is added to a certain PdfDocument,
        //the <strong>PDF</strong> representation of every Element added to this Document will be written to the outputstream.
        //PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // Obtener la instancia del PdfWriter
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        //LEADING = separacion entre lineas del documento
        writer.setInitialLeading(16);
        Rectangle rct = new Rectangle(36, 54, 559, 788);
        //Definimos un nombre y un tamao para el PageBox los nombres posibles son: crop?, trim?, art? and bleed?.
        writer.setBoxSize("art", rct);
        //Opens the document.
        //You have to open the document before you can begin to add content to the body of the document.
        document.open();
        //**************************************************************
        //Ejemplos de TABLE

        //Aadir tabla 15 columnas
        PdfPTable table = new PdfPTable(15);
        //   PdfPTable tabla = new PdfPTable(15);
        PdfPCell celda;
        //Aadir CABECERA

        PdfPCell cell;
        Image image = Image.getInstance("logo/logo.png");
        //    String col = "jhon";
        cell = new PdfPCell(image);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(4);
        cell.setRowspan(7);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Calle 12 # 6-68 Nia Ceci"));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(6);
        cell.setRowspan(2);

        table.addCell(cell);

        while (rs.next()) {

            c1 = rs.getInt(1);
            c2 = rs.getInt(2);
            c3 = rs.getInt(3);
            c4 = rs.getInt(4);
            c5 = rs.getInt(5);
            c6 = rs.getInt(8);
            c7 = rs.getInt(9);
            c8 = rs.getInt(10);
            c9 = rs.getInt(11);
            c10 = rs.getInt(12);
            c11 = rs.getInt(13);
            c12 = rs.getInt(14);
            c13 = rs.getInt(15);
            c14 = rs.getInt(16);
            c15 = rs.getInt(17);
            c16 = rs.getInt(18);
            c17 = rs.getInt(19);
            c18 = rs.getInt(21);
            c19 = rs.getInt(22);
            c20 = rs.getInt(23);
            c21 = rs.getInt(24);
            c22 = rs.getInt(25);
            c23 = rs.getInt(26);
            c24 = rs.getInt(28);
            c25 = rs.getInt(29);
            c26 = rs.getInt(30);
            c27 = rs.getInt(31);
            c28 = rs.getInt(32);

            colorUno = verColor.consultarNombreColorUno(c4);
            colorDos = verColor.consultarNombreColorDos(c5);
            ob = verTiquet.ConsultaObservacion(tiquet);

            System.out.print("Color Uno: " + colorUno);

            //cell.setBackgroundColor(BaseColor.BLUE);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("TIKET #:"));
            cell.setColspan(2);
            cell.setRowspan(2);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            //cell.setBackgroundColor(BaseColor.GRAY);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("" + tiquet));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(3);
            cell.setRowspan(2);
            table.addCell(cell);
            //Aadir dos filas de celdas sin formato

            cell = new PdfPCell(new Phrase("Tel: 5783364"));
            cell.setColspan(6);
            cell.setRowspan(2);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.CYAN);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("REF:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(2);
            cell.setRowspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("" + c6));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(3);
            cell.setRowspan(2);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("calzadoseiya@gmail.com"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(6);
            cell.setRowspan(2);//para eliminar espacio cabecera reemplazo el 2 por 3
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("PARES:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(2);
            cell.setRowspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("" + c7));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(3);
            cell.setRowspan(2);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("FECHA"));//espacio intermedio cabecera
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(fe));//espacio intermedio cabecera
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("ORDEN:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(2);
            cell.setRowspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("" + codOrden));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //cell.setBackgroundColor(BaseColor.ORANGE);
            cell.setColspan(3);
            cell.setRowspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("CORTADA"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(""));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            cell.setRowspan(1);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("GUARNICION"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(""));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("MONTADA"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(""));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("EMPLANTILLADA"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(""));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("COLOR 1:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(3);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(colorUno));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("COLOR 2:"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(3);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(colorDos));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(5);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("OBSERVACION"));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(4);
            cell.setRowspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(ob));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(11);
            cell.setRowspan(2);
            table.addCell(cell);

            table.addCell("21");
            table.addCell("22");
            table.addCell("23");
            table.addCell("24");
            table.addCell("25");
            table.addCell("26");
            table.addCell("27");
            table.addCell("28");
            table.addCell("29");
            table.addCell("30");
            table.addCell("31");
            table.addCell("32");
            table.addCell("33");
            table.addCell("34");
            table.addCell("35");

            table.addCell(" " + c8);
            table.addCell(" " + c9);
            table.addCell(" " + c10);
            table.addCell(" " + c11);
            table.addCell(" " + c12);
            table.addCell(" " + c13);
            table.addCell(" " + c14);
            table.addCell(" " + c15);
            table.addCell(" " + c16);
            table.addCell(" " + c17);
            table.addCell(" " + c18);
            table.addCell(" " + c19);
            table.addCell(" " + c20);
            table.addCell(" " + c21);
            table.addCell(" " + c22);

            table.addCell("36");
            table.addCell("37");
            table.addCell("38");
            table.addCell("39");
            table.addCell("40");
            table.addCell("41");
            table.addCell("42");
            table.addCell("43");
            table.addCell("44");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");

            table.addCell(" " + c23);
            table.addCell(" " + c24);
            table.addCell(" " + c25);
            table.addCell(" " + c26);
            table.addCell(" " + c27);
            table.addCell(" " + c28);
            table.addCell(" " + c29);
            table.addCell(" " + c30);
            table.addCell(" " + c31);
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");
            table.addCell(" ");

            document.add(table);
            String cadena = "";
            for (int i = 1; i <= 4; i++) {
                //Chunk chunkSeparador =  new Chunk(SEPARADOR);
                // document.add(chunkSeparador);
                // document.add(Chunk.NEWLINE);

                PdfPTable tabla = new PdfPTable(15);
                if (i == 1)
                    cadena = "EMPLANTILLADA";
                if (i == 2)
                    cadena = "MONTADA";

                if (i == 3) {
                    cadena = "GUARNICION";

                }
                if (i == 4)
                    cadena = "CORTADA";

                cell = new PdfPCell(
                        new Phrase("------------------------------------------------------------------------"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(15);
                cell.setRowspan(1);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase("CALZADO SEIYA"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(5);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase(cadena));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(4);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("TIQUET #"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("" + tiquet));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase("PARES:"));
                cell.setHorizontalAlignment(Font.BOLD);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(2);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("" + c7));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase(""));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(4);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("REF:"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase("" + c6));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                cell.setRowspan(1);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase("COLOR 1:"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase(colorUno));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(4);
                tabla.addCell(cell);

                cell = new PdfPCell(new Phrase("COLOR 2:"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(3);
                tabla.addCell(cell);
                cell = new PdfPCell(new Phrase(colorDos));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setColspan(5);
                tabla.addCell(cell);

                tabla.addCell("21");
                tabla.addCell("22");
                tabla.addCell("23");
                tabla.addCell("24");
                tabla.addCell("25");
                tabla.addCell("26");
                tabla.addCell("27");
                tabla.addCell("28");
                tabla.addCell("29");
                tabla.addCell("30");
                tabla.addCell("31");
                tabla.addCell("32");
                tabla.addCell("33");
                tabla.addCell("34");
                tabla.addCell("35");

                tabla.addCell(" " + c8);
                tabla.addCell(" " + c9);
                tabla.addCell(" " + c10);
                tabla.addCell(" " + c11);
                tabla.addCell(" " + c12);
                tabla.addCell(" " + c13);
                tabla.addCell(" " + c14);
                tabla.addCell(" " + c15);
                tabla.addCell(" " + c16);
                tabla.addCell(" " + c17);
                tabla.addCell(" ");
                tabla.addCell(" " + c20);
                tabla.addCell(" " + c21);
                tabla.addCell(" " + c22);
                tabla.addCell(" " + c23);

                tabla.addCell("36");
                tabla.addCell("37");
                tabla.addCell("38");
                tabla.addCell("39");
                tabla.addCell("40");
                tabla.addCell("41");
                tabla.addCell("42");
                tabla.addCell("43");
                tabla.addCell("44");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");

                tabla.addCell(" " + c24);
                tabla.addCell(" " + c25);
                tabla.addCell(" " + c26);
                tabla.addCell(" " + c27);
                tabla.addCell(" " + c28);
                tabla.addCell(" " + c29);
                tabla.addCell(" " + c30);
                tabla.addCell(" " + c31);
                tabla.addCell(" " + c32);
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");
                tabla.addCell(" ");

                document.add(tabla);

            }

            //document.add(new Paragraph(new Date().toString()));
            //FIN Ejemplos de TABLE
            //**************************************************************

            //**************************************************************
            // Cierre del documento
            document.close();
        }

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:org.smap.sdal.managers.MiscPDFManager.java

License:Open Source License

public void createUsagePdf(Connection sd, OutputStream outputStream, String basePath,
        HttpServletResponse response, int o_id, int month, int year, String period, String org_name) {

    PreparedStatement pstmt = null;

    if (org_name == null) {
        org_name = "None";
    }//w w w .  j a v  a 2  s.  c  o  m

    try {

        String filename;

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        filename = org_name + "_" + year + "_" + month + ".pdf";

        /*
         * Get the usage results
         */
        String sql = "SELECT users.id as id," + "users.ident as ident, " + "users.name as name, "
                + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id "
                + "and se.status = 'success' " + "and se.subscriber = 'results_db' "
                + "and extract(month from upload_time) = ? " // current month
                + "and extract(year from upload_time) = ? " // current year
                + "and ue.user_name = users.ident) as month, "
                + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id "
                + "and se.status = 'success' " + "and se.subscriber = 'results_db' "
                + "and ue.user_name = users.ident) as all_time " + "from users " + "where users.o_id = ? "
                + "and not users.temporary " + "order by users.ident;";

        pstmt = sd.prepareStatement(sql);
        pstmt.setInt(1, month);
        pstmt.setInt(2, year);
        pstmt.setInt(3, o_id);
        log.info("Get Usage Data: " + pstmt.toString());

        // If the PDF is to be returned in an http response then set the file name now
        if (response != null) {
            log.info("Setting filename to: " + filename);
            setFilenameInResponse(filename, response);
        }

        /*
         * Get a template for the PDF report if it exists
         * The template name will be the same as the XLS form name but with an extension of pdf
         */
        String stationaryName = basePath + File.separator + "misc" + File.separator + "UsageReportTemplate.pdf";
        File stationaryFile = new File(stationaryName);

        ByteArrayOutputStream baos = null;
        ByteArrayOutputStream baos_s = null;
        PdfWriter writer = null;

        /*
         * Create document in two passes, the second pass adds the letter head
         */

        // Create the underlying document as a byte array
        Document document = new Document(PageSize.A4);
        document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);

        if (stationaryFile.exists()) {
            baos = new ByteArrayOutputStream();
            baos_s = new ByteArrayOutputStream();
            writer = PdfWriter.getInstance(document, baos);
        } else {
            writer = PdfWriter.getInstance(document, outputStream);
        }

        writer.setInitialLeading(12);
        writer.setPageEvent(new PageSizer());
        document.open();

        // Write the usage data
        ResultSet resultSet = pstmt.executeQuery();

        PdfPTable table = new PdfPTable(4);

        // Add the header row
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
        table.getDefaultCell().setBackgroundColor(VLG);

        table.addCell("User Id");
        table.addCell("User Name");
        table.addCell("Usage in Period");
        table.addCell("All Time Usage");

        table.setHeaderRows(1);

        // Add the user data
        int total = 0;
        int totalAllTime = 0;

        table.getDefaultCell().setBackgroundColor(null);
        while (resultSet.next()) {
            String ident = resultSet.getString("ident");
            String name = resultSet.getString("name");
            String monthUsage = resultSet.getString("month");
            int monthUsageInt = resultSet.getInt("month");
            String allTime = resultSet.getString("all_time");
            int allTimeInt = resultSet.getInt("all_time");

            table.addCell(ident);
            table.addCell(name);
            table.addCell(monthUsage);
            table.addCell(allTime);

            total += monthUsageInt;
            totalAllTime += allTimeInt;

        }

        // Add the totals
        table.getDefaultCell().setBackgroundColor(VLG);

        table.addCell("Totals: ");
        table.addCell(" ");
        table.addCell(String.valueOf(total));
        table.addCell(String.valueOf(totalAllTime));

        document.add(table);
        document.close();

        if (stationaryFile.exists()) {

            // Step 2 - Populate the fields in the stationary
            PdfReader s_reader = new PdfReader(stationaryName);
            PdfStamper s_stamper = new PdfStamper(s_reader, baos_s);
            AcroFields pdfForm = s_stamper.getAcroFields();
            Set<String> fields = pdfForm.getFields().keySet();
            for (String key : fields) {
                log.info("Field: " + key);
            }

            pdfForm.setField("billing_period", period);
            pdfForm.setField("organisation", org_name);

            s_stamper.setFormFlattening(true);
            s_stamper.close();

            // Step 3 - Apply the stationary to the underlying document
            PdfReader reader = new PdfReader(baos.toByteArray()); // Underlying document
            PdfReader f_reader = new PdfReader(baos_s.toByteArray()); // Filled in stationary
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            PdfImportedPage letter1 = stamper.getImportedPage(f_reader, 1);
            int n = reader.getNumberOfPages();
            PdfContentByte background;
            for (int i = 0; i < n; i++) {
                background = stamper.getUnderContent(i + 1);
                if (i == 0) {
                    background.addTemplate(letter1, 0, 0);
                }
            }

            stamper.close();
            reader.close();

        }

    } catch (SQLException e) {
        log.log(Level.SEVERE, "SQL Error", e);

    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception", e);

    } finally {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
    }

}