Example usage for com.itextpdf.text Document open

List of usage examples for com.itextpdf.text Document open

Introduction

In this page you can find the example usage for com.itextpdf.text Document open.

Prototype

boolean open

To view the source code for com.itextpdf.text Document open.

Click Source Link

Document

Is the document open or not?

Usage

From source file:cis_690_report.Reporter.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    File1 = jTextField1.getText();
    JFileChooser chooser = new JFileChooser();
    int option = chooser.showOpenDialog(null);
    if (option == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile() != null) {
            File3 = chooser.getSelectedFile().getAbsolutePath();
        }/*from   www.  j  a  v  a2  s .  c om*/
        File file = new File(File1);

        try {
            br1 = new BufferedReader(new FileReader(file));
            b1 = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException ex) {

        }
        int number_of_rows1 = 0;
        String line = "";
        String cvsSplitBy = ",";
        try {
            while ((line = br1.readLine()) != null) {

                // use comma as separator
                number_of_rows1++;
            }

        } catch (IOException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        }

        bull1 = new String[number_of_rows1][];
        int k = 0;
        BufferedReader br2 = null;
        try {
            br2 = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException ex) {
        }
        try {
            while ((line = br2.readLine()) != null) {

                // use comma as separator
                String Bull[] = line.split(",");
                System.out.println(Bull.length);
                bull1[k] = new String[93];
                if (Bull.length < 10) {
                    for (int j = 0; j < 92; j++) {
                        bull1[k][j] = "";
                        //System.out.println(Bull[j]);
                    }
                } else {
                    for (int j = 0; j < Bull.length; j++) {
                        bull1[k][j] = Bull[j];
                        //System.out.println(Bull[j]);
                    }
                }
                k++;
            }
        } catch (IOException ex) {
        }
        Document doc = new Document();
        PdfWriter docWriter = null;

        DecimalFormat df = new DecimalFormat("0.00");

        try {

            //special font sizes
            Font bfBold12 = new Font(FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0));
            Font bf12 = new Font(FontFamily.TIMES_ROMAN, 6);
            Font bfBold20 = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD);

            //file path

            docWriter = PdfWriter.getInstance(doc, new FileOutputStream(File3));

            //document header attributes
            doc.addAuthor("Shubh Chopra");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("Shubh Chopra");
            doc.addTitle("BES");
            doc.setPageSize(PageSize.LETTER.rotate());

            //open document
            doc.open();
            //create a paragraph
            Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n");
            paragraph.setFont(bfBold20);
            paragraph.setAlignment(Element.ALIGN_CENTER);

            Image img = Image.getInstance("VETMED.png");

            img.scaleToFit(300f, 150f);
            doc.add(paragraph);
            PdfPTable table1 = new PdfPTable(2);
            table1.setWidthPercentage(100);
            PdfPCell cell = new PdfPCell(img);
            cell.setBorder(PdfPCell.NO_BORDER);
            table1.addCell(cell);

            String temp1 = "\tOwner: " + bull1[1][78] + " " + bull1[1][79] + "\n\n\tRanch: " + bull1[1][80]
                    + "\n\n\tAddress: " + bull1[1][71] + "\n\n\tCity: " + bull1[1][73] + "\n\n\tState: "
                    + bull1[1][76] + "\tZip: " + bull1[1][77] + "\n\n\tPhone: " + bull1[1][75] + "\n\n";

            table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT));
            doc.add(table1);

            boolean[] checkboxs = { jCheckBox1.isSelected(), jCheckBox2.isSelected(), jCheckBox3.isSelected(),
                    jCheckBox4.isSelected(), jCheckBox5.isSelected(), jCheckBox6.isSelected(),
                    jCheckBox7.isSelected(), jCheckBox8.isSelected(), jCheckBox9.isSelected(),
                    jCheckBox10.isSelected(), jCheckBox11.isSelected(), jCheckBox12.isSelected(),
                    jCheckBox13.isSelected() };
            //specify column widths
            int temp = 0;
            for (int x = 0; x < checkboxs.length; x++) {
                if (checkboxs[x] == true) {
                    temp++;
                }
            }
            float[] columnWidths = new float[temp + 5];
            for (int x = 0; x < columnWidths.length; x++) {
                if (x < 5)
                    columnWidths[x] = 1f;
                else if (jCheckBox1.isSelected() && x == 5)
                    columnWidths[x] = 2f;
                else if (jCheckBox2.isSelected() && jCheckBox3.isSelected() && x == 7)
                    columnWidths[x] = 2f;
                else if (!jCheckBox2.isSelected() && jCheckBox3.isSelected() && x == 6)
                    columnWidths[x] = 2f;
                else if (jCheckBox4.isSelected() && x == columnWidths.length - 2)
                    columnWidths[x] = 2f;
                else if (jCheckBox5.isSelected() && x == columnWidths.length - 1)
                    columnWidths[x] = 2f;
                else
                    columnWidths[x] = 1f;
            }

            //create PDF table with the given widths
            PdfPTable table = new PdfPTable(columnWidths);
            // set table width a percentage of the page width
            table.setWidthPercentage(90f);
            Reporter re;
            re = new Reporter();
            //insert column headings
            re.insertCell(table, "ID-Tag", Element.ALIGN_CENTER, 1, bfBold12);
            re.insertCell(table, "ID-Tatto", Element.ALIGN_CENTER, 1, bfBold12);
            re.insertCell(table, "ID-RFID", Element.ALIGN_CENTER, 1, bfBold12);
            re.insertCell(table, "ID-Brand", Element.ALIGN_CENTER, 1, bfBold12);
            re.insertCell(table, "ID-Other", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox1.isSelected())
                re.insertCell(table, "Age", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox2.isSelected())
                re.insertCell(table, "Scrotal", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox3.isSelected())
                re.insertCell(table, "Motility", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox6.isSelected())
                re.insertCell(table, "Normal", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox7.isSelected())
                re.insertCell(table, "M2", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox8.isSelected())
                re.insertCell(table, "M3", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox9.isSelected())
                re.insertCell(table, "M4", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox10.isSelected())
                re.insertCell(table, "M5", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox11.isSelected())
                re.insertCell(table, "M6", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox12.isSelected())
                re.insertCell(table, "M7", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox13.isSelected())
                re.insertCell(table, "M8", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox4.isSelected())
                re.insertCell(table, "Comments", Element.ALIGN_CENTER, 1, bfBold12);
            if (jCheckBox5.isSelected())
                re.insertCell(table, "Classification", Element.ALIGN_CENTER, 1, bfBold12);

            table.setHeaderRows(1);

            //insert an empty row

            //create section heading by cell merging

            //just some random data to fill 
            for (int x = 1; x < number_of_rows1; x++) {

                re.insertCell(table, bull1[x][7], Element.ALIGN_CENTER, 1, bf12);
                re.insertCell(table, bull1[x][8], Element.ALIGN_CENTER, 1, bf12);
                re.insertCell(table, bull1[x][6], Element.ALIGN_CENTER, 1, bf12);
                re.insertCell(table, bull1[x][2], Element.ALIGN_CENTER, 1, bf12);
                re.insertCell(table, bull1[x][9], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox1.isSelected())
                    re.insertCell(table, bull1[x][0], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox2.isSelected())
                    re.insertCell(table, bull1[x][70], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox3.isSelected())
                    re.insertCell(table, bull1[x][61], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox6.isSelected())
                    re.insertCell(table, bull1[x][43], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox7.isSelected())
                    re.insertCell(table, bull1[x][45], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox8.isSelected())
                    re.insertCell(table, bull1[x][47], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox9.isSelected())
                    re.insertCell(table, bull1[x][49], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox10.isSelected())
                    re.insertCell(table, bull1[x][51], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox11.isSelected())
                    re.insertCell(table, bull1[x][53], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox12.isSelected())
                    re.insertCell(table, bull1[x][55], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox13.isSelected())
                    re.insertCell(table, bull1[x][57], Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox4.isSelected())
                    re.insertCell(table, "", Element.ALIGN_CENTER, 1, bf12);
                if (jCheckBox5.isSelected())
                    re.insertCell(table, bull1[x][35], Element.ALIGN_CENTER, 1, bf12);
            }
            doc.add(table);

        } catch (DocumentException dex) {
            dex.printStackTrace();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (doc != null) {
                //close the document
                doc.close();
            }
            if (docWriter != null) {
                //close the writer
                docWriter.close();
            }
        }
        // TODO add your handling code here:
    } //GEN-LAST:event_jButton1ActionPerformed
}

