Download Código fuente. Generador de Historiales Académicos
Document related concepts
no text concepts found
Transcript
Código fuente. Generador de Historiales Académicos (Kardexs) //Archivo Main.java package historiales; /** * * @author Alberto */ public class Main { public static void main (String[] arg){ /////////////////////////////////////////////////////// java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GUI().setVisible(true); //new GUI_1().setVisible(true); } }); /////////////////////////////////////////////////////// } } //Archivo GUI.java package historiales; import javax.swing.JFileChooser; /** * * @author Alberto */ public class GUI extends javax.swing.JFrame { 1 Código fuente. Generador de Historiales Académicos (Kardexs) /** Creates new form GUI */ public GUI() { initComponents(); initComponentes(); agregaListeners(); } /** 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"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); botonCalificaciones = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); botonCarpetaDestino = new javax.swing.JButton(); botonIniciar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); reportes = new javax.swing.JTextArea(); jLabel3 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); 2 Código fuente. Generador de Historiales Académicos (Kardexs) botonContacto = new javax.swing.JButton(); eliminarCeros = new javax.swing.JCheckBox(); clasificarActividades = new javax.swing.JCheckBox(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBounds(new java.awt.Rectangle(100, 100, 620, 570)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setMinimumSize(new java.awt.Dimension(620, 570)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setText("Seleccionar el archivo origen con las CALIFICACIONES:"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, -1)); jTextField1.setEditable(false); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 32, 489, -1)); botonCalificaciones.setText("Examinar"); botonCalificaciones.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonCalificacionesActionPerformed(evt); } }); getContentPane().add(botonCalificaciones, new 3 Código fuente. Generador de Historiales Académicos (Kardexs) org.netbeans.lib.awtextra.AbsoluteConstraints(505, 31, 88, -1)); jLabel2.setText("Seleccionar la CARPETA destino:"); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, -1, -1)); jTextField3.setEditable(false); getContentPane().add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 150, 489, -1)); botonCarpetaDestino.setText("Examinar"); botonCarpetaDestino.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonCarpetaDestinoActionPerformed(evt); } }); getContentPane().add(botonCarpetaDestino, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 150, 88, -1)); botonIniciar.setText("Iniciar la generación de historiales"); botonIniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonIniciarActionPerformed(evt); } }); getContentPane().add(botonIniciar, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 270, 330, 56)); reportes.setColumns(20); reportes.setEditable(false); 4 Código fuente. Generador de Historiales Académicos (Kardexs) reportes.setRows(5); jScrollPane1.setViewportView(reportes); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 340, 583, 166)); jLabel3.setText("Seleccionar archivo con datos de CONTACTO:"); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1)); jTextField2.setEditable(false); getContentPane().add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 489, -1)); botonContacto.setText("Examinar"); botonContacto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonContactoActionPerformed(evt); } }); getContentPane().add(botonContacto, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 90, 88, -1)); eliminarCeros.setSelected(true); eliminarCeros.setText("Eliminar actividades con calificación de 0.00 (cero)."); getContentPane().add(eliminarCeros, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 190, -1, -1)); clasificarActividades.setSelected(true); clasificarActividades.setText("Clasificar actividades por capítulos."); getContentPane().add(clasificarActividades, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 220, -1, -1)); 5 Código fuente. Generador de Historiales Académicos (Kardexs) }// </editor-fold> private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { } private void botonCarpetaDestinoActionPerformed(java.awt.event.ActionEvent evt) { } private void botonIniciarActionPerformed(java.awt.event.ActionEvent evt) { } private void botonCalificacionesActionPerformed(java.awt.event.ActionEvent evt) { } private void botonContactoActionPerformed(java.awt.event.ActionEvent evt) { } // Variables declaration - do not modify protected javax.swing.JButton botonCalificaciones; protected javax.swing.JButton botonCarpetaDestino; protected javax.swing.JButton botonContacto; protected javax.swing.JButton botonIniciar; protected javax.swing.JCheckBox clasificarActividades; protected javax.swing.JCheckBox eliminarCeros; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; protected javax.swing.JTextField jTextField1; protected javax.swing.JTextField jTextField2; protected javax.swing.JTextField jTextField3; 6 Código fuente. Generador de Historiales Académicos (Kardexs) protected javax.swing.JTextArea reportes; // End of variables declaration /** * variables declaradas por el programador. */ protected int repEnum; //para llevar un contador de la cantidad de avisos al usuairo protected JFileChooser fc; //para seleccionar el archivo y la carpeta. private String[] paths; private Historial g; //private Historial g; protected void initComponentes() { this.fc = new JFileChooser(); this.repEnum = 0; } /** * Método que muestra los avisos para el usuario. */ protected void avisar(String r, boolean n) { if (n) { repEnum += 1; reportes.append("-------------Reporte #" + repEnum + "-------------\n" + r + "\n"); } else { reportes.append(r + "\n"); } reportes.setCaretPosition(reportes.getDocument().getLength()); 7 Código fuente. Generador de Historiales Académicos (Kardexs) } private void agregaListeners() { Controlador cont = new Controlador(this); this.addWindowListener(cont); this.botonCalificaciones.addActionListener(cont); this.botonContacto.addActionListener(cont); this.botonCarpetaDestino.addActionListener(cont); this.botonIniciar.addActionListener(cont); }} //Archivo Controlador.java package historiales; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.LinkedList; import javax.swing.JFileChooser; /** * * @author Alberto */ public class Controlador implements ActionListener, WindowListener { /// Atributos principales GUI gui; //interfaz de usuairo Archivo arch; //acceso a los datos de los archivos de excel 8 Código fuente. Generador de Historiales Académicos (Kardexs) Historial hist; //para generar los historiales /// Atributos auxiliares LinkedList<Alumno> datos; //JFileChooser fc; public Controlador(GUI g) { this.gui = g; this.arch = new Archivo(); this.hist = new Historial(); } public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); // seleccionar CALIFICACIONES if (obj == this.gui.botonCalificaciones) { this.selectCalificaciones(); // seleccionar DATOS DE CONTACTO } else if (obj == this.gui.botonContacto) { this.selectDatosContacto(); // seleccionar CARPETA DESTINO } else if (obj == this.gui.botonCarpetaDestino) { this.selectCarpetaDestino(); // instrucción de GENERAR HITORIALES } else if (obj == this.gui.botonIniciar) { this.iniGeneracionHistoriales(); } } 9 Código fuente. Generador de Historiales Académicos (Kardexs) public void windowOpened(WindowEvent e) { } public void windowClosing(WindowEvent e) { System.exit(0); } public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } private boolean validarCampos() { boolean valido = true; if (this.gui.jTextField1.getText().isEmpty()) { valido = false; this.gui.avisar("Falta archivo con CALIFICACIONES.", false); } if (this.gui.jTextField2.getText().isEmpty()) { valido = false; this.gui.avisar("Falta archivo con DATOS DE CONTACTO.", false); } if (this.gui.jTextField3.getText().isEmpty()) { 10 Código fuente. Generador de Historiales Académicos (Kardexs) valido = false; this.gui.avisar("Falta seleccionar la CARPETA DESTINO.", false); } return valido; } private boolean validarArchivos() { boolean valido = true; if (!this.arch.esValido(1)) { valido = false; this.gui.avisar("El archivo con CALIFICACIONES es INVÁLIDO", false); } if (!this.arch.esValido(2)) { valido = false; this.gui.avisar("El archivo con DATOS DE CONTACTO es INVÁLIDO", false); } return valido; } private void selectCalificaciones() { String texto = ""; this.gui.fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int fcVal = this.gui.fc.showOpenDialog(this.gui); if (fcVal == JFileChooser.APPROVE_OPTION) { texto = new String(this.gui.fc.getSelectedFile().toString()); this.arch.setRuta(texto); this.hist.setOrigen(texto); 11 Código fuente. Generador de Historiales Académicos (Kardexs) this.gui.jTextField1.setText(texto); } else { this.gui.avisar("No se seleccionó el archivo con las calificaciones.", true); } } private void selectDatosContacto() { String texto = ""; this.gui.fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int fcVal = this.gui.fc.showOpenDialog(this.gui); if (fcVal == JFileChooser.APPROVE_OPTION) { texto = new String(this.gui.fc.getSelectedFile().toString()); this.arch.setRutaTels(texto); this.gui.jTextField2.setText(texto); } else { this.gui.avisar("No se seleccionó el archivo con los datos de contacto.", true); } } private void selectCarpetaDestino() { String texto = ""; this.gui.fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int fcVal = this.gui.fc.showOpenDialog(this.gui); if (fcVal == JFileChooser.APPROVE_OPTION) { texto = new String(this.gui.fc.getSelectedFile().toString()); this.hist.setDestino(texto); this.gui.jTextField3.setText(texto); } else { 12 Código fuente. Generador de Historiales Académicos (Kardexs) this.gui.avisar("No se seleccionó el archivo con los datos de contacto.", true); } } private void iniGeneracionHistoriales() { this.gui.avisar("Proceso iniciado.", true); //código para medir tiempos long ini = System.currentTimeMillis(); // if (this.validarCampos()) { if (this.validarArchivos()) { this.arch.elimCeros = this.gui.eliminarCeros.isSelected(); this.datos = this.arch.getDatos(); try { this.hist.setClasificaActividades(this.gui.clasificarActividades.isSelected()); this.hist.setEliminaCeros(this.gui.eliminarCeros.isSelected()); this.hist.setDatos(datos); this.hist.generarHistoriales(); } catch (Exception ex) { this.gui.avisar("Error al generar los historiales", false); } } else { this.gui.avisar("Se detuvo la generación de historiales.", false); } } else { this.gui.avisar("Se detuvo la generación de historiales.", false); 13 Código fuente. Generador de Historiales Académicos (Kardexs) } this.gui.avisar("Los " + this.hist.getGenerados() + " historiales se guardaron en la carpeta seleecionada.", false); //código para medir tiempos long fin = System.currentTimeMillis(); long dur = fin - ini; this.gui.avisar("Proceso finalizado.\nDuración: " + dur + "milisegundos.", false); // } } //Archivo Historial.java package historiales; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.ExceptionConverter; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfPageEventHelper; 14 Código fuente. Generador de Historiales Académicos (Kardexs) import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Iterator; import java.util.LinkedList; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger;/** * * @author Alberto */ public class Historial extends PdfPageEventHelper { private String origen; private String destino; private String telefonos; private String destinoCarpeta; private LinkedList<Alumno> datos; Archivo a; TreeMap subsistemas; String[] preposiciones; private boolean eliminaCeros; 15 Código fuente. Generador de Historiales Académicos (Kardexs) private boolean clasificaActividades; private int generados; Image fondo; protected PdfTemplate total; protected BaseFont helv; public Historial() { this.datos = new LinkedList<Alumno>(); this.origen = ""; this.destino = "c://"; this.destinoCarpeta = ""; this.telefonos = ""; this.generados = 0; this.subsistemas = new TreeMap(); this.generaSubsistemasCompletos(); this.generarPreposiciones(); this.fondo = null; } public void generarHistoriales() { //String pathFondo = "c:\\FOMIX\\Historiales\\fondo.tif"; if (this.fondo == null) { String pathFondo = "fondo.tif"; try { this.fondo = Image.getInstance(pathFondo); this.fondo.scalePercent(72f / fondo.getDpiX() * 100); //fondo.setWidthPercentage(24); 16 Código fuente. Generador de Historiales Académicos (Kardexs) this.fondo.setAbsolutePosition(0, 0); //fondo.setAlt("Imagen de fondo"); //document.add(fondo); } catch (IOException iOException) { System.err.println(iOException.getMessage()); } catch (DocumentException documentException) { System.err.println(documentException.getMessage()); } } this.generados = 0; try { this.generarPdfsFinal(); } catch (Exception e) { System.out.println("Excepción generarHistoriales(),generarPdfsFinal()"); } } public void generarPdfsFinal() throws Exception { // variables para la creación de los pdfs Document doc; PdfPTable tab; PdfPCell cel; Paragraph tex = new Paragraph(); Fuente f = new Fuente(); String docNom = ""; int center = Element.ALIGN_CENTER; 17 Código fuente. Generador de Historiales Académicos (Kardexs) //se crea la carpeta que almacenará los PDFs según el área. this.crearCarpeta(); //variables de los datos de los alumnos String[] nombre; String curso = "", subsist = "", act = "", telLoc = "", telCel = "", correo1 = "", correo2 = ""; short periodo = 0; Double calDiag = 0.0, calFinal = 0.0, promedio = 0.0, actCal = 0.0; String estado = ""; LinkedList<Actividad> acts = new LinkedList<Actividad>(); Calendar cal = Calendar.getInstance(); String fechaActual = new String( String.valueOf(cal.get(Calendar.DATE)) + "-" + String.valueOf(cal.get(Calendar.MONTH) + 1) + "-" + String.valueOf(cal.get(Calendar.YEAR))); //inicia el proceso de creación de pdf for (int i = 0; i < this.getDatos().size(); i++) { //se obtienen los datos del alumno 'i' nombre = getDatos().get(i).getNombreSep(); curso = getDatos().get(i).getCurso(); periodo = getDatos().get(i).getPeriodo(); subsist = getDatos().get(i).getSubsist(); calDiag = getDatos().get(i).getCalDiag(); calFinal = getDatos().get(i).getCalFinal(); promedio = getDatos().get(i).getPromedio(); acts = getDatos().get(i).getActividades(); 18 Código fuente. Generador de Historiales Académicos (Kardexs) telLoc = getDatos().get(i).getTelLocal(); telCel = getDatos().get(i).getTelCelular(); correo1 = getDatos().get(i).getCorreo1(); correo2 = getDatos().get(i).getCorreo2(); estado = getDatos().get(i).getEstado(); //inicializamos el formato del documento docNom = this.determinaNomDoc(curso, periodo, promedio, subsist, nombre); doc = new Document(PageSize.LETTER); doc.setMargins(80f, 56f, 92f, 35f); //doc.setMargins(izquierdo, derecho, superior, inferior); //se crea el archivo. try { PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(docNom)); writer.setPageEvent(this); } catch (DocumentException ex) { System.out.println("No se creó el archivo. DocumentException"); } catch (Exception e) { System.out.println("No se creó el archivo. Exception"); System.out.println(e.getMessage() + ". "); System.out.println(e.getCause()); } doc.open(); // SECCIÓN del encabezado del documento tex = new Paragraph(); tex.setFont(f.getF(2)); 19 Código fuente. Generador de Historiales Académicos (Kardexs) tex.setAlignment(Element.ALIGN_CENTER); tex.add("Historial Académico \n" + "Diplomado de actualización docente de nivel Medio Superior \n" + "con valor curricular por " + this.horasCurrciulares(curso) + " horas"); doc.add(tex); tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_CENTER); tex.add("\n Área de especialización:"); doc.add(tex); tex = new Paragraph(); tex.setFont(f.getF(2)); tex.setAlignment(Element.ALIGN_CENTER); tex.add(curso); doc.add(tex); ////////////////////// float[] col = {5f, 7f}; ////////////////////// doc.add(new Paragraph(" \n ")); /// DATOS DEL DOCENTE tab = new PdfPTable(1); tex = new Paragraph(); tex.setFont(f.getF(1)); tex.add("Datos del docente: \n"); 20 Código fuente. Generador de Historiales Académicos (Kardexs) cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); cel = new PdfPCell(new Paragraph(" ")); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); doc.add(tab); //fecha de última actualización tab = new PdfPTable(col); tab.setHorizontalAlignment(Element.ALIGN_CENTER); //// FECHA DE ACTUALIZACIÓN título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Fecha de actualización:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); //// FECHA DE ACTUALIZACIÓN contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("10 de enero de 2010"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); 21 Código fuente. Generador de Historiales Académicos (Kardexs) tab.addCell(cel); /// NOMBRE DEL DOCENTE título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Nombre del Docente:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// NOMBRE DEL DOCENTE contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.add(this.textoEnMayusMinus(nombre[0]) + " " + this.textoEnMayusMinus(nombre[1])); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// SUBSISTEMA título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Subsistema:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); 22 Código fuente. Generador de Historiales Académicos (Kardexs) /// SUBSISTEMA contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); try { tex.add(this.textoEnMayusMinus((String) this.subsistemas.get(subsist))); } catch (Exception e) { System.out.println("Subsistema"); } cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// TELÉFONOS título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Teléfono:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// TELÉFONOS contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.add(telLoc + " ; " + telCel); cel = new PdfPCell(tex); 23 Código fuente. Generador de Historiales Académicos (Kardexs) cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// CORREOS título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Correo electrónico:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// CORREOS contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.add(correo1 + " ; " + correo2); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); // SECCIÓN de las evaluaciones diagnóstica y final de alumno /// EVALUACIÓN DIAGNÓSTICA título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Evaluación Diagnóstica:"); cel = new PdfPCell(tex); 24 Código fuente. Generador de Historiales Académicos (Kardexs) cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// EVALUACIÓN DIAGNÓSTICA contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.add(calDiag.toString()); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// EVALUACIÓN FINAL título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Evaluación Final:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// EVALUACIÓN FINAL contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.add(calFinal.toString()); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); 25 Código fuente. Generador de Historiales Académicos (Kardexs) tab.addCell(cel); /// PROMEDIO ACTIVIDADES título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Promedio de las actividades del Diplomado:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// PROMEDIO ACTIVIDADES contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.add(this.califOk(promedio, 0.0)); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// MEJORA EN DESEMPREÑO "1" título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Mejora en desempeño 1:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// MEJORA EN DESEMPREÑO "1" contenido 26 Código fuente. Generador de Historiales Académicos (Kardexs) tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.setFont(f.getF(7)); if ((calFinal - calDiag) > 0) { tex.add("+"); } tex.add(this.califOk(calFinal, calDiag) + "/100 = "); if ((calFinal - calDiag) > 0) { tex.add("+"); } tex.add(this.califOk(calFinal, calDiag) + "%"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// MEJORA EN DESEMPREÑO "2" título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Mejora en desempeño 2:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// MEJORA EN DESEMPREÑO "2" contenido tex = new Paragraph(); 27 Código fuente. Generador de Historiales Académicos (Kardexs) tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); if ((promedio - calDiag) > 0) { tex.add("+"); } tex.add(this.califOk(promedio, calDiag) + "/100 = "); if ((promedio - calDiag) > 0) { tex.add("+"); } tex.add(this.califOk(promedio, calDiag) + "%"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// ESTADO (o situación del docente) título tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_LEFT); tex.add("Estado:"); cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// ESTADO (o situación del docente) contenido tex = new Paragraph(); tex.setFont(f.getF(7)); tex.setAlignment(Element.ALIGN_LEFT); tex.add(estado); 28 Código fuente. Generador de Historiales Académicos (Kardexs) cel = new PdfPCell(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); /// AGREGAMOS LA TABLA AL DOCUMENTO doc.add(tab); ////////////////////// col[0] = 5f; col[1] = 3f; ////////////////////// // SECCIÓN DE LAS FIRMAS ****AL PRINCIPIO DEL DOCUMENTO**** doc.add(new Paragraph("\n \n \n \n")); tab = new PdfPTable(2); tab.setWidthPercentage(100); //// RECTOR tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_CENTER); tex.setSpacingAfter(1); tex.add("Dr. Pablo Martín Buitrón Morales \n" + "Rector \n" + "Universidad Politécnica del Estado de Morelos \n"); cel = new PdfPCell(); cel.setBorder(Rectangle.NO_BORDER); cel.addElement(tex); tab.addCell(cel); 29 Código fuente. Generador de Historiales Académicos (Kardexs) //// SILVIA tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_CENTER); tex.setSpacingAfter(1); tex.add("cDra. en C. Silvia Melbi Gaona Jiménez \n" + "Profesora de Tiempo Completo \n" + "Universidad Politécnica del Estado de Morelos \n" + "Responsable Técnico del Proyecto \n" + "CONACYT MOR-2009-C01-116163"); cel = new PdfPCell(); cel.addElement(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); doc.add(tab); // SECCIÓN de las actividades del alumno con sus calificaciones. //// ENCABEZADO: LISTA DE ACTIVIDADES tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_CENTER); if (this.clasificaActividades) { tex.add("\n \n \n Actividades por Módulo"); } else{ tex.add("\n \n \n Actividades"); } 30 Código fuente. Generador de Historiales Académicos (Kardexs) doc.add(tex); ////se agregan las actividades al TreeSet tab = new PdfPTable(1); TreeSet activis = new TreeSet(); for (int g = 0; g < acts.size(); g++) { activis.add(acts.get(g)); } if (this.clasificaActividades) {// si se desea clasificar las actividades por capítulos //obtenemos el primer capítulo de la lista Actividad act1 = null; Iterator it = activis.iterator(); try { it.next(); it.next(); act1 = (Actividad) it.next(); } catch (Exception e) { System.out.println("Clasifica actividades"); doc.close(); continue; } short h = act1.getCapitulo(); boolean nuevoCap = true; boolean primerActivi = true; //se agregan las actividades al PDF while (it.hasNext()) { Actividad at = null; 31 Código fuente. Generador de Historiales Académicos (Kardexs) if (primerActivi) { at = act1; primerActivi = false; } else { at = (Actividad) it.next();//se obtiene la actividad } if (at.getCapitulo() != h) { doc.add(tab); nuevoCap = true; h = at.getCapitulo(); } if (nuevoCap) { doc.add(new Paragraph(" ")); tab = new PdfPTable(1); tex = new Paragraph(); tex.setFont(f.getF(1)); tex.add("Módulo " + h); cel = new PdfPCell(tex); cel.setHorizontalAlignment(center); tab.addCell(cel); doc.add(tab); col[0] = 4f; col[1] = 1f; tab = new PdfPTable(col); nuevoCap = false; 32 Código fuente. Generador de Historiales Académicos (Kardexs) } act = at.getNombre(); act = this.textoEnMayusMinus(act); actCal = at.getResult(); if (this.eliminaCeros) { if (actCal == 0.0) { continue; } } //nombre de actividad tex = new Paragraph(); tex.setFont(f.getF(1)); tex.add(act); tab.addCell(tex); //calificación de la actividad tex = new Paragraph(); tex.setFont(f.getF(1)); tex.add(actCal.toString()); cel = new PdfPCell(tex); cel.setHorizontalAlignment(center); tab.addCell(cel); } doc.add(tab); } else {//si no se desea clasificar por capítulos. if (acts.size() == 0) {//si no esxisten actividades... 33 Código fuente. Generador de Historiales Académicos (Kardexs) doc.close();//se cierra el documento continue;//se continúa con el siguiente alumno. } doc.add(new Paragraph(" ")); col[0] = 5f; col[1] = 1f; tab = new PdfPTable(col); tex = new Paragraph(); tex.setFont(f.getF(1)); tex.add("Actividad"); cel = new PdfPCell(tex); cel.setHorizontalAlignment(center); tab.addCell(cel); tex = new Paragraph(); tex.setFont(f.getF(1)); tex.add("Calificación"); cel = new PdfPCell(tex); cel.setHorizontalAlignment(center); tab.addCell(cel); Iterator it = activis.iterator(); try { it.next(); it.next(); } catch (Exception e) { System.out.println("No clasifica actividades. Primera actividad"); doc.close(); 34 Código fuente. Generador de Historiales Académicos (Kardexs) continue; } while (it.hasNext()) { //se captura la actividad Actividad act2 = (Actividad) it.next(); act = act2.getNombre();//nombre de actividad actCal = act2.getResult();//resultado de actividad if (this.eliminaCeros) { if (actCal == 0.0) { continue; } } //celda para el nombre de actividad tex = new Paragraph(); tex.setFont(f.getF(1)); tex.add(act); tab.addCell(tex); //celda para el resultado de la actividad tex = new Paragraph(); tex.setFont(f.getF(1)); tex.add(actCal.toString()); cel = new PdfPCell(tex); cel.setHorizontalAlignment(center); tab.addCell(cel); } 35 Código fuente. Generador de Historiales Académicos (Kardexs) doc.add(tab); doc.add(new Paragraph(" ")); } // SECCIÓN DE LAS FIRMAS ****AL PIÉ DEL DOCUMENTO**** doc.add(new Paragraph("\n \n \n")); tab = new PdfPTable(2); tab.setWidthPercentage(100); //// RECTOR tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_CENTER); tex.setSpacingAfter(1); tex.add("Dr. Pablo Martín Buitrón Morales \n" + "Rector \n" + "Universidad Politécnica del Estado de Morelos \n"); cel = new PdfPCell(); cel.setBorder(Rectangle.NO_BORDER); cel.addElement(tex); tab.addCell(cel); //// SILVIA tex = new Paragraph(); tex.setFont(f.getF(1)); tex.setAlignment(Element.ALIGN_CENTER); tex.setSpacingAfter(1); tex.add("cDra. en C. Silvia Melbi Gaona Jiménez \n" \n" + "Profesora de Tiempo Completo 36 Código fuente. Generador de Historiales Académicos (Kardexs) + "Universidad Politécnica del Estado de Morelos \n" + "Responsable Técnico del Proyecto \n" + "CONACYT MOR-2009-C01-116163"); cel = new PdfPCell(); cel.addElement(tex); cel.setBorder(Rectangle.NO_BORDER); tab.addCell(cel); doc.add(tab); // cerrar el documento. doc.close(); this.generados = i + 1; } } private String determinaNomDoc(String curso, short periodo, Double promedio, String subsist, String[] nombre) { String nomDoc = ""; //RUTA //nomDoc = this.destino + "\\"; nomDoc = this.destinoCarpeta + "\\"; //CURSO if (curso.equals("FÍSICA")) { nomDoc = nomDoc + "FS"; } else if (curso.equals("QUÍMICA")) { nomDoc = nomDoc + "QM"; } else if (curso.equals("BIOLOGÍA")) { 37 Código fuente. Generador de Historiales Académicos (Kardexs) nomDoc = nomDoc + "BI"; } else if (curso.equals("ECOLOGÍA")) { nomDoc = nomDoc + "EC"; } else if (curso.equals("MATEMÁTICAS")) { nomDoc = nomDoc + "MA"; } else { nomDoc = nomDoc + "CC"; } //PERIODO if (periodo == 1) { nomDoc = nomDoc + "-MJ"; } else if (periodo == 2) { nomDoc = nomDoc + "-SO"; } else { nomDoc = nomDoc + "-PP"; } //PROMEDIO promedio = Double.valueOf(this.califOk(promedio, 0.0)); String[] prom = promedio.toString().split("\\u002E"); if (prom[0].length() < 2) { nomDoc = nomDoc + "-" + "0" + prom[0] + "."; } else { nomDoc = nomDoc + "-" + prom[0] + "."; } if (prom[1].length() < 2) { 38 Código fuente. Generador de Historiales Académicos (Kardexs) nomDoc = nomDoc + prom[1] + "0"; //nomDoc = nomDoc + "-" + prom[0] + "_" + prom[1] + "0"; } else { nomDoc = nomDoc + prom[1]; //nomDoc = nomDoc + "-" + prom[0] + "_" + prom[1]; } //SUBSISTEMA nomDoc = nomDoc + "-" + subsist; //NOMBRE nomDoc = nomDoc + "-" + nombre[0].replace('\u0020', '\u005F') + "_" + nombre[1].replace('\u0020', '\u005F'); //EXTENSIÓN nomDoc = nomDoc + ".pdf"; return nomDoc; } private void generaSubsistemasCompletos() { ESTUDIOS CIENTÍFICOS Y TECNOLÓGICOS"); this.subsistemas.put("CECY", "COLEGIO DE this.subsistemas.put("CONA", "COLEGIO NACIONAL DE EDUCACIÓN PROFESIONAL TÉCNICA"); this.subsistemas.put("COBA", "COLEGIO DE BACHILLERES DEL ESTADO DE MORELOS"); this.subsistemas.put("CBTA", "CENTRO DE BACHILLERATO TECNOLÓGICO AGROPECUARIO"); this.subsistemas.put("CBTI", "CENTRO DE BACHILLERATO TECNOLÓGICO INDUSTRIAL Y DE SERVICIOS"); this.subsistemas.put("PREF", "PREPARATORIA FEDERAL POR COOPERACIÓN"); this.subsistemas.put("UNAM", "PREPARATORIA DE LA UNIVERSIDAD NACIONAL AUTÓNOMA DE MÉXICO"); this.subsistemas.put("UAEM", "PREPARATORIA DE LA UNIVERSIDAD AUTÓNOMA DEL ESTADO DE 39 Código fuente. Generador de Historiales Académicos (Kardexs) MORELOS"); this.subsistemas.put("PART", "PREPARATORIA PRIVADA"); this.subsistemas.put("OOOO", "INDETERMINADO");////////////////////////////////////////// this.subsistemas.put("PRCO", "PREPARATORIA FEDERAL POR COOPERACIÓN"); this.subsistemas.put("PRIV", "PREPARATORIA PRIVADA"); this.subsistemas.put("UPEM", "UNIVERSIDAD POLITÉCNICA DEL ESTADO DE MORELOS"); this.subsistemas.put("INEA", "INSTITUTO NACIONAL PARA LA EDUCACIÓN DE LOS ADULTOS"); this.subsistemas.put("OTRO", "INDETERMINADO");////////////////////////////////////////// this.subsistemas.put("IBEM", "INSTITUTO DE EDUCACIÓN BÁSICA DEL ESTADO DE MORELOS"); this.subsistemas.put("IEBE", "INSTITUTO DE EDUCACIÓN BÁSICA DEL ESTADO DE MORELOS"); this.subsistemas.put("CEBA", "DIRECCIÓN GENERAL DEL BACHILLERATO"); this.subsistemas.put("PAEM", "PREPARATORIA ABIERTA DEL ESTADO DE MORELOS"); this.subsistemas.put("CEAM", "CENTRO DE ACTUALIZACIÓN DEL MAGISTERIO MORELOS"); this.subsistemas.put("UVAC", "UNIVERSIDAD DEL VALLE DE CUERNAVACA"); this.subsistemas.put("CESP", "COORDINACIÓN ESTATAL DEL SUBSISTEMA DE PREPARATORIA ABIERTA"); } private void crearCarpeta() { //determinamos el nombre del curso o área String cur = ""; String[] tokRuta = this.origen.split("\\u005C"); String[] tokNomb = tokRuta[tokRuta.length - 1].split("_"); cur = tokNomb[0]; if (cur.equals("CB01") || cur.equals("CB02")) { cur = "BIOLOGÍA"; } else if (cur.equals("CF01") || cur.equals("CF02")) { 40 Código fuente. Generador de Historiales Académicos (Kardexs) cur = "FÍSICA"; } else if (cur.equals("CE01") || cur.equals("CE02")) { cur = "ECOLOGÍA"; } else if (cur.equals("CQ01") || cur.equals("CQ02")) { cur = "QUÍMICA"; } else if (cur.equals("CM01") || cur.equals("CM02")) { cur = "MATEMÁTICAS"; } else { cur = "NO ESPECIFICADO"; } //creamos la carpeta del curso o área dentro de la carpeta destino. File dir = new File(this.destino + "\\" + cur); dir.mkdir(); this.destinoCarpeta = dir.getAbsolutePath(); } private String califOk(Double calFinal, Double calDiag) { calFinal *= 100; calDiag *= 100; Integer cal = calFinal.intValue() - calDiag.intValue(); Double calok = cal.doubleValue() / 100; return calok.toString(); } private String textoEnMayusMinus(String string) { String nomRet = string; String[] tokens = nomRet.split(" "); 41 Código fuente. Generador de Historiales Académicos (Kardexs) nomRet = ""; int c = 0; char[] arr; for (int i = 0; i < tokens.length; i++) { tokens[i] = tokens[i].toLowerCase(); if (this.esPreposicion(tokens[i])) { nomRet = nomRet.concat(tokens[i]).concat(" "); continue; } arr = tokens[i].toCharArray(); if (arr.length < 1) { continue; } c = (int) arr[0]; if (c > 96 && c < 123) { c -= 32; arr[0] = (char) c; } else if (this.isCaracterValido((char) c)) { arr[0] = ((String.valueOf(arr[0])).toUpperCase()).charAt(0); } tokens[i] = String.valueOf(arr); nomRet = nomRet.concat(tokens[i]).concat(" "); } return nomRet; } private boolean isCaracterValido(char c) { 42 Código fuente. Generador de Historiales Académicos (Kardexs) boolean band; switch (c) { case 'á': band = true; break; case 'é': band = true; break; case 'í': band = true; break; case 'ó': band = true; break; case 'ú': band = true; break; case 'Á': band = true; break; case 'É': band = true; break; case 'Í': band = true; 43 Código fuente. Generador de Historiales Académicos (Kardexs) break; case 'Ó': band = true; break; case 'Ú': band = true; break; case 'ü': band = true; break; case 'Ü': band = true; break; case 'ñ': band = true; break; case 'Ñ': band = true; break; case ' ': band = true; break; default: band = false; break; } 44 Código fuente. Generador de Historiales Académicos (Kardexs) return band; } @Override public void onOpenDocument(PdfWriter writer, Document document) { total = writer.getDirectContent().createTemplate(100, 100); total.setBoundingBox(new Rectangle(-20, -20, 100, 100)); try { helv = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); } catch (Exception e) { System.out.println("Excepción. onOpenDocument()"); throw new ExceptionConverter(e); } } @Override public void onStartPage(PdfWriter writer, Document document) { try { //IMAGEN DE FONDO document.add(this.fondo); } catch (DocumentException ex) { System.out.println("Excepción. onStartPage(). agregar fondo."); Logger.getLogger(Historial.class.getName()).log(Level.SEVERE, null, ex); } } @Override 45 Código fuente. Generador de Historiales Académicos (Kardexs) public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); String text = "Página " + writer.getPageNumber() + " de "; float textBase = document.bottom() - 20; float textSize = helv.getWidthPoint(text, 8); cb.beginText(); cb.setFontAndSize(helv, 8); if ((writer.getPageNumber() % 2) == 1) { cb.setTextMatrix(document.right() - textSize, textBase); cb.showText(text); cb.endText(); cb.addTemplate(total, document.right(), textBase); //+ textSize } else { float adjust = helv.getWidthPoint("0", 8); cb.setTextMatrix(document.right() - adjust - textSize, textBase); //- textSize - adjust cb.showText(text); cb.endText(); cb.addTemplate(total, document.right() - adjust, textBase); // - adjust } cb.restoreState(); } @Override public void onCloseDocument(PdfWriter writer, Document document) { total.beginText(); 46 Código fuente. Generador de Historiales Académicos (Kardexs) total.setFontAndSize(helv, 8); total.setTextMatrix(0, 0); total.showText(String.valueOf(writer.getPageNumber() - 1)); total.endText(); } private boolean esPreposicion(String string) { int tam = this.preposiciones.length; for (int i = 0; i < tam; i++) { if (string.equals(this.preposiciones[i])) { return true; } } return false; } private void generarPreposiciones() { this.preposiciones = new String[8]; this.preposiciones[0] = "de"; this.preposiciones[1] = "del"; this.preposiciones[2] = "la"; this.preposiciones[3] = "el"; this.preposiciones[4] = "por"; this.preposiciones[5] = "para"; this.preposiciones[6] = "y"; this.preposiciones[7] = "los"; } private String horasCurrciulares(String curso) { 47 Código fuente. Generador de Historiales Académicos (Kardexs) String horas = "120"; if (curso.equals("BIOLOGÍA")) { horas = "240"; } else if (curso.equals("ECOLOGÍA")) { horas = "240"; } return horas; } /** * @return the origen */ public String getOrigen() { return origen; } /** * @param origen the origen to set */ public void setOrigen(String origen) { this.origen = origen; } /** * @return the destino */ public String getDestino() { return destino; 48 Código fuente. Generador de Historiales Académicos (Kardexs) } /** * @param destino the destino to set */ public void setDestino(String destino) { this.destino = destino; } /** * @return the telefonos */ public String getTelefonos() { return telefonos; } /** * @param telefonos the telefonos to set */ public void setTelefonos(String telefonos) { this.telefonos = telefonos; } /** * @return the destinoCarpeta */ public String getDestinoCarpeta() { return destinoCarpeta; } /** 49 Código fuente. Generador de Historiales Académicos (Kardexs) * @param destinoCarpeta the destinoCarpeta to set */ public void setDestinoCarpeta(String destinoCarpeta) { this.destinoCarpeta = destinoCarpeta; } /** * @return the eliminaCeros */ public boolean isEliminaCeros() { return eliminaCeros; } /** * @param eliminaCeros the eliminaCeros to set */ public void setEliminaCeros(boolean eliminaCeros) { this.eliminaCeros = eliminaCeros; } /** * @return the clasificaActividades */ public boolean isClasificaActividades() { return clasificaActividades; } /** * @param clasificaActividades the clasificaActividades to set 50 Código fuente. Generador de Historiales Académicos (Kardexs) */ public void setClasificaActividades(boolean clasificaActividades) { this.clasificaActividades = clasificaActividades; } /** * @return the generados */ public int getGenerados() { return generados; } /** * @return the datos */ public LinkedList<Alumno> getDatos() { return datos; } /** * @param datos the datos to set */ public void setDatos(LinkedList<Alumno> datos) { this.datos = datos; } } //Archivo Archivo.java package historiales; 51 Código fuente. Generador de Historiales Académicos (Kardexs) import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * * @author Alberto */ public class Archivo { private String ruta, rutaTels; private HSSFWorkbook xls; //archivo de tipo XLS private HSSFSheet shXLS; //hoja de cálculo de Excel 2003 private Iterator<Row> rXLS; //iterador de filas de Excel 2003 private LinkedList<Alumno> datos; private LinkedHashMap telefonos; boolean elimCeros; /** * Constructor nulo */ public Archivo() { 52 Código fuente. Generador de Historiales Académicos (Kardexs) this.ruta = ""; this.rutaTels = ""; this.datos = new LinkedList<Alumno>(); this.telefonos = new LinkedHashMap(); } /** * Constructor que recibe la ruta del archivo y procede a abrir el archivo * en excel, genera su stream de lectura y obtiene la referencia hacia la * primera hoja del documento. */ public Archivo(String r, String t, boolean elimCeros) { this.ruta = r; this.rutaTels = t; this.elimCeros = elimCeros; this.datos = new LinkedList<Alumno>(); this.telefonos = new LinkedHashMap(); //teléfonos this.getDataTelefonosCorreos(); //calificaciones this.abrirArchivoXLS(); this.getDataCalificaciones(); } private void getDataTelefonosCorreos() { //se abre el archivo para leer los teléfonos. POIFSFileSystem fs; 53 Código fuente. Generador de Historiales Académicos (Kardexs) FileInputStream fis; try { fis = new FileInputStream(this.getRutaTels()); fs = new POIFSFileSystem(fis); } catch (FileNotFoundException ex) { throw new Error("El archivo seleccionado no se puede encontrar, verifique el nombre y la ruta del archivo."); } catch (IOException e) { throw new Error("No se puede generar el Stream del archivo de Excel 2003. " + this.getRutaTels()); } try { // creamos un objeto que contiene los datos del archivo XLS. this.xls = new HSSFWorkbook(fs); // obtenemos la primer hoja de cálculo del archivo. this.shXLS = this.xls.getSheetAt(0); //creamos el objeto que permite recorrer todas las filas de la hoja. this.rXLS = this.shXLS.rowIterator(); } catch (IOException e) { throw new Error("No se puede abrir el archivo de Excel 2003. " + this.getRutaTels()); } //se leen los teléfonos y se almacenan en un hashMap String key = new String(""); String[] telsMails = new String[4]; String[] nomb = new String[3]; Row fila; 54 Código fuente. Generador de Historiales Académicos (Kardexs) fila = this.rXLS.next(); while (this.rXLS.hasNext()) { //se leen el "Ap.Paterno Ap.Materno Nombre" fila = this.rXLS.next(); try { nomb[0] = fila.getCell(1).getStringCellValue(); nomb[0] = this.sinEspaciosFinales(nomb[0]); nomb[0] = this.sinEspaciosIniciales(nomb[0]); } catch (Exception e) { nomb[0] = ""; } try { nomb[1] = fila.getCell(2).getStringCellValue(); nomb[1] = this.sinEspaciosFinales(nomb[1]); nomb[1] = this.sinEspaciosIniciales(nomb[1]); } catch (Exception e) { nomb[1] = ""; } try { nomb[2] = fila.getCell(0).getStringCellValue(); nomb[2] = this.sinEspaciosFinales(nomb[2]); nomb[2] = this.sinEspaciosIniciales(nomb[2]); } catch (Exception e) { nomb[2] = ""; } 55 Código fuente. Generador de Historiales Académicos (Kardexs) // se concatenan los campos para formar el nombre y la key key = new String(""); boolean band = true; if (nomb[0].length() > 0) { key = key + nomb[0]; band = true; } else { band = false; } if (band) { key = key + " "; } if (nomb[1].length() > 0) { key = key + nomb[1]; band = true; } else { band = false; } if (band) { key = key + " "; } if (nomb[2].length() > 0) { key = key + nomb[2]; } key = this.validaNombre(key); 56 Código fuente. Generador de Historiales Académicos (Kardexs) key = key.toUpperCase(); // se leen los teléfonos del registro leído. try {//local telsMails[0] = fila.getCell(3).getStringCellValue(); } catch (Exception e) { try { telsMails[0] = fila.getCell(3).toString(); } catch (Exception ex) { telsMails[0] = ""; } } try {//celular telsMails[1] = fila.getCell(4).getStringCellValue(); } catch (Exception e) { try { telsMails[1] = fila.getCell(4).toString(); } catch (Exception ex) { telsMails[1] = ""; } } //se obtienen los correos try {//correo 1 telsMails[2] = fila.getCell(5).getStringCellValue(); } catch (Exception e) { try { telsMails[2] = fila.getCell(5).toString(); 57 Código fuente. Generador de Historiales Académicos (Kardexs) } catch (Exception ex) { telsMails[2] = ""; } } try {//correo 2 telsMails[3] = fila.getCell(6).getStringCellValue(); } catch (Exception e) { try { telsMails[3] = fila.getCell(6).toString(); } catch (Exception ex) { telsMails[3] = ""; } } //se guardan los datos en su respectivo arreglo. String[] TT = new String[4]; TT[0] = new String(telsMails[0]); TT[1] = new String(telsMails[1]); TT[2] = new String(telsMails[2]); TT[3] = new String(telsMails[3]); this.telefonos.put(key, TT); } } /** * Abre un archivo de formato MS Office Excel 2003 o anterior. Solo lo abre si ya se ha validado su formato. 58 Código fuente. Generador de Historiales Académicos (Kardexs) * @throws FileNotFoundException * @throws IOException */ private void abrirArchivoXLS() throws Error { //crear un objeto POIFSFileSystem para leer los datos POIFSFileSystem fs; FileInputStream fis; try { fis = new FileInputStream(this.getRuta()); fs = new POIFSFileSystem(fis); } catch (FileNotFoundException ex) { throw new Error("El archivo seleccionado no se puede encontrar, verifique el nombre y la ruta del archivo."); } catch (IOException e) { throw new Error("No se puede generar el Stream del archivo de Excel 2003. " + this.getRuta()); } try { // creamos un objeto que contiene los datos del archivo XLS. this.xls = new HSSFWorkbook(fs); // obtenemos la primer hoja de cálculo del archivo. this.shXLS = this.xls.getSheetAt(0); //creamos el objeto que permite recorrer todas las filas de la hoja. this.rXLS = this.shXLS.rowIterator(); } catch (IOException e) { throw new Error("No se puede abrir el archivo de Excel 2003. " + this.getRuta()); 59 Código fuente. Generador de Historiales Académicos (Kardexs) } } /** * Extrae los datos del archivo de calificaciones y los guarda en un arreglo * el cual tiene la estructura de Alumno. (LinkedList) */ private void getDataCalificaciones() { Row fila = null; //se obtiene el último índice de la columna final (promedio) fila = this.rXLS.next(); int indiceFinal = (int) fila.getLastCellNum(); //variables para acceder a los datos de la hoja String nombre = "", curso = "", subsist = ""; String[] nombreSep = new String[2]; Integer[] estado = {0, 0, 0};////{ED,EF,Actividades} String estadoAlum = "Terminado"; Double calDiag = new Double(0), calFinal = new Double(0), promedio = new Double(0); short periodo = 0; //se obtiene el nombre del curso curso = this.determinaCurso(); //se recorre sobre las filas, o sea, para cada alumno del curso this.datos = new LinkedList<Alumno>(); while (this.rXLS.hasNext()) { fila = this.rXLS.next(); // se obtiene el nombre del alumno 60 Código fuente. Generador de Historiales Académicos (Kardexs) nombre = fila.getCell(1).getStringCellValue() + " " + fila.getCell(0).getStringCellValue(); nombre = this.validaNombre(nombre); nombre = nombre.toUpperCase(); nombre = this.sinEspaciosIniciales(nombre); nombreSep = new String[2]; nombreSep[0] = fila.getCell(1).getStringCellValue(); nombreSep[0] = this.validaNombre(nombreSep[0]); nombreSep[1] = fila.getCell(0).getStringCellValue(); nombreSep[1] = this.validaNombre(nombreSep[1]); nombreSep[0] = nombreSep[0].toUpperCase(); //mayúsculas nombreSep[0] = this.sinEspaciosIniciales(nombreSep[0]); nombreSep[1] = nombreSep[1].toUpperCase(); //mayúsculas nombreSep[1] = this.sinEspaciosIniciales(nombreSep[1]); // estado o situación del alumno estadoAlum = "Terminado"; estado[0] = 0; estado[1] = 0; estado[2] = 0; //se obtiene el periodo del alumno periodo = this.determinaPeriodo(); try {// se obtiene el subsistema subsist = fila.getCell(3).getStringCellValue(); } catch (Exception e) { subsist = ""; 61 Código fuente. Generador de Historiales Académicos (Kardexs) } try {//se obtiene el promedio del curso para el alumno promedio = fila.getCell(indiceFinal - 1).getNumericCellValue(); // Valor directo de Moodle. } catch (Exception e) { promedio = 0.0; } //variables para las actividades String actNombre = new String(""); Double actResult = new Double(0); LinkedList<Actividad> acts = new LinkedList<Actividad>(); short capitulo = 0; //se obtienen todas las actividades y sus resultados. for (int i = 6; i < indiceFinal - 1; i++) { // se obtiene el nombre de la actividad actNombre = this.shXLS.getRow(0).getCell(i).getStringCellValue(); calificación obtenida en la actividad try {// se obtiene la actResult = fila.getCell(i).getNumericCellValue(); } catch (Exception e) { actResult = 0.0; estado[2] += 1; } capitulo = this.getCapitiulo(actNombre); actNombre = this.purgaNombre(actNombre); //actNombre = actNombre.toUpperCase(); ////////////////////////////////////// 62 Código fuente. Generador de Historiales Académicos (Kardexs) // AQUÍ PONEMOS LA CONDICIÓN DE LAS ACTIVIDADES OCULTAS EN MATEMÁTICAS if (curso.equals("MATEMÁTICAS")) { if (this.esActEspMate(actNombre)) { actResult = 90.0; } } ////////////////////////////////////// acts.add(new Actividad(actNombre, actResult, capitulo)); } //se obtiene la calificación diagnóstica y final Actividad tmp; tmp = this.obtenCalExamen("0.ED.", acts); calDiag = tmp.getResult(); tmp = this.obtenCalExamen("0.EF.", acts); calFinal = tmp.getResult(); if (calFinal < 70) { estado[1] += 1; } if (estado[2] > 0) { if (curso.equals("MATEMÁTICAS")) { if (estado[2] > 4) { estadoAlum = "En proceso"; } } else { // se recalcula el promedio. 63 Código fuente. Generador de Historiales Académicos (Kardexs) promedio = this.reCalculaPromedio(acts, calDiag, calFinal);// Valor calculado con base en las actividades totales /*if (promedio < 70) { estadoAlum = "En proceso"; }*/ } } if (calFinal < 1.0) { estadoAlum = "En proceso"; } promedio = this.reCalculaPromedio(acts, calDiag, calFinal);// Valor calculado con base en las actividades totales //se obtienen los teléfonos String telsMails[] = this.getTelsMails(nombre); // agregamos el alumno. this.datos.add(new Alumno(nombre, nombreSep, periodo, curso, subsist, calDiag, calFinal, promedio, acts, telsMails[0], telsMails[1], telsMails[2], telsMails[3], estadoAlum)); } } private String[] getTelsMails(String nom) { String[] telsMails = {"", "", "", ""}; //obtenemos teléfonos y correos. if (this.telefonos.containsKey(nom)) { telsMails = (String[]) this.telefonos.get(nom); } 64 Código fuente. Generador de Historiales Académicos (Kardexs) //se refinan los teléfonos String[] tels = new String[2]; tels[0] = telsMails[0]; tels[1] = telsMails[1]; tels = this.refinarTels(tels); //aquí se mandan a refinar los teléfonos telsMails[0] = tels[0]; telsMails[1] = tels[1]; //se regresan los tléfonos refinados y los correos. return telsMails; } private String[] refinarTels(String[] tels) { String[] tr = new String[2]; int r, i, j; char[] tel; //primero se eliminan los caracteres innecesarios (espacio,punto,gión,paréntesis,notación científica) for (i = 0; i < tels.length; i++) { tel = new char[tels[i].length()]; r = 0; for (j = 0; j < tel.length; j++) { if (tels[i].charAt(j) == '.') { r++; } else if (tels[i].charAt(j) == ' ') { r++; } else if (tels[i].charAt(j) == '(') { r++; 65 Código fuente. Generador de Historiales Académicos (Kardexs) } else if (tels[i].charAt(j) == ')') { r++; } else if (tels[i].charAt(j) == '-') { r++; } else if (tels[i].charAt(j) == 'E') { break; } else { tel[j - r] = tels[i].charAt(j); } } tr[i] = String.valueOf(tel, 0, j - r); } //después se agregan los ceros faltantes al principio del teléfono. /*for (i=0;i<tels.length;i++){ if (tels[i].length() > 8){ if (tels[i].charAt(0) == '1'){ } } }*/ return tr; } private String determinaCurso() { String cur = ""; String[] tokRuta = this.getRuta().split("\\u005C"); String[] tokNomb = tokRuta[tokRuta.length - 1].split("_"); 66 Código fuente. Generador de Historiales Académicos (Kardexs) cur = tokNomb[0]; if (cur.equals("CB01") || cur.equals("CB02")) { cur = "BIOLOGÍA"; } else if (cur.equals("CF01") || cur.equals("CF02")) { cur = "FÍSICA"; } else if (cur.equals("CE01") || cur.equals("CE02")) { cur = "ECOLOGÍA"; } else if (cur.equals("CQ01") || cur.equals("CQ02")) { cur = "QUÍMICA"; } else if (cur.equals("CM01") || cur.equals("CM02")) { cur = "MATEMÁTICAS"; } return cur; } /** * @return the datos */ private String validaNombre(String nombre) { int nomLong = nombre.length(), r = 0; char[] nom = new char[nomLong]; char letra = ' '; int letraN = 0; for (int i = 0; i < nombre.length(); i++) { letra = nombre.charAt(i); letraN = nombre.codePointAt(i); if (letraN > 64 && letraN < 91) { 67 Código fuente. Generador de Historiales Académicos (Kardexs) nom[i + r] = nombre.charAt(i); } else if (letraN > 96 && letraN < 123) { nom[i + r] = nombre.charAt(i); } else if (this.isCaracterValido(letra)) { nom[i + r] = nombre.charAt(i); } else { r -= 1; } } if (r < 0) { char[] nom2 = new char[nomLong + r]; for (int i = 0; i < nom2.length; i++) { nom2[i] = nom[i]; } return String.valueOf(nom2); } else { return String.valueOf(nom); } } private String sinEspaciosFinales(String n) { int lon = n.length(), r = 0, i = 0; char[] ns = new char[lon]; //determina los espacios al final. for (i = 0; i < lon; i++) { ns[i] = n.charAt(i); 68 Código fuente. Generador de Historiales Académicos (Kardexs) } i = 0; while (ns[lon - i - 1] == ' ') { r++; i++; } return String.valueOf(ns, 0, lon - r); } private String sinEspaciosIniciales(String n) { int lon = n.length(), r = 0, i = 0; char[] ns = new char[lon]; //determina los espacios al principio. for (i = 0; i < lon; i++) { ns[i] = n.charAt(i); } i = 0; while (ns[i] == ' ') { r++; i++; } return String.valueOf(ns, r, lon - r); } private boolean isCaracterValido(char c) { boolean band; switch (c) { 69 Código fuente. Generador de Historiales Académicos (Kardexs) case 'á': band = true; break; case 'é': band = true; break; case 'í': band = true; break; case 'ó': band = true; break; case 'ú': band = true; break; case 'Á': band = true; break; case 'É': band = true; break; case 'Í': band = true; break; case 'Ó': band = true; 70 Código fuente. Generador de Historiales Académicos (Kardexs) break; case 'Ú': band = true; break; case 'ü': band = true; break; case 'Ü': band = true; break; case 'ñ': band = true; break; case 'Ñ': band = true; break; case ' ': band = true; break; default: band = false; break; } return band; } 71 Código fuente. Generador de Historiales Académicos (Kardexs) private short determinaPeriodo() { short perVal = 0; String cur = ""; String[] tokRuta = this.getRuta().split("\\u005C"); String[] tokNomb = tokRuta[tokRuta.length - 1].split("_"); cur = tokNomb[0]; char[] perNum = new char[2]; perNum[0] = cur.charAt(2); perNum[1] = cur.charAt(3); String per = String.valueOf(perNum); if (per.equals("01")) { perVal = 1; } else if (per.equals("02")) { perVal = 2; } return perVal; } private short getCapitiulo(String actNombre) { short cap = 0; String[] tokens = actNombre.split(" "); cap = (short) tokens[1].charAt(0); cap -= 48; return cap; } private String purgaNombre(String actNombre) { 72 Código fuente. Generador de Historiales Académicos (Kardexs) String nomRet = ""; String[] tokens = actNombre.split(" "); for (int i = 1; i < tokens.length; i++) { nomRet += tokens[i]; if (i + 1 < tokens.length) { nomRet += " "; } } tokens = nomRet.split(" "); String nomRetBak = nomRet; nomRet = ""; int c = 0; char[] arr; for (int i = 1; i < tokens.length; i++) { tokens[i] = tokens[i].toLowerCase(); //arr = new char[tokens[i].length()]; arr = tokens[i].toCharArray(); if (arr.length <= 0) { continue; } //return nomRetBak; c = (int) arr[0]; c -= 32; arr[0] = (char) c; tokens[i] = String.valueOf(arr); nomRet = nomRet.concat(tokens[i]).concat(" "); 73 Código fuente. Generador de Historiales Académicos (Kardexs) } nomRet = tokens[0].concat(" ").concat(nomRet); return nomRet; } private Actividad obtenCalExamen(String e, LinkedList<Actividad> a) { Actividad act; String actNom = ""; act = a.getFirst(); for (int i = 0; i < a.size(); i++) { actNom = a.get(i).getNombre(); String[] tok = actNom.split(" "); if (e.equals(tok[0])) { act = a.get(i); break; } } return act; } private boolean esActEspMate(String actNombre) { String[] tok = actNombre.split(" "); if (tok[0].equals("4.1.")) { return true; } else if (tok[0].equals("4.2.")) { return true; } else if (tok[0].equals("6.1.")) { 74 Código fuente. Generador de Historiales Académicos (Kardexs) return true; } else if (tok[0].equals("7.1.")) { return true; } else { return false; } } private Double reCalculaPromedio(LinkedList<Actividad> acts, Double cd, Double cf) { Double suma = 0.0, prom = 0.0; int totact = 0; Actividad act; Iterator it = acts.iterator(); //it.next(); //it.next(); for (; it.hasNext();) { act = (Actividad) it.next(); if (esActividad(act.getNombre())) { if (this.elimCeros) { if (act.getResult() > 0.0) { suma += act.getResult(); totact += 1; } } else { suma += act.getResult(); totact += 1; } 75 Código fuente. Generador de Historiales Académicos (Kardexs) } } //suma = suma - cd - cf; prom = suma / totact; if (prom > 100.0) { prom = 100.0; } return prom; } /** * @return the ruta */ public String getRuta() { return ruta; } /** * @param ruta the ruta to set */ public void setRuta(String ruta) { this.ruta = ruta; } /** * @return the rutaTels */ public String getRutaTels() { 76 Código fuente. Generador de Historiales Académicos (Kardexs) return rutaTels; } /** * @param rutaTels the rutaTels to set */ public void setRutaTels(String rutaTels) { this.rutaTels = rutaTels; } public LinkedList<Alumno> getDatos() { if (this.telefonos.isEmpty()) { this.getDataTelefonosCorreos(); } this.abrirArchivoXLS(); this.getDataCalificaciones(); return datos; } /** * @return the telefonos */ public LinkedHashMap getTelefonos() { return telefonos; } /** * @param datos the datos to set */ 77 Código fuente. Generador de Historiales Académicos (Kardexs) public void setDatos(LinkedList<Alumno> datos) { this.datos = datos; } /** * @param telefonos the telefonos to set */ public void setTelefonos(LinkedHashMap telefonos) { this.telefonos = telefonos; } boolean esValido(int i) { boolean valido = false; String r = ""; if (i == 1) { r = this.ruta; } else if (i == 2) { r = this.rutaTels; } POIFSFileSystem fs; FileInputStream fis; try { fis = new FileInputStream(r); fs = new POIFSFileSystem(fis); valido = true; } catch (FileNotFoundException ex) { throw new Error("No existe archivo: " + r); } catch (IOException e) { 78 Código fuente. Generador de Historiales Académicos (Kardexs) throw new Error("Imposible abrir archivo (Excel 2003). " + r); } return valido; } private boolean esActividad(String nombre) { String[] tok = nombre.split(" "); if (tok[0].equals("0.ED.") || tok[0].equals("0.EF.")) return false; else return true; } } //Archivo Alumno.java package historiales; import java.util.LinkedList; /** * * @author Alberto */ public class Alumno { private String nombre; private String[] nombreSep; private String curso; private short periodo; private String subsist; 79 Código fuente. Generador de Historiales Académicos (Kardexs) private Double calDiag; private Double calFinal; private Double promedio; private LinkedList<Actividad> actividades; private String telLocal; private String telCelular; private String correo1; private String correo2; private String estado; public Alumno() { } public Alumno(String nombre, String[] nombreSep, short periodo, String curso, String subsist, Double calDiag, Double calFinal, Double promedio, LinkedList<Actividad> acts, String telLocal, String telCelular, String correo1, String correo2, String estado) { this.nombre = nombre; this.nombreSep = nombreSep; this.periodo = (short) periodo; this.curso = curso; this.subsist = subsist; this.calDiag = calDiag; this.calFinal = calFinal; this.promedio = promedio; this.actividades = acts; this.telLocal = telLocal; this.telCelular = telCelular; this.correo1 = correo1; 80 Código fuente. Generador de Historiales Académicos (Kardexs) this.correo2 = correo2; this.estado = estado; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return the nombreSep */ public String[] getNombreSep() { return nombreSep; } /** * @param nombreSep the nombreSep to set */ public void setNombreSep(String[] nombreSep) { 81 Código fuente. Generador de Historiales Académicos (Kardexs) this.nombreSep = nombreSep; } /** * @return the curso */ public String getCurso() { return curso; } /** * @param curso the curso to set */ public void setCurso(String curso) { this.curso = curso; } /** * @return the periodo */ public short getPeriodo() { return periodo; } /** * @param periodo the periodo to set */ public void setPeriodo(short periodo) { this.periodo = periodo; } 82 Código fuente. Generador de Historiales Académicos (Kardexs) /** * @return the subsist */ public String getSubsist() { return subsist; } /** * @param subsist the subsist to set */ public void setSubsist(String subsist) { this.subsist = subsist; } /** * @return the calDiag */ public Double getCalDiag() { return calDiag; } /** * @param calDiag the calDiag to set */ public void setCalDiag(Double calDiag) { this.calDiag = calDiag; } /** 83 Código fuente. Generador de Historiales Académicos (Kardexs) * @return the calFinal */ public Double getCalFinal() { return calFinal; } /** * @param calFinal the calFinal to set */ public void setCalFinal(Double calFinal) { this.calFinal = calFinal; } /** * @return the promedio */ public Double getPromedio() { return promedio; } /** * @param promedio the promedio to set */ public void setPromedio(Double promedio) { this.promedio = promedio; } /** * @return the actividades 84 Código fuente. Generador de Historiales Académicos (Kardexs) */ public LinkedList<Actividad> getActividades() { return actividades; } /** * @param actividades the actividades to set */ public void setActividades(LinkedList<Actividad> actividades) { this.actividades = actividades; } /** * @return the telLocal */ public String getTelLocal() { return telLocal; } /** * @param telLocal the telLocal to set */ public void setTelLocal(String telLocal) { this.telLocal = telLocal; } /** * @return the telCelular */ public String getTelCelular() { 85 Código fuente. Generador de Historiales Académicos (Kardexs) return telCelular; } /** * @param telCelular the telCelular to set */ public void setTelCelular(String telCelular) { this.telCelular = telCelular; } /** * @return the correo1 */ public String getCorreo1() { return correo1; } /** * @param correo1 the correo1 to set */ public void setCorreo1(String correo1) { this.correo1 = correo1; } /** * @return the correo2 */ public String getCorreo2() { return correo2; 86 Código fuente. Generador de Historiales Académicos (Kardexs) } /** * @param correo2 the correo2 to set */ public void setCorreo2(String correo2) { this.correo2 = correo2; } /** * @return the estado */ public String getEstado() { return estado; } /** * @param estado the estado to set */ public void setEstado(String estado) { this.estado = estado; } } //Archivo Actividad.java package historiales; /** * * @author Alberto */ 87 Código fuente. Generador de Historiales Académicos (Kardexs) public class Actividad implements Comparable{ private String nombre; private Double result; private short capitulo; Actividad(String actNombre, Double actResult, short capitulo) { this.nombre = actNombre; this.result = actResult; this.capitulo = capitulo; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return the result */ public Double getResult() { 88 Código fuente. Generador de Historiales Académicos (Kardexs) return result; } /** * @param result the result to set */ public void setResult(Double result) { this.result = result; } /** * @return the capitulo */ public short getCapitulo() { return capitulo; } /** * @param capitulo the capitulo to set */ public void setCapitulo(short capitulo) { this.capitulo = capitulo; } public boolean equals(Object objeto) { // Indica en base a que atributos se iguala el objeto if (objeto == null) { return false; } Actividad producto = (Actividad) objeto; 89 Código fuente. Generador de Historiales Académicos (Kardexs) if (this.getNombre().equals(producto.getNombre())) { return true; } return false; } public int hashCode() { // retorna un identificador unico del objeto. return this.getNombre().hashCode(); } public int compareTo(Object o) { // Indica en base a que atributos se compara el objeto // Devuelve +1 si this es > que objeto // Devuelve -1 si this es < que objeto // Devuelve 0 si son iguales Actividad producto = (Actividad) o; String nombreObjeto = producto.getNombre().toLowerCase(); String nombreThis = this.getNombre().toLowerCase(); return (nombreThis.compareTo(nombreObjeto)); } } //Archivo Fuente.java package historiales; //import pruebas.estilos.*; import com.itextpdf.text.Font; /** 90 Código fuente. Generador de Historiales Académicos (Kardexs) * * @author Alberto */ public class Fuente { private Font f; int estilo; public Fuente() { this.f = new Font(); this.estilo = 0; } private void hacerEstilo(int s) { switch (s) { case 1: this.f.setSize(8); this.f.setStyle(Font.NORMAL); break; case 2: this.f.setSize(10); this.f.setStyle(Font.NORMAL); break; case 3: this.f.setSize(10); this.f.setStyle(Font.BOLD); break; case 4: this.f.setSize(16); 91 Código fuente. Generador de Historiales Académicos (Kardexs) this.f.setStyle(Font.NORMAL); break; case 5: this.f.setSize(12); this.f.setStyle(Font.BOLD); break; case 6: this.f.setSize(16); this.f.setStyle(Font.BOLDITALIC); break; default: this.f.setSize(8); this.f.setStyle(Font.NORMAL); break; } } /** * @return the f */ public Font getF(int s) { this.hacerEstilo(s); return f; } /** * @param f the f to set 92 Código fuente. Generador de Historiales Académicos (Kardexs) */ public void setF(Font f) { this.f = f; } } //Archivo BaseReportBuilder.java package historiales; /** * * @author Alberto */ import java.io.ByteArrayOutputStream; import java.io.InputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfPageEventHelper; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; public abstract class BaseReportBuilder extends PdfPageEventHelper { protected BaseFont baseFont; private PdfTemplate totalPages; private float footerTextSize = 8f; 93 Código fuente. Generador de Historiales Académicos (Kardexs) private int pageNumberAlignment = Element.ALIGN_CENTER; public BaseReportBuilder() { super(); baseFont = load("fonts", "tahoma.ttf"); } private BaseFont load(String location, String fontname) { try { InputStream is = getClass().getClassLoader().getResourceAsStream(location + System.getProperty("file.separator") + fontname); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; while (true) { int size = is.read(buf); if (size < 0) { break; } out.write(buf, 0, size); } is.close(); buf = out.toByteArray(); return BaseFont.createFont(fontname, BaseFont.CP1252, true, true, buf, null); } catch (Exception ex) { return null; } } @Override 94 Código fuente. Generador de Historiales Académicos (Kardexs) public void onOpenDocument(PdfWriter writer, Document document) { totalPages = writer.getDirectContent().createTemplate(100, 100); totalPages.setBoundingBox(new Rectangle(-20, -20, 100, 100)); } @Override public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); String text = String.format("Page %s of ", writer.getPageNumber()); float textBase = document.bottom() - 20; float textSize = baseFont.getWidthPoint(text, footerTextSize); cb.beginText(); cb.setFontAndSize(baseFont, footerTextSize); if (Element.ALIGN_CENTER == pageNumberAlignment) { cb.setTextMatrix((document.right() / 2), textBase); cb.showText(text); cb.endText(); cb.addTemplate(totalPages, (document.right() / 2) + textSize, textBase); } else if (Element.ALIGN_LEFT == pageNumberAlignment) { cb.setTextMatrix(document.left(), textBase); cb.showText(text); cb.endText(); cb.addTemplate(totalPages, document.left() + textSize, textBase); } else { float adjust = baseFont.getWidthPoint("0", footerTextSize); 95 Código fuente. Generador de Historiales Académicos (Kardexs) cb.setTextMatrix(document.right() - textSize - adjust, textBase); cb.showText(text); cb.endText(); cb.addTemplate(totalPages, document.right() - adjust, textBase); } cb.restoreState(); } @Override public void onCloseDocument(PdfWriter writer, Document document) { totalPages.beginText(); totalPages.setFontAndSize(baseFont, footerTextSize); totalPages.setTextMatrix(0, 0); totalPages.showText(String.valueOf(writer.getPageNumber() - 1)); totalPages.endText(); } public void setPageNumberAlignment(int pageNumberAlignment) { this.pageNumberAlignment = pageNumberAlignment; } } 96