nominas.sei.form.Principal.java Source code

Java tutorial

Introduction

Here is the source code for nominas.sei.form.Principal.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 nominas.sei.form;

import java.awt.Rectangle;
import java.awt.print.PageFormat;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import nominas.sei.PaginaNomina;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.PDFTextStripperByArea;

/**
 *
 * @author jmoron
 */
public class Principal extends javax.swing.JFrame {

    /**
     * Creates new form Principal
     */
    public Principal() {
        initComponents();
    }

    /**
     * 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() {

        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Ordenar");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout
                        .createSequentialGroup().addContainerGap().addComponent(jButton1,
                                javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(594, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout
                        .createSequentialGroup().addContainerGap().addComponent(jButton1,
                                javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(502, Short.MAX_VALUE)));

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        // Abrimos Ventana para seleccionar archivo de nominas
        String entrada = "";
        String salida = "";
        JFileChooser fChoser = new JFileChooser();
        int opcion = fChoser.showOpenDialog(this);

        boolean seguir = false;
        if (opcion == JFileChooser.APPROVE_OPTION) {
            entrada = fChoser.getSelectedFile().getPath(); //Obtiene path del archivo
            seguir = true;
        }
        if (seguir) {
            seguir = false;
            fChoser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fChoser.setCurrentDirectory(new File(entrada));
            opcion = fChoser.showSaveDialog(this);
            if (opcion == JFileChooser.APPROVE_OPTION) {
                salida = fChoser.getSelectedFile().getPath(); //Obtiene path del archivo
                seguir = true;
            }
        }
        System.out.println(entrada);
        salida = salida + "\\Nominas Ordenadas.pdf";
        System.out.println(salida);
        //Pasamos direccion del archivo de nominas
        //Seleccionamos archivo para guardar las nominas ordenadas

        //Ejecutamos el procedimiento.
        ordenaNominas(entrada, salida);
    }//GEN-LAST:event_jButton1MouseClicked

    /**
     * @param args the command line arguments
     */
    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(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.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 Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    // End of variables declaration//GEN-END:variables
    //Procedimientos

    private void ordenaNominas(String rutaEntrada, String rutaSalida) {
        ArrayList<PaginaNomina> paginasNomina = new ArrayList<PaginaNomina>();

        for (int x = 0; x < 1; x++) {//RECORREMOS EL ARREGLO CON LOS NOMBRES DE ARCHIVO

            try {
                PDDocument pd = PDDocument.load(rutaEntrada); //CARGAR EL PDF
                List l = pd.getDocumentCatalog().getAllPages();//NUMERO LAS PAGINAS DEL ARCHIVO
                Object[] obj = l.toArray();//METO EN UN OBJETO LA LISTA DE PAGINAS PARA MANIPULARLA
                for (int i = 0; i < l.size(); i++) {
                    PDPage page = (PDPage) obj[i];//PAGE ES LA PAGINA 1 DE LA QUE CONSTA EL ARCHIVO
                    PageFormat pageFormat = pd.getPageFormat(0);//PROPIEDADES DE LA PAGINA (FORMATO)
                    Double d1 = new Double(pageFormat.getHeight());//ALTO
                    Double d2 = new Double(pageFormat.getWidth());//ANCHO
                    int width = d1.intValue();//ANCHO
                    int eigth = 1024;//ALTO

                    PDFTextStripperByArea stripper = new PDFTextStripperByArea();//COMPONENTE PARA ACCESO AL TEXTO
                    Rectangle rect = new Rectangle(0, 0, width, eigth);//DEFNIR AREA DONDE SE BUSCARA EL TEXTO
                    stripper.addRegion("area1", rect);//REGISTRAMOS LA REGION CON UN NOMBRE
                    stripper.extractRegions(page);//EXTRAE TEXTO DEL AREA

                    String contenido = new String();//CONTENIDO = A LO QUE CONTENGA EL AREA O REGION
                    contenido = (stripper.getTextForRegion("area1"));
                    String[] lines = contenido.split("[\\r\\n]+");
                    String nombre = lines[1].substring(28, lines[1].length() - 10);//Separamos el nombre
                    PaginaNomina nomina = new PaginaNomina(page, nombre);
                    paginasNomina.add(nomina);
                }
                Collections.sort(paginasNomina);
                // Create a new empty document
                PDDocument document = new PDDocument();

                for (int i = 0; i < paginasNomina.size(); i++) {
                    System.out.println(paginasNomina.get(i).getNombre());
                    document.addPage(paginasNomina.get(i).getPagina());
                }
                // Save the newly created document
                document.save(rutaSalida);

                // finally make sure that the document is properly
                // closed.
                document.close();
                pd.close();//CERRAMOS OBJETO ACROBAT
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } //CATCH
        } //FOR
    }
}