From source file:ci_eletronico.FXMLMainController.java

@FXML
private void handleBtnImprimirCI(ActionEvent event) throws IOException {
    if (null == TbViewGeral.getSelectionModel().getSelectedItem()) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Erro");
        alert.setHeaderText("CI no foi selecionada.");
        alert.setContentText("Favor selecionar uma CI da tabela");
        alert.showAndWait();// w w w. java2 s  .  co m
    } else {

        File outfile = null; // variavel para abrir documento pdf aps sua criao

        String strFileName = this.lblNumeroSequencialCI.getText();
        String strUserHome = System.getProperty("user.home") + "\\Downloads\\" + strFileName + ".pdf";
        final Document document = new Document();
        try {
            document.setPageSize(PageSize.A4);
            document.setMargins(10f, 10f, 70f, 40f);
            String strCIAssinatura = TbViewGeral.getSelectionModel().getSelectedItem().getStrp_CoinAssinatura();

            //PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:/Temp/teste.pdf"));
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(strUserHome));

            MyFooter evento = new MyFooter(strCIAssinatura);
            writer.setPageEvent(evento);

        } catch (IOException | DocumentException e) {
            System.out.println(e.toString());
            System.out.println(e.getMessage());
        }
        document.open();

        //String htmlString = htmlEditorCI.getHtmlText();
        String strlCITitulo = "";
        strlCITitulo = "<br /><p align=\"center\"><b>" + strFileName + "</b></p>";
        String htmlString = TbViewGeral.getSelectionModel().getSelectedItem().getStrp_Conteudo();
        //String strCIAssinatura = TbViewGeral.getSelectionModel().getSelectedItem().getStrp_CoinAssinatura();

        //            htmlString = htmlString.replace("<br>", "\n");
        //            htmlString = htmlString.replace("<br/>", "\n");
        //            htmlString = htmlString.replace("<br />", "\n");

        htmlString = htmlString.replace("<br>", "<br />");

        //            htmlString = htmlString.replace("<hr>", "<p></p>");
        //            htmlString = htmlString.replace("<hr/>", "<p></p>");
        //            htmlString = htmlString.replace("<hr />", "<p></p>");

        htmlString = htmlString.replace("<hr>", "<hr />");

        htmlString = strlCITitulo.concat(htmlString);

        StringReader in = new StringReader(htmlString);

        try {
            final Paragraph test = new Paragraph();
            XMLWorkerHelper.getInstance().parseXHtml(new ElementHandler() {
                @Override
                public void add(final Writable w) {
                    if (w instanceof WritableElement) {
                        List<Element> elements = ((WritableElement) w).elements();
                        for (Element e : elements) {
                            test.add(e);
                        }
                    }
                }
            }, in);

            document.add(test);
        } catch (IOException | DocumentException e) {
            System.out.println(e.toString());
            System.out.println(e.getMessage());
        }

        document.close();

        outfile = new File(strUserHome);

        //            Alert alert = new Alert(Alert.AlertType.INFORMATION);
        //            alert.setTitle("Informao");
        //            alert.setHeaderText("Imprimir CI: " + strFileName );
        //            alert.setContentText("Arquivo pdf criado com sucesso na pasta Downloads");
        //            alert.showAndWait();

        openArquivo(outfile); // Abrimos o pdf criado para ser visualizado
    }
}

