Vista.GenerarPDF.java Source code

Java tutorial

Introduction

Here is the source code for Vista.GenerarPDF.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.Administrar_Mantenimientos;
import Modelo.Detalle_Mantenimiento;
import Modelo.Mantenimientos;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author jordans
 */
public class GenerarPDF extends javax.swing.JFrame {

    /**
     * Creates new form GenerarPDF
     */
    public GenerarPDF() {
        initComponents();
        btngenerar.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btngenerar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cmbtiponave = new javax.swing.JComboBox<String>();
        txtruta = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        btnMenu = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btngenerar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/botones/pdf.png"))); // NOI18N
        btngenerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btngenerarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
        jLabel1.setText("Generar Informes de Mantenimientos");

        jLabel2.setText("Seleccione el tipo de nave");

        cmbtiponave.setModel(
                new javax.swing.DefaultComboBoxModel(new String[] { "Helicptero BK-117", "Avion Cessna-172" }));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/botones/ruta.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("Seleccione ruta donde se guardara el informe");

        btnMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/botones/regresar.png"))); // NOI18N
        btnMenu.setBorder(null);
        btnMenu.setBorderPainted(false);
        btnMenu.setContentAreaFilled(false);
        btnMenu.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMenuActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup()
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnMenu).addGap(50, 50, 50)
                                .addComponent(
                                        btngenerar, javax.swing.GroupLayout.PREFERRED_SIZE, 158,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(200, 200, 200))
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup().addComponent(jLabel3)
                                                .addGap(18, 18, 18)
                                                .addComponent(txtruta, javax.swing.GroupLayout.PREFERRED_SIZE, 211,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 116,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(layout.createSequentialGroup().addComponent(jLabel2)
                                                .addGap(49, 49, 49).addComponent(cmbtiponave,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(98, 98, 98))
                        .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 691, Short.MAX_VALUE)
                                .addContainerGap()))));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 71,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel2).addComponent(cmbtiponave,
                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup().addGap(34, 34, 34).addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jLabel3)
                                                .addComponent(txtruta, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGroup(layout.createSequentialGroup().addGap(25, 25, 25).addComponent(
                                                jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 36,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 197,
                                        Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(btngenerar, javax.swing.GroupLayout.PREFERRED_SIZE, 36,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btnMenu))
                                .addGap(17, 17, 17)));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btngenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btngenerarActionPerformed
        String nave = "" + cmbtiponave.getSelectedItem();
        String ruta = txtruta.getText();
        try {
            FileOutputStream archivo = new FileOutputStream(ruta + ".pdf");

            Document doc = new Document();
            PdfWriter.getInstance(doc, archivo);
            doc.open();
            Paragraph parrafo2 = new Paragraph("INFORME DE MANTENIMIENTOS");
            parrafo2.setAlignment(1);//el 1 es para centrar
            doc.add(parrafo2);

            doc.add(new Phrase(Chunk.NEWLINE));
            doc.add(new Phrase(Chunk.NEWLINE));

            doc.add(new Paragraph(
                    "Acontinuacion se muestra una lista de los mantenimientos realizados a la aeronave " + nave
                            + ""));
            doc.add(new Phrase(Chunk.NEWLINE));
            PdfPTable tabla = new PdfPTable(6);
            tabla.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabla.setTotalWidth(PageSize.A4.getWidth() - 10);
            //el numero indica la cantidad de Columnas

            tabla.addCell("ID");
            tabla.addCell("Matricula");
            tabla.addCell("Estado");
            tabla.addCell("Tareas");
            tabla.addCell("Fecha inicio");
            tabla.addCell("Fecha termino");
            tabla.setWidths(new int[] { 1, 2, 4, 4, 3, 3 });
            Administrar_Mantenimientos av = new Administrar_Mantenimientos();

            ArrayList<Detalle_Mantenimiento> listaMantenimientos = av.listarMantenimientosMatricula(nave);
            for (int i = 0; i < listaMantenimientos.size(); i++) {
                tabla.addCell(String.valueOf(listaMantenimientos.get(i).getId()));
                tabla.addCell(listaMantenimientos.get(i).getMatricula());
                tabla.addCell(listaMantenimientos.get(i).getEstado());
                tabla.addCell(listaMantenimientos.get(i).getTareas_seleccionadas());
                tabla.addCell(listaMantenimientos.get(i).getFecha_inicio());
                tabla.addCell(listaMantenimientos.get(i).getFecha_termino());
            }

            // esto nos crea una tabla de 3 Columnas por 2 Filas
            doc.add(tabla);
            doc.close();
            JOptionPane.showMessageDialog(null, "PDF CREADO CON EXITO");

        } catch (Exception e) {
            System.out.println("error" + e);
        }

    }//GEN-LAST:event_btngenerarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        JFileChooser dlg = new JFileChooser();
        int OPTION = dlg.showSaveDialog(this);
        if (OPTION == JFileChooser.APPROVE_OPTION) {
            File f = dlg.getSelectedFile();
            txtruta.setText(f.toString());
        }
        btngenerar.setEnabled(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMenuActionPerformed
        MenuConsultor menu = new MenuConsultor();
        menu.setLocationRelativeTo(null);
        menu.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_btnMenuActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        //        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
        //         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
        //         */
        //        try {
        //            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        //                if ("Nimbus".equals(info.getName())) {
        //                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
        //                    break;
        //                }
        //            }
        //        } catch (ClassNotFoundException ex) {
        //            java.util.logging.Logger.getLogger(IngresarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        //        } catch (InstantiationException ex) {
        //            java.util.logging.Logger.getLogger(IngresarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        //        } catch (IllegalAccessException ex) {
        //            java.util.logging.Logger.getLogger(IngresarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        //        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        //            java.util.logging.Logger.getLogger(IngresarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        //        }
        //        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GenerarPDF().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnMenu;
    private javax.swing.JButton btngenerar;
    private javax.swing.JComboBox<String> cmbtiponave;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField txtruta;
    // End of variables declaration//GEN-END:variables
}