lecteur.Interface.java Source code

Java tutorial

Introduction

Here is the source code for lecteur.Interface.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 lecteur;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author tbalandier
 */
public class Interface extends javax.swing.JFrame {

    private static void veriftabbilan(ArrayList<Bilan> tab) {
        //Verifier si la la 2nd rubrique est gale  la premire
        //Si c'est la cas, la deuxime = 0
        Bilan bil1;
        Bilan bil2;

        if (tab.size() == 2) {
            bil1 = tab.get(0);
            bil2 = tab.get(1);

            if (bil1.getValeur() == bil2.getValeur()) {
                tab.get(1).setValeur(0);
            }
        }
    }

    /**
     * Creates new form Interface
     */

    private DocPDF doc;

    public Interface() {
        initComponents();
        this.doc = new DocPDF();
    }

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

        lb_fichier = new javax.swing.JLabel();
        button_parcourir = new javax.swing.JButton();
        button_lire = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        text_form = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lb_fichier.setText("Nom du fichier");
        lb_fichier.setToolTipText("");
        lb_fichier.setName("lb_fichier"); // NOI18N

        button_parcourir.setLabel("Parcourir...");
        button_parcourir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_parcourirActionPerformed(evt);
            }
        });

        button_lire.setText("Lire");
        button_lire.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_lireActionPerformed(evt);
            }
        });

        text_form.setEditable(false);
        text_form.setColumns(20);
        text_form.setRows(5);
        jScrollPane1.setViewportView(text_form);
        text_form.getAccessibleContext().setAccessibleName("text_form");

        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(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(button_lire, javax.swing.GroupLayout.Alignment.TRAILING,
                                        javax.swing.GroupLayout.PREFERRED_SIZE, 94,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(lb_fichier).addComponent(button_parcourir)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup().addGap(0, 161, Short.MAX_VALUE)
                                        .addComponent(lb_fichier).addGap(18, 18, 18).addComponent(button_parcourir)
                                        .addGap(76, 76, 76).addComponent(button_lire,
                                                javax.swing.GroupLayout.PREFERRED_SIZE, 46,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jScrollPane1))
                        .addContainerGap()));

        lb_fichier.getAccessibleContext().setAccessibleName("lb_ficher");
        button_parcourir.getAccessibleContext().setAccessibleName("button_parcourir");
        button_lire.getAccessibleContext().setAccessibleName("button_lire");

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

    private void button_parcourirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_parcourirActionPerformed
        // TODO add your handling code here:

        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Documents", "pdf");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.doc.setNom(chooser.getSelectedFile().getName());
            this.doc.setChemin(chooser.getSelectedFile().getPath());

            this.lb_fichier.setText(doc.getNom());

            //test affichage
            this.doc.show();
        }
    }//GEN-LAST:event_button_parcourirActionPerformed

    private void button_lireActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_lireActionPerformed
        // TODO add your handling code here:
        String text = "";
        //this.doc.show();
        text = ReadPDF(this.doc.getChemin());

        if (text.equals("")) {
            this.lb_fichier.setText("Nom du fichier.");
            this.text_form.setText("");
        } else {
            this.text_form.setText(text);
        }
    }//GEN-LAST:event_button_lireActionPerformed

    public void createPdf(String filename) throws DocumentException, IOException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph("Hello World!"));
        document.add(new Paragraph("Hello Me"));
        // step 5
        document.close();
    }

    private static String ReadPDF(String pdf_url) {
        String[] row;
        ArrayList<Bilan> tabRubriqueBilanTotal = new ArrayList<>();
        ArrayList<Bilan> tabRubriqueBilan = null;
        System.out.println("ReadPDF");

        StringBuilder str = new StringBuilder();

        try {
            PdfReader reader = new PdfReader(pdf_url);
            int nbpage = reader.getNumberOfPages();
            System.out.println("Nombre de page = " + nbpage);
            //Recherche page BILAN - ACTIF
            //Recherche page BILAN - PASSIF
            //Recherche page 
            //pour chaque page, lire ligne.
            for (int i = 22; i <= 22; i++) {
                //for(int i=1;i<=nbpage;i++) {
                String str2 = PdfTextExtractor.getTextFromPage(reader, i);
                //System.out.println("STR2 = " + str2);
                //System.out.println("===========================");

                row = null;
                //Concatener les pages :
                //str.append(str2);
                //System.out.println("STR = " + str);

                //Appel fonction split chaque ligne de la page.
                row = splitPage(str2);
                System.out.println();
                System.out.println("\nnb row  traiter = " + row.length);

                //recherche de correspondance AA, AF, ect..
                //Recherche deux majuscules suivis d'espaces et nombre/espace/nombre
                //TODO
                //Gerer les cas o il n'y a pas de chiffre
                String pattern1 = "[A-Z]{2}";
                String pattern = "[A-Z]{2}\\p{Space}+\\d+\\p{Space}?\\d+";
                for (int j = 0; j < row.length; j++) {
                    System.out.println("\nLigne  traiter AVANT FCT: " + row[j]);
                    //TAB_BILAN par ligne
                    tabRubriqueBilan = recherchebilan(row[j], pattern);
                    for (int k = 0; k < tabRubriqueBilan.size(); k++) {
                        tabRubriqueBilanTotal.add(tabRubriqueBilan.get(k));
                    }
                }

                for (int j = 0; j < tabRubriqueBilanTotal.size(); j++) {
                    tabRubriqueBilanTotal.get(j).show();
                }

                System.out.println("TAILLE TAB PAR PAGE = " + tabRubriqueBilanTotal.size());
            }
            afficheResultat(tabRubriqueBilanTotal);

        } catch (Exception err) {
            err.printStackTrace();
        }
        return String.format("%s", str);
    }

    //stock chaque ligne dans un tableau de str.
    private static String[] splitPage(String page) {
        String[] row = null;

        row = page.split("(?m)\n");
        //row = page.split("(?m)^.*$");

        return row;
    }

    private static ArrayList<Bilan> recherchebilan(String ligne, String pattern) {

        ArrayList<Bilan> tab = new ArrayList<>();
        Bilan bil;
        String resultat;
        String rubrique;
        Integer valeur;

        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(ligne);

        while (m.find()) {
            //System.out.println("MATCH");
            //Cratoin d'un nouveau bilan
            bil = new Bilan();
            resultat = ligne.substring(m.start(), m.end());
            System.out.println(resultat);

            //Get rubrique du resultat
            rubrique = getRubriqueRegex(resultat);
            //Get valeur du resultat
            valeur = getValeurRegex(resultat);

            bil.setNom(rubrique);
            bil.setValeur(valeur);

            tab.add(bil);

            //System.out.println("TAILLE TAB PAR LIGNE = " + tab.size());
        }
        veriftabbilan(tab);

        for (int i = 0; i < tab.size(); i++) {
            tab.get(i).show();
        }

        return tab;
    }

    private static Integer getValeurRegex(String resultat) {
        Integer res;
        String[] strsplit;
        String str;

        strsplit = resultat.split("[a-zA-Z]+");
        str = strsplit[1].replaceAll(" ", "");
        res = Integer.parseInt(str);

        return res;
    }

    private static String getRubriqueRegex(String resultat) {
        String res = null;
        String pattern;

        pattern = "[a-zA-Z]{2}";

        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(resultat);

        while (m.find()) {
            res = (resultat.substring(m.start(), m.end()));
        }
        return res;
    }

    private static void afficheResultat(ArrayList<Bilan> tabRubriqueBilanTotal) {

        for (int i = 0; i < tabRubriqueBilanTotal.size(); i++) {

        }
    }

    /**
     * @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 | InstantiationException | IllegalAccessException
                | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>

        //</editor-fold>

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton button_lire;
    private javax.swing.JButton button_parcourir;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lb_fichier;
    private javax.swing.JTextArea text_form;
    // End of variables declaration//GEN-END:variables
}