From source file:clases.Funciones.java

private String GenerateReporte_pdf(JTable t, String title, int open) {
    Document documento = new Document(PageSize.LETTER.rotate(), 10, 10, 10, 10);
    FileOutputStream ficheroPdf;//from w ww .j  av a 2 s  . co m
    File ruta = null;
    com.itextpdf.text.Image imagen = null;
    try {
        imagen = com.itextpdf.text.Image.getInstance(p.ReturnPropiedad(p.Ruta_logo));

        char rt = p.ReturnPropiedad(p.Ruta_SaveReports)
                .charAt(p.ReturnPropiedad(p.Ruta_SaveReports).length() - 1);

        if ("/".equalsIgnoreCase(String.valueOf(rt))) {
            ruta = new File(p.ReturnPropiedad(p.Ruta_SaveReports) + ReturnNombreUsuario().replace(" ", "_")
                    + "_" + GetFechaAndHourActual().replace(" ", "_").replace(":", "_").replace("-", "_")
                    + ".pdf");
        } else {
            ruta = new File(p.ReturnPropiedad(p.Ruta_SaveReports) + "/"
                    + ReturnNombreUsuario().replace(" ", "_") + "_"
                    + GetFechaAndHourActual().replace(" ", "_").replace(":", "_").replace("-", "_") + ".pdf");
        }

        ficheroPdf = new FileOutputStream(ruta);
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
    } catch (DocumentException | IOException ex) {
        Alert("Verifique las rutas de guardado de reportes y logo.");
    }

    try {
        documento.open();

        title += "\nGENER: " + ReturnNombreUsuario();

        Paragraph Title = new Paragraph(title.toUpperCase());
        Title.setAlignment(1);
        documento.add(Title);
        imagen.setAlignment(Element.ALIGN_CENTER);
        imagen.scaleToFit(200, 100);

        String membrete = ReturnDatosFisicos(this.Datos_Nombre) + "\n";
        membrete += "DIRECCION: " + ReturnDatosFisicos(this.Datos_Direccion) + "\n";
        membrete += "RFC: " + ReturnDatosFisicos(this.Datos_Rfc) + "\n";
        membrete += "TELEFONO: " + ReturnDatosFisicos(this.Datos_Telefono) + "\n";
        membrete += "GENERO DOCUMENTO: " + ReturnNombreUsuario() + "\n";
        membrete += "FECHA Y HORA DE GENERACION: " + GetFechaAndHourActual() + "\n";

        /////////
        PdfPTable HeaderDatos = new PdfPTable(2);
        HeaderDatos.setWidthPercentage(100);

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

        PdfPCell cell = new PdfPCell(new Phrase(membrete));
        cell.setBorder(0);
        HeaderDatos.addCell(cell);
        cell = new PdfPCell(imagen);
        cell.setBorder(0);
        cell.setHorizontalAlignment(1);
        HeaderDatos.addCell(cell);

        documento.add(HeaderDatos);
        documento.add(new Paragraph("\n"));
        /////////

        PdfPTable tabla = new PdfPTable(t.getColumnCount());

        tabla.setWidthPercentage(100);

        for (int i = 0; i < t.getColumnCount(); i++) {
            Paragraph header = new Paragraph(t.getColumnName(i));
            header.setAlignment(1);
            tabla.addCell(header);
        }

        for (int i = 0; i < t.getRowCount(); i++) {
            for (int a = 0; a < t.getColumnCount(); a++) {

                Paragraph campo = new Paragraph(String.valueOf(t.getValueAt(i, a)));
                campo.setAlignment(1);
                tabla.addCell(campo);
            }
        }

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

        Paragraph footer = new Paragraph("SOFTWARE Y MAS ! - WWW.CYBERCHOAPAS.COM");
        footer.setAlignment(1);
        documento.add(footer);

        documento.close();
        if (open > 0) {
            Desktop.getDesktop().open(ruta);
        }
    } catch (IOException | DocumentException ex) {
        Alert(ex.getMessage());
    }
    return ruta.getAbsolutePath();
}

From source file:clases.Funciones.java

