List of usage examples for com.itextpdf.text FontFactory getFont
public static Font getFont(final String fontname, final float size, final int style, final BaseColor color)
Font
-object. From source file:com.systemevent.jsfclass.util.PdfEvento.java
public PdfPTable Tabla_compleja() { //creamos una tabla con 3 columnas PdfPTable mitablacompleja = new PdfPTable(3); //aadimos texto con formato a la primera celda PdfPCell celda = new PdfPCell(new Paragraph("Historial de Observaciones", FontFactory.getFont("arial", // fuente 22, // tamao Font.BOLD, // estilo BaseColor.RED))); // color //unimos esta celda con otras 2 celda.setColspan(3);/*from w w w.ja v a 2s. co m*/ //alineamos el contenido al centro celda.setHorizontalAlignment(Element.ALIGN_CENTER); // aadimos un espaciado celda.setPadding(12.0f); //colocamos un color de fondo celda.setBackgroundColor(BaseColor.GRAY); //se aade a la tabla mitablacompleja.addCell(celda); //fila 2 celda = new PdfPCell(new Paragraph("AUDITORIA DE SISTEMAS")); celda.setColspan(2); celda.setBackgroundColor(BaseColor.GREEN); mitablacompleja.addCell(celda); celda = new PdfPCell(new Paragraph("Aprobado")); celda.setBackgroundColor(BaseColor.LIGHT_GRAY); mitablacompleja.addCell(celda); //fila 3 celda = new PdfPCell(new Paragraph("COMPILADORES")); celda.setColspan(2); celda.setBackgroundColor(BaseColor.YELLOW); mitablacompleja.addCell(celda); celda = new PdfPCell(new Paragraph("Reprobado")); celda.setBackgroundColor(BaseColor.LIGHT_GRAY); mitablacompleja.addCell(celda); //fila 4 celda = new PdfPCell(new Paragraph("Prog. Bajo Nivel")); celda.setColspan(2); celda.setBackgroundColor(BaseColor.CYAN); mitablacompleja.addCell(celda); celda = new PdfPCell(new Paragraph("Eximido")); celda.setBackgroundColor(BaseColor.LIGHT_GRAY); mitablacompleja.addCell(celda); //fila 5 mitablacompleja.addCell("Conclusion"); celda = new PdfPCell(new Paragraph("GET A LIFE!!!")); celda.setHorizontalAlignment(Element.ALIGN_RIGHT); celda.setColspan(2); celda.setBackgroundColor(BaseColor.ORANGE); mitablacompleja.addCell(celda); // se retorna la tabla return mitablacompleja; }
From source file:com.udec.utilidades.PdfTable.java
public void createPdf(List<Nomina> nomi, Periodo pe) { //Abrimos el documento para edicin //Declaramos un texto como Paragraph //Le podemos dar formado como alineacin, tamao y color a la fuente. Paragraph parrafo = new Paragraph(); parrafo.setAlignment(Paragraph.ALIGN_CENTER); parrafo.setFont(FontFactory.getFont("Arial", 12, Font.BOLD, BaseColor.BLACK)); parrafo.add("CAJA DE PREVISION SOCIAL U. DE C.\n"); parrafo.add(pe.getNombre() + "\n"); parrafo.add(" "); try {/*from w w w. ja v a 2 s . c o m*/ //Agregamos el texto al documento documento.add(parrafo); //Agregamos un salto de linea documento.add(new Paragraph(" ")); //Agregamos la tabla al documento haciendo //la llamada al mtodo tabla() //documento.add(tabla()); documento.add(tabla2(nomi)); documento.add(new Paragraph(" ")); documento.add(tabla3(nomi)); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(firma()); } catch (DocumentException ex) { ex.getMessage(); } try { //File file = new File(archivo); //Desktop.getDesktop().open(file); } catch (Exception e) { //e.printStackTrace(); } }
From source file:com.vectorprint.report.itext.style.stylers.Font.java
License:Open Source License
public com.itextpdf.text.Font getFont() { com.itextpdf.text.Font f = FontFactory.getFont(getFamily(), getValue(FONTENCODING, ENCODING.class).getEncoding(), getSize(), getStyle().style); if (getColor() != null) { f.setColor(itextHelper.fromColor(getColor())); }/* w w w . j av a 2 s. co m*/ return f; }
From source file:Controlador.PDF.java
public String escribePDF(String nombre) { FileOutputStream ficheroPdf = null; Random r = new Random(); r.setSeed(System.currentTimeMillis()); String f_nombre = "cons" + nombre + r.nextInt(9000) + ".pdf"; try {/* ww w. j a v a2 s. co m*/ Document documento = new Document(); String basePath = new File("").getAbsolutePath(); String[] parts = basePath.split("/"); final String path = "/" + parts[1] + "/" + parts[2] + "/NetBeansProjects/pag_ingles/web/" + f_nombre; ficheroPdf = new FileOutputStream(path); PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20); documento.open(); Image foto = Image.getInstance( "/" + parts[1] + "/" + parts[2] + "/NetBeansProjects/pag_ingles/web/img/escuela.png"); foto.scaleToFit(200, 200); foto.setAlignment(Chunk.ALIGN_RIGHT); documento.add(foto); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph("Darktech Anglo Institute", FontFactory.getFont("Courier-Bold", 30, Font.UNDERLINE, BaseColor.BLUE))); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" OTORGA LA PRESENTEaaa", FontFactory.getFont("ARIAL", 30, Font.NORMAL, BaseColor.BLACK))); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" CONSTANCIA", FontFactory.getFont("ARIAL", 30, Font.NORMAL, BaseColor.BLACK))); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" A : " + nombre, FontFactory.getFont("ARIAL", 20, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph("POR HABER CONCLUIDO CON EXITO EL CURSO DE INGLES.", FontFactory.getFont("ARIAL", 14, Font.NORMAL, BaseColor.BLACK))); documento.close(); ficheroPdf.close(); Thread.sleep(3000); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException ex) { Logger.getLogger(PDF.class.getName()).log(Level.SEVERE, null, ex); } finally { try { ficheroPdf.close(); } catch (IOException e) { e.printStackTrace(); } } return f_nombre; }
From source file:controlador.PDFServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .j a v a 2s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, BadElementException, DocumentException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { this.cliente = new ClienteDAO(); ArrayList c = cliente.listarTodo(); FileOutputStream archivo = new FileOutputStream( "C:\\Users\\ayoro\\OneDrive\\Documents\\NetBeansProjects\\Proyecto2\\ExpoturismoDriver\\archivo.pdf"); Document documento = new Document(); PdfWriter.getInstance(documento, archivo); documento.open(); documento.add(new Paragraph("Clientes!")); documento.add(new Paragraph("Pruebita del primer pdf", FontFactory.getFont("arial", // fuente 22, // tamao Font.ITALIC, // estilo BaseColor.CYAN))); // color documento.add( new Paragraph("Nueva tablita", FontFactory.getFont("arial", 28, Font.BOLD, BaseColor.BLUE))); documento.add(Chunk.NEWLINE); PdfPTable tabla = new PdfPTable(4); Paragraph ced = new Paragraph("Cdula", FontFactory.getFont("arial", 12, Font.BOLD, BaseColor.BLACK)); Paragraph nom = new Paragraph("Nombre", FontFactory.getFont("arial", 12, Font.BOLD, BaseColor.BLACK)); Paragraph cor = new Paragraph("Correo", FontFactory.getFont("arial", 12, Font.BOLD, BaseColor.BLACK)); Paragraph tel = new Paragraph("Telfono", FontFactory.getFont("arial", 12, Font.BOLD, BaseColor.BLACK)); tabla.addCell(ced); tabla.addCell(nom); tabla.addCell(cor); tabla.addCell(tel); for (int i = 0; i < c.size(); i += 4) { tabla.addCell("" + c.get(i)); tabla.addCell((String) c.get(i + 1)); tabla.addCell((String) c.get(i + 2)); tabla.addCell("" + c.get(i + 3)); } documento.add(tabla); documento.add(new Paragraph("Finito")); documento.add(new Paragraph("Prueba 2")); documento.close(); response.sendRedirect("opciones.jsp"); } }
From source file:controller.CCInstance.java
License:Open Source License
public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings, final SignatureListener sl) throws CertificateException, IOException, DocumentException, KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { PrivateKey pk;// w ww .j a v a 2 s . c o m final PdfReader reader = new PdfReader(pdfPath); pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias()); if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) { String message = Bundle.getBundle().getString("fileDoesNotAllowChanges"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new SignatureFailedException(message); } if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) { settings.setPageNumber(reader.getNumberOfPages() - 1); } if (null == pk) { String message = Bundle.getBundle().getString("noSmartcardFound"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) { String message = Bundle.getBundle().getString("certificateNullChain"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain(); final Certificate owner = embeddedCertificateChain.get(0); final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1); if (null == owner) { String message = Bundle.getBundle().getString("certificateNameUnknown"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } final X509Certificate X509C = ((X509Certificate) lastCert); final Calendar now = Calendar.getInstance(); final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain( X509C); final Certificate[] fullCertificateChain; if (filledMissingCertsFromChainInTrustedKeystore.length < 2) { fullCertificateChain = new Certificate[embeddedCertificateChain.size()]; for (int i = 0; i < embeddedCertificateChain.size(); i++) { fullCertificateChain[i] = embeddedCertificateChain.get(i); } } else { fullCertificateChain = new Certificate[embeddedCertificateChain.size() + filledMissingCertsFromChainInTrustedKeystore.length - 1]; int i = 0; for (i = 0; i < embeddedCertificateChain.size(); i++) { fullCertificateChain[i] = embeddedCertificateChain.get(i); } for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) { fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f]; } } // Leitor e Stamper FileOutputStream os = null; try { os = new FileOutputStream(destination); } catch (FileNotFoundException e) { String message = Bundle.getBundle().getString("outputFileError"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new IOException(message); } // Aparncia da Assinatura final char pdfVersion; switch (Settings.getSettings().getPdfVersion()) { case "/1.2": pdfVersion = PdfWriter.VERSION_1_2; break; case "/1.3": pdfVersion = PdfWriter.VERSION_1_3; break; case "/1.4": pdfVersion = PdfWriter.VERSION_1_4; break; case "/1.5": pdfVersion = PdfWriter.VERSION_1_5; break; case "/1.6": pdfVersion = PdfWriter.VERSION_1_6; break; case "/1.7": pdfVersion = PdfWriter.VERSION_1_7; break; default: pdfVersion = PdfWriter.VERSION_1_7; } final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0 ? PdfStamper.createSignature(reader, os, pdfVersion) : PdfStamper.createSignature(reader, os, pdfVersion, null, true)); final PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setSignDate(now); appearance.setReason(settings.getReason()); appearance.setLocation(settings.getLocation()); appearance.setCertificationLevel(settings.getCertificationLevel()); appearance.setSignatureCreator(SIGNATURE_CREATOR); appearance.setCertificate(owner); final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath)); if (settings.isVisibleSignature()) { appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1, fieldName); appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION); if (null != settings.getAppearance().getImageLocation()) { appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation())); } com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0) .getBaseFont()); font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB())); if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) { font.setStyle(Font.BOLD + Font.ITALIC); } else if (settings.getAppearance().isBold()) { font.setStyle(Font.BOLD); } else if (settings.getAppearance().isItalic()) { font.setStyle(Font.ITALIC); } else { font.setStyle(Font.PLAIN); } appearance.setLayer2Font(font); String text = ""; if (settings.getAppearance().isShowName()) { if (!settings.getCcAlias().getName().isEmpty()) { text += settings.getCcAlias().getName() + "\n"; } } if (settings.getAppearance().isShowReason()) { if (!settings.getReason().isEmpty()) { text += settings.getReason() + "\n"; } } if (settings.getAppearance().isShowLocation()) { if (!settings.getLocation().isEmpty()) { text += settings.getLocation() + "\n"; } } if (settings.getAppearance().isShowDate()) { DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("Z"); text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n"; } if (!settings.getText().isEmpty()) { text += settings.getText(); } PdfTemplate layer2 = appearance.getLayer(2); Rectangle rect = settings.getPositionOnDocument(); Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight()); float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT); ColumnText ct = new ColumnText(layer2); ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT); ct.setAlignment(Element.ALIGN_MIDDLE); int align; switch (settings.getAppearance().getAlign()) { case 0: align = Element.ALIGN_LEFT; break; case 1: align = Element.ALIGN_CENTER; break; case 2: align = Element.ALIGN_RIGHT; break; default: align = Element.ALIGN_LEFT; } ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(), size, align); ct.go(); } else { appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName); } // CRL <- Pesado! final ArrayList<CrlClient> crlList = null; // OCSP OcspClient ocspClient = new OcspClientBouncyCastle(); // TimeStamp TSAClient tsaClient = null; if (settings.isTimestamp()) { tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null); } final String hashAlg = getHashAlgorithm(X509C.getSigAlgName()); final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName()); final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName()); try { MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient, 0, MakeSignature.CryptoStandard.CMS); if (sl != null) { sl.onSignatureComplete(pdfPath, true, ""); } return true; } catch (Exception e) { os.flush(); os.close(); new File(destination).delete(); if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) { throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled")); } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) { throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions")); } else if (e instanceof ExceptionConverter) { String message = Bundle.getBundle().getString("timestampFailed"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new SignatureFailedException(message); } else { if (sl != null) { sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog")); } controller.Logger.getLogger().addEntry(e); } return false; } }
From source file:Controller.Movimientos.generatePDF.java
public void generateAgendaEmpleados() { mm = new Model_Movimientos(); try {/*w w w. j a v a2 s . c om*/ Calendar calendar = Calendar.getInstance(); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int monthOfYear = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); int hour = calendar.get(Calendar.HOUR_OF_DAY); int min = calendar.get(Calendar.MINUTE); int sec = calendar.get(Calendar.SECOND); Document documento = new Document();//Creamos el documento FileOutputStream ficheroPdf = new FileOutputStream("agendaEmpleados" + dayOfMonth + "--" + monthOfYear + "--" + year + " " + hour + ";" + min + ";" + sec + ".pdf");//Abrimos el flujo y le asignamos nombre al pdf y su direccion PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);//Instanciamos el documento con el fichero documento.open();//Abrimos el documento documento.add(new Paragraph("Lista Empleados", FontFactory.getFont("Calibri", 30, Font.BOLD, BaseColor.BLACK)));//Le indicamos el tipo de letra, el tamanio, el estilo y el color de la letra documento.add(new Paragraph("___________________________"));//Realiza un salto de linea Iterator it; it = mm.getCrews().iterator(); while (it.hasNext()) { Crew c = (Crew) it.next(); System.out.println("" + c.getEmail().toString()); documento.add(new Paragraph("")); //Le decimos que nos imprima el Dni, Nombre y Apellidos del cliente, contenidos en el objeto Cliente y le indicamos el tipo de letra, tamanio, estilo y color de la letra documento.add(new Paragraph("Nombre: " + c.getName(), FontFactory.getFont("Calibri", 20, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph("Apellidos: " + c.getSurname(), FontFactory.getFont("Calibri", 20, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph("Email: " + c.getEmail(), FontFactory.getFont("Calibri", 20, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph("Telfono: " + c.getPhoneNumber(), FontFactory.getFont("Calibri", 20, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph("Nickname: " + c.getNickname(), FontFactory.getFont("Calibri", 20, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph("Contrasea: " + c.getPassword(), FontFactory.getFont("Calibri", 20, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph("Puesto: " + c.getRole(), FontFactory.getFont("Calibri", 20, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(new Paragraph( "______________________________________________________________________________")); } documento.close();//Cerramos el flujo con el documento JOptionPane.showMessageDialog(null, "Se ha creado agenda de Empleados."); } catch (DocumentException ex) { Logger.getLogger(generatePDF.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(generatePDF.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Controller.Movimientos.generatePDF.java
public void generateAgendaClientes() { mm = new Model_Movimientos(); try {//from www. ja v a 2 s .co m Calendar calendar = Calendar.getInstance(); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int monthOfYear = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); int hour = calendar.get(Calendar.HOUR_OF_DAY); int min = calendar.get(Calendar.MINUTE); int sec = calendar.get(Calendar.SECOND); Document documento = new Document();//Creamos el documento FileOutputStream ficheroPdf = new FileOutputStream("agendaClientes" + dayOfMonth + "--" + monthOfYear + "--" + year + " " + hour + ";" + min + ";" + sec + ".pdf");//Abrimos el flujo y le asignamos nombre al pdf y su direccion PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);//Instanciamos el documento con el fichero documento.open();//Abrimos el documento documento.add(new Paragraph("Agenda Clientes", FontFactory.getFont("Calibri", 30, Font.BOLD, BaseColor.BLACK)));//Le indicamos el tipo de letra, el tamanio, el estilo y el color de la letra documento.add(new Paragraph("___________________________"));//Realiza un salto de linea Iterator it; it = mm.getUserss().iterator(); while (it.hasNext()) { User u = (User) it.next(); System.out.println("" + u.getEmail().toString()); documento.add(new Paragraph("")); try { Image foto = Image.getInstance("src/IMG/userBig.png"); foto.scaleToFit(48, 48); foto.setAlignment(Chunk.ALIGN_LEFT); documento.add(foto); } catch (Exception e) { e.printStackTrace(); } //Le decimos que nos imprima el Dni, Nombre y Apellidos del cliente, contenidos en el objeto Cliente y le indicamos el tipo de letra, tamanio, estilo y color de la letra documento.add(new Paragraph( "Nombre: " + u.getName() + " Apellidos: " + u.getSurname() + " Email: " + u.getEmail() + " Nickname: " + u.getNickname() + " Contrasea: " + u.getPassword(), FontFactory.getFont("Calibri", 8, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph(" ")); documento.add(new Paragraph( "______________________________________________________________________________")); } documento.close();//Cerramos el flujo con el documento JOptionPane.showMessageDialog(null, "Se ha creado la agenda Clientes."); } catch (DocumentException ex) { Logger.getLogger(generatePDF.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(generatePDF.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Controller.Movimientos.generatePDF.java
public void generateInforme() { mm = new Model_Movimientos(); try {//from w w w . j a v a2 s. c o m Calendar calendar = Calendar.getInstance(); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int monthOfYear = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); int hour = calendar.get(Calendar.HOUR_OF_DAY); int min = calendar.get(Calendar.MINUTE); int sec = calendar.get(Calendar.SECOND); Document documento = new Document();//Creamos el documento FileOutputStream ficheroPdf = new FileOutputStream("agendaClientes" + dayOfMonth + "--" + monthOfYear + "--" + year + " " + hour + ";" + min + ";" + sec + ".pdf");//Abrimos el flujo y le asignamos nombre al pdf y su direccion PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);//Instanciamos el documento con el fichero documento.open();//Abrimos el documento documento.add(new Paragraph("Informe", FontFactory.getFont("Calibri", 30, Font.BOLD, BaseColor.BLACK)));//Le indicamos el tipo de letra, el tamanio, el estilo y el color de la letra documento.add(new Paragraph(" ")); documento.add(new Paragraph("Datos mensuales de Ventas:", FontFactory.getFont("Calibri", 12, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph(" ")); PdfPTable tabla = new PdfPTable(2);//Creamos una tabla de tres columnas tabla.addCell("Mes"); tabla.addCell("NVentas"); tabla.addCell("Enero"); tabla.addCell("" + mm.getRecordEnero()); tabla.addCell("Febrero"); tabla.addCell("" + mm.getRecordFebrero()); tabla.addCell("Marzo"); tabla.addCell("" + mm.getRecordMarzo()); tabla.addCell("Abril"); tabla.addCell("" + mm.getRecordAbril()); tabla.addCell("Mayo"); tabla.addCell("" + mm.getRecordMayo()); tabla.addCell("Junio"); tabla.addCell("" + mm.getRecordJunio()); tabla.addCell("Julio"); tabla.addCell("" + mm.getRecordJulio()); tabla.addCell("Agosto"); tabla.addCell("" + mm.getRecordAgosto()); tabla.addCell("Septiembre"); tabla.addCell("" + mm.getRecordSeptiembre()); tabla.addCell("Octubre"); tabla.addCell("" + mm.getRecordOctubre()); tabla.addCell("Noviembre"); tabla.addCell("" + mm.getRecordNoviembre()); tabla.addCell("Diciembre"); tabla.addCell("" + mm.getRecordDiciembre()); documento.add(tabla); documento.add(new Paragraph(" ")); documento.add(new Paragraph("Conexiones de Empleados:", FontFactory.getFont("Calibri", 12, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph(" ")); PdfPTable tabla2 = new PdfPTable(2);//Creamos una tabla de tres columnas tabla.addCell("Usuario"); tabla.addCell("N Conexiones"); Iterator it; it = mm.getCrews().iterator(); while (it.hasNext()) { Crew c = (Crew) it.next(); System.out.println("" + c.getEmail().toString()); tabla2.addCell("" + c.getName() + " " + c.getSurname()); tabla2.addCell("" + mm.getConexionesCount(c.getEmail().toString())); } documento.add(new Paragraph(" ")); documento.add(tabla2); documento.add(new Paragraph(" ")); documento.add(new Paragraph("Registro de movimientos Empleados: ", FontFactory.getFont("Calibri", 12, Font.BOLD, BaseColor.BLACK))); documento.add(new Paragraph(" ")); Iterator it2; it2 = mm.getBookmark().iterator(); while (it2.hasNext()) { Bookmark c = (Bookmark) it2.next(); System.out.println("" + c.getCrew().toString()); documento.add(new Paragraph( c.getDate() + " User: " + c.getCrew().getName() + " " + c.getCrew().getSurname() + " --> " + c.getDescription(), FontFactory.getFont("Calibri", 10, Font.NORMAL, BaseColor.BLACK))); } documento.close();//Cerramos el flujo con el documento JOptionPane.showMessageDialog(null, "Se ha creado el Informe General"); } catch (DocumentException ex) { Logger.getLogger(generatePDF.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(generatePDF.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:cz.zcu.kiv.eegdatabase.logic.pdf.PDFUtils.java
License:Apache License
public Paragraph setHeader(Document document, String title) throws IOException, BadElementException { Paragraph paragraph = new Paragraph(title, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD, BaseColor.BLACK)); paragraph.setAlignment(Element.ALIGN_CENTER); Image img = GetResizedAndCenteredImage(path + convertPath("/files/images/" + HEADERIMG)); float topMargin = img.getHeight() + 2 * PADDING[0]; img.setAbsolutePosition(PADDING[3], (PageSize.A4.getHeight() - img.getHeight()) - PADDING[0]); paragraph.add(img);/*from w ww . jav a 2 s . co m*/ img = GetResizedAndCenteredImage(path + convertPath("/files/images/" + FOOTERIMG)); img.setAbsolutePosition((PageSize.A4.getWidth() - img.getWidth()) / 2, PADDING[2]); paragraph.add(img); float bottomMargin = img.getHeight() + 2 * PADDING[2]; document.setMargins(topMargin, PADDING[1], bottomMargin, PADDING[3]); paragraph.setSpacingAfter(1.5f * PADDING[0]); return paragraph; }