Java tutorial
/* * 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 com.pdfExtract; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.AcroFields.Item; import com.itextpdf.text.pdf.PdfReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.RowFilter.Entry; import javax.swing.UIManager; import javax.swing.*; import static javax.swing.JOptionPane.NO_OPTION; import static javax.swing.JOptionPane.showInputDialog; /** * * @author abougeniere */ public class pdfExtract extends javax.swing.JFrame { private String[] files = null; private int nbrFichiersPDF = 0; private DefaultListModel listeFichiersPDF; private String nomFichierDestination = null; /** * Creates new form pdfExtract */ public pdfExtract() { initComponents(); this.setLocationRelativeTo(null); String defaultLookAndFeel = UIManager.getSystemLookAndFeelClassName(); //UIManager.setLookAndFeel(defaultLookAndFeel); try { UIManager.setLookAndFeel(defaultLookAndFeel); } catch (ClassNotFoundException ex) { Logger.getLogger(pdfExtract.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(pdfExtract.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(pdfExtract.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(pdfExtract.class.getName()).log(Level.SEVERE, null, ex); } } public void scanFields(String sourceFile, String destinationFile, int index) throws IOException { // le fichier existe dj ? File f = new File(destinationFile); if (f.exists() && !f.isDirectory()) { JOptionPane optionPane = new JOptionPane("Le fichier existe dj.\nRemplacer le fichier ?\n", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION); } PdfReader pdfReader; pdfReader = new PdfReader(sourceFile); AcroFields acroFields = pdfReader.getAcroFields(); // Create a reader to extract info PrintWriter writer = new PrintWriter(new FileOutputStream(destinationFile, true)); // Create a reader to extract info PdfReader reader = new PdfReader(sourceFile); // Get the fields from the reader (read-only!!!) AcroFields form = reader.getAcroFields(); Set<String> fields = form.getFields().keySet(); // affichage entete (nom des champs) if (index == 0) { for (String key : fields) { writer.append(key + ";"); } writer.append("\n"); } // affichage valeur des champs for (String key : fields) { String t; t = form.getField(key); writer.append(form.getField(key)); writer.append(";"); } writer.append("\n"); writer.close(); } /** * 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() { ConversionPDF = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); chooseDirectoryButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); listeFichiers = new javax.swing.JList(); jSeparator2 = new javax.swing.JSeparator(); dossierSource = new javax.swing.JTextField(); infoBar = new javax.swing.JLabel(); jSeparator3 = new javax.swing.JSeparator(); choixFichierDestination = new javax.swing.JButton(); nomFichierDestinationText = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); ProgressionBar = new javax.swing.JProgressBar(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Pdf2Csv - Conversion PDF vers CSV"); ConversionPDF.setText("Executer la conversion vers CSV / Excel"); ConversionPDF.setEnabled(false); ConversionPDF.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ConversionPDFActionPerformed(evt); } }); chooseDirectoryButton.setText("Choisir le dossier contenant les PDF"); chooseDirectoryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chooseDirectoryButtonActionPerformed(evt); } }); jScrollPane1.setViewportView(listeFichiers); dossierSource.setEditable(false); choixFichierDestination.setText("Choisir le fichier de destination"); choixFichierDestination.setEnabled(false); choixFichierDestination.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { choixFichierDestinationActionPerformed(evt); } }); nomFichierDestinationText.setEditable(false); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setText("1"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel2.setText("2"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel3.setText("3"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1).addComponent(jSeparator2) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout .createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2).addComponent(jLabel1).addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addComponent(ConversionPDF) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ProgressionBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(4, 4, 4)) .addGroup(layout.createSequentialGroup().addComponent(chooseDirectoryButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(dossierSource)) .addGroup(layout.createSequentialGroup() .addComponent(choixFichierDestination) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(nomFichierDestinationText)))) .addGroup(layout.createSequentialGroup().addGap(36, 36, 36).addComponent(infoBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE))) .addContainerGap()) .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING)); 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.LEADING).addComponent(jLabel1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(chooseDirectoryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(dossierSource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(infoBar, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(choixFichierDestination, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nomFichierDestinationText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(8, 8, 8).addComponent( ProgressionBar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ConversionPDF, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE))); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] { ConversionPDF, choixFichierDestination, chooseDirectoryButton }); getAccessibleContext().setAccessibleDescription(""); pack(); }// </editor-fold>//GEN-END:initComponents private void ConversionPDFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConversionPDFActionPerformed // setup progressionBar ProgressionBar.setMinimum(0); ProgressionBar.setMaximum(nbrFichiersPDF); // Efface le fichier si il existe File f = new File(nomFichierDestination); if (f.exists() && !f.isDirectory()) { f.delete(); } // Extraction des pdf for (int n = 0; n < nbrFichiersPDF; n++) { ProgressionBar.setValue(n + 1); try { scanFields(dossierSource.getText() + "\\" + (String) listeFichiersPDF.getElementAt(n), nomFichierDestination, n); } catch (IOException ex) { Logger.getLogger(pdfExtract.class.getName()).log(Level.SEVERE, null, ex); } } JOptionPane.showMessageDialog(null, "Conversion termine.\nLe fichier ".concat(nomFichierDestination).concat(" est cr."), "Conversion termine", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_ConversionPDFActionPerformed /* Slection rpertoire ou sont stocks les PDF */ private void chooseDirectoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseDirectoryButtonActionPerformed JFileChooser fileChooser; fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); listeFichiersPDF = new DefaultListModel(); String fileNameFilterPattern; fileNameFilterPattern = ".pdf"; int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedDirectory = fileChooser.getSelectedFile(); try { dossierSource.setText(selectedDirectory.getCanonicalPath()); //ArrayList<String> pdfFiles = new ArrayList<String>(); files = selectedDirectory.list(); if (files.length != 0) { for (int i = 0; i < files.length; i++) { if (fileNameFilterPattern == null || files[i].contains(fileNameFilterPattern)) { //pdfFiles.add(this.files[i]); listeFichiersPDF.addElement(files[i]); } } } listeFichiers.setModel(listeFichiersPDF); // Affiche le nombre de fichiers que l'on va extraire nbrFichiersPDF = listeFichiers.getModel().getSize(); if (nbrFichiersPDF == 0) { infoBar.setText("Aucun fichier extraire"); choixFichierDestination.setEnabled(false); } else if (nbrFichiersPDF == 1) { infoBar.setText("1 fichier extraire"); choixFichierDestination.setEnabled(true); } else { infoBar.setText(nbrFichiersPDF + " fichiers extraire"); choixFichierDestination.setEnabled(true); } } catch (IOException ex) { Logger.getLogger(pdfExtract.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_chooseDirectoryButtonActionPerformed private void choixFichierDestinationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_choixFichierDestinationActionPerformed JFileChooser fileChooser; fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); nomFichierDestination = ""; nomFichierDestinationText.setText(nomFichierDestination); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFileHandle = fileChooser.getSelectedFile(); /* int dot = fullPath.lastIndexOf("."); String ext = fullPath.substring(dot + 1); */ File f = new File(selectedFileHandle.toString() + ".csv"); if (f.exists() && !f.isDirectory()) { if (JOptionPane.showConfirmDialog(null, "Le fichier existe dj, le remplacer ?", "Le fichier existe dj", JOptionPane.YES_NO_OPTION) == NO_OPTION) { return; } } nomFichierDestination = selectedFileHandle.toString() + ".csv"; nomFichierDestinationText.setText(nomFichierDestination); ConversionPDF.setEnabled(true); } }//GEN-LAST:event_choixFichierDestinationActionPerformed /* */ /** * @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(pdfExtract.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(pdfExtract.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(pdfExtract.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(pdfExtract.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 pdfExtract().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ConversionPDF; private javax.swing.JProgressBar ProgressionBar; private javax.swing.JButton choixFichierDestination; private javax.swing.JButton chooseDirectoryButton; private javax.swing.JTextField dossierSource; private javax.swing.JLabel infoBar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JList listeFichiers; private javax.swing.JTextField nomFichierDestinationText; // End of variables declaration//GEN-END:variables }