public boolean GenerateReporte_Service(JTable t_client, JTable t_vehiculos, int open, String S_solicitad,
        String S_realizado, JTable t_productos, String Total, String Prioridad, JComboBox client,
        JComboBox vehiculos, Double km) {
    boolean r = false;

    int Folio = GenerateFolioService();

    if (AddService(client, vehiculos, S_solicitad, S_realizado, t_productos, Double.parseDouble(Total),
            "URGENTE".equals(Prioridad)) && vehiculos.getSelectedIndex() > 0) {
        UpdateKilometraje((String) ListVehiculos.get(vehiculos.getSelectedIndex()), km);

        Table_LoadClient(t_client, client);
        Table_LoadCar(t_vehiculos, vehiculos);

        Document documento = new Document(PageSize.LETTER, 10, 10, 10, 10);
        FileOutputStream ficheroPdf;
        File ruta = null;/*  w ww.  j  a va2  s  .c  om*/
        com.itextpdf.text.Image imagen = null;
        try {
            imagen = com.itextpdf.text.Image.getInstance(p.ReturnPropiedad(p.Ruta_logo));

            char rt = p.ReturnPropiedad(p.Ruta_SaveReports)
                    .charAt(p.ReturnPropiedad(p.Ruta_SaveReports).length() - 1);

            if ("/".equalsIgnoreCase(String.valueOf(rt))) {
                ruta = new File(p.ReturnPropiedad(p.Ruta_SaveReports) + ReturnNombreUsuario().replace(" ", "_")
                        + "_" + GetFechaAndHourActual().replace(" ", "_").replace(":", "_").replace("-", "_")
                        + ".pdf");
            } else {
                ruta = new File(p.ReturnPropiedad(p.Ruta_SaveReports) + "/"
                        + ReturnNombreUsuario().replace(" ", "_") + "_"
                        + GetFechaAndHourActual().replace(" ", "_").replace(":", "_").replace("-", "_")
                        + ".pdf");
            }

            ficheroPdf = new FileOutputStream(ruta);
            PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
        } catch (DocumentException | IOException ex) {
            Alert("Verifique las rutas de guardado de reportes y logo.");
        }

        try {
            documento.open();

            imagen.setAlignment(Element.ALIGN_CENTER);
            imagen.scaleToFit(200, 100);

            String membrete = "REPORTE DE SERVICIO NO: " + Folio + "\n\n";
            membrete += ReturnDatosFisicos(this.Datos_Nombre) + "\n";
            membrete += "DIRECCION: " + ReturnDatosFisicos(this.Datos_Direccion) + "\n";
            membrete += "RFC: " + ReturnDatosFisicos(this.Datos_Rfc) + "\n";
            membrete += "TELEFONO: " + ReturnDatosFisicos(this.Datos_Telefono) + "\n";
            membrete += "GENERO DOCUMENTO: " + ReturnNombreUsuario() + "\n";
            membrete += "GENERADO: " + GetFechaAndHourActual() + "\n";

            PdfPTable HeaderDatos = new PdfPTable(2);
            HeaderDatos.setWidthPercentage(100);

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

            PdfPCell cell = new PdfPCell(new Phrase(membrete));
            cell.setBorder(0);
            HeaderDatos.addCell(cell);
            cell = new PdfPCell(imagen);
            cell.setBorder(0);
            cell.setHorizontalAlignment(1);
            cell.setVerticalAlignment(1);
            HeaderDatos.addCell(cell);

            documento.add(HeaderDatos);
            documento.add(new Paragraph("\n"));
            /////////

            //Tabla_Clientes
            String Client_header = "CLIENTE";
            Paragraph Title = new Paragraph(Client_header.toUpperCase());
            Title.setAlignment(1);
            documento.add(Title);
            documento.add(new Paragraph(" "));

            PdfPTable tabla = new PdfPTable(t_client.getColumnCount());

            tabla.setWidthPercentage(100);

            for (int i = 0; i < t_client.getColumnCount(); i++) {
                Paragraph header = new Paragraph(t_client.getColumnName(i));
                header.setAlignment(1);
                tabla.addCell(header);
            }

            for (int i = 0; i < t_client.getRowCount(); i++) {
                for (int a = 0; a < t_client.getColumnCount(); a++) {

                    Paragraph campo = new Paragraph(String.valueOf(t_client.getValueAt(i, a)));
                    campo.setAlignment(1);
                    tabla.addCell(campo);
                }
            }

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

            //Tabla_Vehiculos
            String Vehiculos_header = "VEHICULO";

            Paragraph Title1 = new Paragraph(Vehiculos_header.toUpperCase());
            Title1.setAlignment(1);
            documento.add(Title1);
            documento.add(new Paragraph(" "));

            PdfPTable tabla_vehiculos = new PdfPTable(t_vehiculos.getColumnCount());

            tabla_vehiculos.setWidthPercentage(100);

            for (int i = 0; i < t_vehiculos.getColumnCount(); i++) {
                Paragraph header = new Paragraph(t_vehiculos.getColumnName(i));
                header.setAlignment(1);
                tabla_vehiculos.addCell(header);
            }

            for (int i = 0; i < t_vehiculos.getRowCount(); i++) {
                for (int a = 0; a < t_vehiculos.getColumnCount(); a++) {

                    Paragraph campo = new Paragraph(String.valueOf(t_vehiculos.getValueAt(i, a)));
                    campo.setAlignment(1);
                    tabla_vehiculos.addCell(campo);
                }
            }

            documento.add(tabla_vehiculos);
            documento.add(new Paragraph("SERVICIO SOLICITADO: " + S_solicitad.toUpperCase()));
            documento.add(new Paragraph("SERVICIO REALIZADO: " + S_realizado.toUpperCase()));
            documento.add(new Paragraph("PRIORIDAD: " + Prioridad));

            //Tabla de servicios y productos
            String Service_header = "\nSERVICIOS Y PRODUCTOS UTILIZADOS";

            Paragraph Title2 = new Paragraph(Service_header.toUpperCase());
            Title2.setAlignment(1);
            documento.add(Title2);
            documento.add(new Paragraph(" "));

            PdfPTable tabla_PRODUCTS = new PdfPTable(t_productos.getColumnCount());

            tabla_PRODUCTS.setWidthPercentage(100);

            for (int i = 0; i < t_productos.getColumnCount(); i++) {
                Paragraph header = new Paragraph(t_productos.getColumnName(i));
                header.setAlignment(1);
                tabla_PRODUCTS.addCell(header);
            }

            for (int i = 0; i < t_productos.getRowCount(); i++) {
                for (int a = 0; a < t_productos.getColumnCount(); a++) {

                    Paragraph campo = new Paragraph(String.valueOf(t_productos.getValueAt(i, a)));
                    campo.setAlignment(1);
                    tabla_PRODUCTS.addCell(campo);
                }
            }

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

            documento.add(new Paragraph("COSTO TOTAL DE SERVICIO $ " + Total));
            documento.add(new Paragraph(
                    "FECHA Y HORA DE ENTREGA: ____________________________________________________"));
            documento.add(new Paragraph(
                    "NOMBRE Y FIRMA DEL QUE REALIZA: _____________________________________________"));
            documento.add(new Paragraph(
                    "CONFORMIDAD, NOMBRE Y FIRMA DE QUIEN RECIBE: _______________________________"));
            documento.add(new Paragraph(
                    "PROXIMO SERVICIO: ___________________________________________________________"));

            Paragraph footer = new Paragraph("SOFTWARE Y MAS ! - WWW.CYBERCHOAPAS.COM");
            footer.setAlignment(1);
            documento.add(footer);

            documento.close();
            r = true;
            if (open > 0) {
                Desktop.getDesktop().open(ruta);
            }
        } catch (IOException | DocumentException ex) {
            Alert(ex.getMessage());
        }
    } else {
        Alert("VERIFIQUE SU INFORMACION");
    }
    return r;
}

From source file:clases.Funciones.java

public void ReGenerateReporte_Service(JTable t) {
    int id = 0, id_cliente = 0;
    double total = 0;
    String id_vehiculo = "", s_solicitado = "", s_realizado = "", productos = "";
    boolean p_urgente = false;

    try {//from   w w w  . j  av  a2  s .c  om
        coneccion = new Conexion();
        try (ResultSet rs = coneccion.Consulta(
                "SELECT id, id_cliente, id_vehiculo, s_solicitado, s_realizado, productos, total, p_urgente FROM services where id = "
                        + Integer.parseInt((String) t.getValueAt(t.getSelectedRow(), 0)) + " ")) {

            if (rs.next()) {
                id = rs.getInt(1);
                id_cliente = rs.getInt(2);
                id_vehiculo = rs.getString(3);
                s_solicitado = rs.getString(4);
                s_realizado = rs.getString(5);
                productos = rs.getString(6);
                total = rs.getDouble(7);
                p_urgente = rs.getBoolean(8);
            }

        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
        Alert(ex.getMessage());
    }

    int Folio = id;

    JTable t_client = new JTable();
    JTable t_vehiculos = new JTable();

    Table_LoadClient(t_client, id_cliente);
    Table_LoadCar(t_vehiculos, id_vehiculo);

    Document documento = new Document(PageSize.LETTER, 10, 10, 10, 10);
    FileOutputStream ficheroPdf;
    File ruta = null;
    com.itextpdf.text.Image imagen = null;
    try {
        imagen = com.itextpdf.text.Image.getInstance(p.ReturnPropiedad(p.Ruta_logo));

        char rt = p.ReturnPropiedad(p.Ruta_SaveReports)
                .charAt(p.ReturnPropiedad(p.Ruta_SaveReports).length() - 1);

        if ("/".equalsIgnoreCase(String.valueOf(rt))) {
            ruta = new File(p.ReturnPropiedad(p.Ruta_SaveReports) + ReturnNombreUsuario().replace(" ", "_")
                    + "_" + GetFechaAndHourActual().replace(" ", "_").replace(":", "_").replace("-", "_")
                    + ".pdf");
        } else {
            ruta = new File(p.ReturnPropiedad(p.Ruta_SaveReports) + "/"
                    + ReturnNombreUsuario().replace(" ", "_") + "_"
                    + GetFechaAndHourActual().replace(" ", "_").replace(":", "_").replace("-", "_") + ".pdf");
        }

        ficheroPdf = new FileOutputStream(ruta);
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
    } catch (DocumentException | IOException ex) {
        Alert("Verifique las rutas de guardado de reportes y logo.");
    }

    try {
        documento.open();

        imagen.setAlignment(Element.ALIGN_CENTER);
        imagen.scaleToFit(200, 100);

        String membrete = "REPORTE DE SERVICIO NO: " + Folio + "\n\n";
        membrete += ReturnDatosFisicos(this.Datos_Nombre) + "\n";
        membrete += "DIRECCION: " + ReturnDatosFisicos(this.Datos_Direccion) + "\n";
        membrete += "RFC: " + ReturnDatosFisicos(this.Datos_Rfc) + "\n";
        membrete += "TELEFONO: " + ReturnDatosFisicos(this.Datos_Telefono) + "\n";
        membrete += "GENERO DOCUMENTO: " + ReturnNombreUsuario() + "\n";
        membrete += "GENERADO: " + GetFechaAndHourActual() + "\n";

        PdfPTable HeaderDatos = new PdfPTable(2);
        HeaderDatos.setWidthPercentage(100);

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

        PdfPCell cell = new PdfPCell(new Phrase(membrete));
        cell.setBorder(0);
        HeaderDatos.addCell(cell);
        cell = new PdfPCell(imagen);
        cell.setBorder(0);
        cell.setHorizontalAlignment(1);
        cell.setVerticalAlignment(1);
        HeaderDatos.addCell(cell);

        documento.add(HeaderDatos);
        documento.add(new Paragraph("\n"));
        /////////

        //Tabla_Clientes
        String Client_header = "CLIENTE";
        Paragraph Title = new Paragraph(Client_header.toUpperCase());
        Title.setAlignment(1);
        documento.add(Title);
        documento.add(new Paragraph(" "));

        PdfPTable tabla = new PdfPTable(t_client.getColumnCount());

        tabla.setWidthPercentage(100);

        for (int i = 0; i < t_client.getColumnCount(); i++) {
            Paragraph header = new Paragraph(t_client.getColumnName(i));
            header.setAlignment(1);
            tabla.addCell(header);
        }

        for (int i = 0; i < t_client.getRowCount(); i++) {
            for (int a = 0; a < t_client.getColumnCount(); a++) {

                Paragraph campo = new Paragraph(String.valueOf(t_client.getValueAt(i, a)));
                campo.setAlignment(1);
                tabla.addCell(campo);
            }
        }

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

        //Tabla_Vehiculos
        String Vehiculos_header = "VEHICULO";

        Paragraph Title1 = new Paragraph(Vehiculos_header.toUpperCase());
        Title1.setAlignment(1);
        documento.add(Title1);
        documento.add(new Paragraph(" "));

        PdfPTable tabla_vehiculos = new PdfPTable(t_vehiculos.getColumnCount());

        tabla_vehiculos.setWidthPercentage(100);

        for (int i = 0; i < t_vehiculos.getColumnCount(); i++) {
            Paragraph header = new Paragraph(t_vehiculos.getColumnName(i));
            header.setAlignment(1);
            tabla_vehiculos.addCell(header);
        }

        for (int i = 0; i < t_vehiculos.getRowCount(); i++) {
            for (int a = 0; a < t_vehiculos.getColumnCount(); a++) {

                Paragraph campo = new Paragraph(String.valueOf(t_vehiculos.getValueAt(i, a)));
                campo.setAlignment(1);
                tabla_vehiculos.addCell(campo);
            }
        }

        documento.add(tabla_vehiculos);
        documento.add(new Paragraph("SERVICIO SOLICITADO: " + s_solicitado.toUpperCase()));
        documento.add(new Paragraph("SERVICIO REALIZADO: " + s_realizado.toUpperCase()));
        String var = "";
        if (p_urgente) {
            var = "URGENTE";
        } else {
            var = "PROGRAMAR";
        }
        documento.add(new Paragraph("PRIORIDAD: " + var));

        //Tabla de servicios y productos
        String Service_header = "\nSERVICIOS Y PRODUCTOS UTILIZADOS";

        Paragraph Title2 = new Paragraph(Service_header.toUpperCase());
        Title2.setAlignment(1);
        documento.add(Title2);
        documento.add(new Paragraph(" "));

        JTable t_productos = new JTable();

        Table_LoadProductsServicio(t_productos);

        String[] result = productos.replace("+", ",").split(",");

        if (result.length >= 1) {
            for (String r : result) {
                if (!r.equalsIgnoreCase("") || !r.isEmpty()) {
                    if (ExistProduct(r)) {
                        Table_AddProductsServicio(t_productos, r);
                    }
                }
            }
        }

        PdfPTable tabla_PRODUCTS = new PdfPTable(t_productos.getColumnCount());

        tabla_PRODUCTS.setWidthPercentage(100);

        for (int i = 0; i < t_productos.getColumnCount(); i++) {
            Paragraph header = new Paragraph(t_productos.getColumnName(i));
            header.setAlignment(1);
            tabla_PRODUCTS.addCell(header);
        }

        for (int i = 0; i < t_productos.getRowCount(); i++) {
            for (int a = 0; a < t_productos.getColumnCount(); a++) {

                Paragraph campo = new Paragraph(String.valueOf(t_productos.getValueAt(i, a)));
                campo.setAlignment(1);
                tabla_PRODUCTS.addCell(campo);
            }
        }

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

        documento.add(new Paragraph("COSTO TOTAL DE SERVICIO $ " + total));
        documento.add(
                new Paragraph("FECHA Y HORA DE ENTREGA: ____________________________________________________"));
        documento.add(
                new Paragraph("NOMBRE Y FIRMA DEL QUE REALIZA: _____________________________________________"));
        documento.add(
                new Paragraph("CONFORMIDAD, NOMBRE Y FIRMA DE QUIEN RECIBE: _______________________________"));
        documento.add(
                new Paragraph("PROXIMO SERVICIO: ___________________________________________________________"));

        Paragraph footer = new Paragraph("SOFTWARE Y MAS ! - WWW.CYBERCHOAPAS.COM");
        footer.setAlignment(1);
        documento.add(footer);

        documento.close();
        Desktop.getDesktop().open(ruta);
    } catch (IOException | DocumentException ex) {
        Alert(ex.getMessage());
    } catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException ex) {
        Alert(ex.getMessage());
    }
}

From source file:clases.Funciones.java

public void ReGenerateReporte_Service(int id_service) {
    int id = 0, id_cliente = 0;
    double total = 0;
    String id_vehiculo = "", s_solicitado = "", s_realizado = "", productos = "";
    boolean p_urgente = false;

    try {// www  .j  a v a 2  s  .  c o  m
        coneccion = new Conexion();
        try (ResultSet rs = coneccion.Consulta(
                "SELECT id, id_cliente, id_vehiculo, s_solicitado, s_realizado, productos, total, p_urgente FROM services where id = "
                        + id_service + " ")) {

            if (rs.next()) {
                id = rs.getInt(1);
                id_cliente = rs.getInt(2);
                id_vehiculo = rs.getString(3);
                s_solicitado = rs.getString(4);
                s_realizado = rs.getString(5);
                productos = rs.getString(6);
                total = rs.getDouble(7);
                p_urgente = rs.getBoolean(8);
            }

        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
        Alert(ex.getMessage());
    }

    int Folio = id;

    JTable t_client = new JTable();
    JTable t_vehiculos = new JTable();

    Table_LoadClient(t_client, id_cliente);
    Table_LoadCar(t_vehiculos, id_vehiculo);

    Document documento = new Document(PageSize.LETTER, 10, 10, 10, 10);
    FileOutputStream ficheroPdf;
    File ruta = null;
    com.itextpdf.text.Image imagen = null;
    try {
        imagen = com.itextpdf.text.Image.getInstance(p.ReturnPropiedad(p.Ruta_logo));

        char rt = p.ReturnPropiedad(p.Ruta_SaveReports)
                .charAt(p.ReturnPropiedad(p.Ruta_SaveReports).length() - 1);

        if ("/".equalsIgnoreCase(String.valueOf(rt))) {
            ruta = new File(p.ReturnPropiedad(p.Ruta_SaveReports) + ReturnNombreUsuario().replace(" ", "_")
                    + "_" + GetFechaAndHourActual().replace(" ", "_").replace(":", "_").replace("-", "_")
                    + ".pdf");
        } else {
            ruta = new File(p.ReturnPropiedad(p.Ruta_SaveReports) + "/"
                    + ReturnNombreUsuario().replace(" ", "_") + "_"
                    + GetFechaAndHourActual().replace(" ", "_").replace(":", "_").replace("-", "_") + ".pdf");
        }

        ficheroPdf = new FileOutputStream(ruta);
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
    } catch (DocumentException | IOException ex) {
        Alert("Verifique las rutas de guardado de reportes y logo.");
    }

    try {
        documento.open();

        imagen.setAlignment(Element.ALIGN_CENTER);
        imagen.scaleToFit(200, 100);

        String membrete = "REPORTE DE SERVICIO NO: " + Folio + "\n\n";
        membrete += ReturnDatosFisicos(this.Datos_Nombre) + "\n";
        membrete += "DIRECCION: " + ReturnDatosFisicos(this.Datos_Direccion) + "\n";
        membrete += "RFC: " + ReturnDatosFisicos(this.Datos_Rfc) + "\n";
        membrete += "TELEFONO: " + ReturnDatosFisicos(this.Datos_Telefono) + "\n";
        membrete += "GENERO DOCUMENTO: " + ReturnNombreUsuario() + "\n";
        membrete += "GENERADO: " + GetFechaAndHourActual() + "\n";

        PdfPTable HeaderDatos = new PdfPTable(2);
        HeaderDatos.setWidthPercentage(100);

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

        PdfPCell cell = new PdfPCell(new Phrase(membrete));
        cell.setBorder(0);
        HeaderDatos.addCell(cell);
        cell = new PdfPCell(imagen);
        cell.setBorder(0);
        cell.setHorizontalAlignment(1);
        cell.setVerticalAlignment(1);
        HeaderDatos.addCell(cell);

        documento.add(HeaderDatos);
        documento.add(new Paragraph("\n"));
        /////////

        //Tabla_Clientes
        String Client_header = "CLIENTE";
        Paragraph Title = new Paragraph(Client_header.toUpperCase());
        Title.setAlignment(1);
        documento.add(Title);
        documento.add(new Paragraph(" "));

        PdfPTable tabla = new PdfPTable(t_client.getColumnCount());

        tabla.setWidthPercentage(100);

        for (int i = 0; i < t_client.getColumnCount(); i++) {
            Paragraph header = new Paragraph(t_client.getColumnName(i));
            header.setAlignment(1);
            tabla.addCell(header);
        }

        for (int i = 0; i < t_client.getRowCount(); i++) {
            for (int a = 0; a < t_client.getColumnCount(); a++) {

                Paragraph campo = new Paragraph(String.valueOf(t_client.getValueAt(i, a)));
                campo.setAlignment(1);
                tabla.addCell(campo);
            }
        }

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

        //Tabla_Vehiculos
        String Vehiculos_header = "VEHICULO";

        Paragraph Title1 = new Paragraph(Vehiculos_header.toUpperCase());
        Title1.setAlignment(1);
        documento.add(Title1);
        documento.add(new Paragraph(" "));

        PdfPTable tabla_vehiculos = new PdfPTable(t_vehiculos.getColumnCount());

        tabla_vehiculos.setWidthPercentage(100);

        for (int i = 0; i < t_vehiculos.getColumnCount(); i++) {
            Paragraph header = new Paragraph(t_vehiculos.getColumnName(i));
            header.setAlignment(1);
            tabla_vehiculos.addCell(header);
        }

        for (int i = 0; i < t_vehiculos.getRowCount(); i++) {
            for (int a = 0; a < t_vehiculos.getColumnCount(); a++) {

                Paragraph campo = new Paragraph(String.valueOf(t_vehiculos.getValueAt(i, a)));
                campo.setAlignment(1);
                tabla_vehiculos.addCell(campo);
            }
        }

        documento.add(tabla_vehiculos);
        documento.add(new Paragraph("SERVICIO SOLICITADO: " + s_solicitado.toUpperCase()));
        documento.add(new Paragraph("SERVICIO REALIZADO: " + s_realizado.toUpperCase()));
        String var = "";
        if (p_urgente) {
            var = "URGENTE";
        } else {
            var = "PROGRAMAR";
        }
        documento.add(new Paragraph("PRIORIDAD: " + var));

        //Tabla de servicios y productos
        String Service_header = "\nSERVICIOS Y PRODUCTOS UTILIZADOS";

        Paragraph Title2 = new Paragraph(Service_header.toUpperCase());
        Title2.setAlignment(1);
        documento.add(Title2);
        documento.add(new Paragraph(" "));

        JTable t_productos = new JTable();

        Table_LoadProductsServicio(t_productos);

        String[] result = productos.replace("+", ",").split(",");

        if (result.length >= 1) {
            for (String r : result) {
                if (!r.equalsIgnoreCase("") || !r.isEmpty()) {
                    if (ExistProduct(r)) {
                        Table_AddProductsServicio(t_productos, r);
                    }
                }
            }
        }

        PdfPTable tabla_PRODUCTS = new PdfPTable(t_productos.getColumnCount());

        tabla_PRODUCTS.setWidthPercentage(100);

        for (int i = 0; i < t_productos.getColumnCount(); i++) {
            Paragraph header = new Paragraph(t_productos.getColumnName(i));
            header.setAlignment(1);
            tabla_PRODUCTS.addCell(header);
        }

        for (int i = 0; i < t_productos.getRowCount(); i++) {
            for (int a = 0; a < t_productos.getColumnCount(); a++) {

                Paragraph campo = new Paragraph(String.valueOf(t_productos.getValueAt(i, a)));
                campo.setAlignment(1);
                tabla_PRODUCTS.addCell(campo);
            }
        }

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

        documento.add(new Paragraph("COSTO TOTAL DE SERVICIO $ " + total));
        documento.add(
                new Paragraph("FECHA Y HORA DE ENTREGA: ____________________________________________________"));
        documento.add(
                new Paragraph("NOMBRE Y FIRMA DEL QUE REALIZA: _____________________________________________"));
        documento.add(
                new Paragraph("CONFORMIDAD, NOMBRE Y FIRMA DE QUIEN RECIBE: _______________________________"));
        documento.add(
                new Paragraph("PROXIMO SERVICIO: ___________________________________________________________"));

        Paragraph footer = new Paragraph("SOFTWARE Y MAS ! - WWW.CYBERCHOAPAS.COM");
        footer.setAlignment(1);
        documento.add(footer);

        documento.close();
        Desktop.getDesktop().open(ruta);
    } catch (IOException | DocumentException ex) {
        Alert(ex.getMessage());
    } catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException ex) {
        Alert(ex.getMessage());
    }
}

From source file:Clases.NuevoPdf.java

public static void main() {
    try {/* www .jav a 2 s .c  om*/
        /*Espaciador*/
        Paragraph espaciador = new Paragraph();
        addEmptyLine(espaciador, 2);
        /**
         *
         */
        Document document = new Document();
        if (Variables.guardar == false) {
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
        } else {

            JFileChooser dig = new JFileChooser();
            int opcion = dig.showSaveDialog(null);

            if (opcion == JFileChooser.APPROVE_OPTION) {
                File f = dig.getSelectedFile();
                String Direccion = f.toString();
                FileOutputStream archivo = new FileOutputStream(Direccion + ".pdf");
                PdfWriter.getInstance(document, archivo);
                Variables.guardar = false;
            }
        }
        //Document document = new Document();
        // PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();
        addMetaData(document);
        addTitlePage(document);
        document.add(espaciador);
        addTableClienteYFactura(document);
        document.add(espaciador);
        addTableProducts(document);
        document.add(espaciador);
        addTableTotales(document);
        addFooter(document);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Clases.PDF.java

public void crearPDF(String filename, String nombre, String objetosComprados)
        throws DocumentException, IOException {
    // step 1/*from  w w w. ja va2s  .c om*/
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4

    /*   Image image1 = Image.getInstance("/Users/davfer29/NetBeansProjects/DiarioFacilWeb/build/web/images/client.png");
      document.add(image1);     
     image1.scaleAbsolute(150f, 150f);*/ //esto se usa para adjuntar imagenes al pdf y centrarlas  

    document.addTitle("Bienvenido a DiarioFacil");
    document.add(new Paragraph("Su compra de los articulos " + objetosComprados + " ha sido exitosa"));
    document.add(new Paragraph("Gracias! Agradecemos que haya elegido nuestra pagina " + nombre));
    // step 5
    document.close();
}

From source file:Classes.GerarPdf.java

public static void main(String arg[]) throws Exception {

    File arquivo = new File("odontograma.pdf");

    System.out.print(arquivo.getAbsolutePath());

    File file = new File(arquivo.getAbsolutePath());
    file.delete();/* www  .jav  a  2 s.co m*/

    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("odontograma.pdf"));
    document.open();
    document.add(new Paragraph("ODONTOGRAMA"));
    document.add(new Paragraph("\nCodigo Paciente: " + arg[0]));
    document.add(new Paragraph("Nome Paciente: " + arg[1]));
    document.add(new Paragraph("Codigo Procedimento: " + arg[2]));
    document.add(new Paragraph("Procedimento: " + arg[3]));
    document.add(new Paragraph("\nDetalhes : " + arg[4]));
    document.add(new Paragraph("\nValor : " + arg[5]));

    document.close();

}

From source file:classes.PdfFiles.java

public static void createPdf(java.util.List<Product> selling_list) {
    try {/*  w  w w  .j  a v a 2 s  .c  om*/
        /*Create new document*/
        Document document = new Document();

        /*Path and name based on date*/
        String FILE = "C:/Users/Dominik/Computer-Service-ERP/Pliki PDF/Faktura - "
                + new Date().toString().substring(4, 11) + new Date().toString().substring(25) + '-'
                + new Date().toString().substring(11, 13) + new Date().toString().substring(14, 16)
                + new Date().toString().substring(17, 19) + ".pdf";

        /*Open file*/
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();

        /*Title*/
        addTitlePage(document);

        /*Table*/
        createTable(document, selling_list);

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