List of usage examples for com.itextpdf.text Element ALIGN_CENTER
int ALIGN_CENTER
To view the source code for com.itextpdf.text Element ALIGN_CENTER.
Click Source Link
From source file:controlador.generadorticket.GenerarpdfticketVE.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w ww . j a va 2 s. com*/ * * @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 { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8");// Forzar a usar codificacin UTF-8 iso-8859-1 String Encabezado = (request.getParameter("encabezado")); String Encabezado1 = (request.getParameter("encabezado1")); String Encabezado2 = (request.getParameter("encabezado2")); String total = (request.getParameter("total")); String Tipo[] = request.getParameterValues("tipo"); String Costo[] = request.getParameterValues("costo"); String Observacion[] = request.getParameterValues("observacion"); String Fecha = (request.getParameter("Fecha")); String Municipio = (request.getParameter("Municipio")); String Cliente = (request.getParameter("Cliente")); String Estado = (request.getParameter("Estado")); String Direccion = (request.getParameter("Direccion")); String Localidad = (request.getParameter("Localidad")); String Venta = (request.getParameter("Id_venta")); Font fuente = new Font(Font.FontFamily.COURIER, 10); Paragraph P = new Paragraph(); Chunk c = new Chunk(); P.setAlignment(Element.ALIGN_CENTER); try { FileOutputStream Archivo = new FileOutputStream("/home/rcortes/Ejemplo.pdf"); Document doc = new Document(); PdfWriter.getInstance(doc, Archivo); doc.open(); doc.add(new Paragraph(Encabezado)); doc.add(new Paragraph(Encabezado1)); doc.add(new Paragraph(Encabezado2)); PdfPTable tabla1 = new PdfPTable(3); doc.add(new Paragraph(" ")); doc.add(new Paragraph("Venta: " + Venta)); doc.add(new Paragraph("Cliente: " + Cliente)); doc.add(new Paragraph("Estado: " + Estado)); doc.add(new Paragraph("Municipio: " + Municipio)); doc.add(new Paragraph("Localidad: " + Localidad)); doc.add(new Paragraph("Direccin: " + Direccion)); doc.add(new Paragraph(" ")); tabla1.addCell("Tipo"); tabla1.addCell("Monto"); tabla1.addCell("Observacin"); for (int i = 0; i < Tipo.length; i++) { tabla1.addCell(Tipo[i]); tabla1.addCell(Costo[i]); tabla1.addCell(Observacion[i]); } doc.add(tabla1); doc.add(new Paragraph(" ")); doc.add(new Paragraph("Total: " + total)); doc.close(); System.out.println("Se creo pdf\n"); } catch (DocumentException e) { System.out.println(e); } }
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;//from www. j a va 2s. co 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.ControllerCompra.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww . j av 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 { response.setContentType("text/html;charset=UTF-8"); if (request.getParameter("action") != null) { //int estado = 0; String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); String action = request.getParameter("action"); switch (action) { case "Registrar": { String documentoUsuario = (request.getParameter("documentoUsuario")); String facturaProveedor = (request.getParameter("txtNumeroFactura")); String nombreProveedor = (request.getParameter("txtNombre")); int lenght = Integer.parseInt(request.getParameter("size")); int totalCompra = Integer.parseInt(request.getParameter("txtTotalCompra")); listObjDetalleMovimientos = new ArrayList<>(); for (int i = 0; i < lenght; i++) { _objDetalleMovimiento = new ObjDetalleMovimiento(); _objDetalleMovimiento .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]"))); _objDetalleMovimiento .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]"))); _objDetalleMovimiento.setPrecioArticulo( Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]"))); _objDetalleMovimiento.setTotalDetalleMovimiento( _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo()); _objDetalleMovimiento.setDescuento(lenght); listObjDetalleMovimientos.add(_objDetalleMovimiento); } _objUsuario.setDocumentoUsuario(documentoUsuario); _objCompra.setFacturaProveedor(facturaProveedor); _objCompra.setNombreProveedor(nombreProveedor); _objCompra.setTotalCompra(totalCompra); daoModelCompra = new ModelCompra(); String salida = Mensaje(daoModelCompra.Add(_objCompra, _objUsuario, listObjDetalleMovimientos), "La compra ha sido registrada", "Ha ocurrido un error"); daoModelCompra.Signout(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(salida); break; } case "Consultar": { int id = Integer.parseInt(request.getParameter("id")); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(consultarDetalle(id)); break; } case "Enlistar": { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(getTableCompra()); break; } //<editor-fold defaultstate="collapsed" desc="PDF mediante iText"> case "Imprimir": { response.setContentType("application/pdf"); try { Locale loc = Locale.getDefault(); NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc); //Primero obtengo el id del Movimiento int id = Integer.parseInt(request.getParameter("id")); //Obtengo el reporte a manera de Map Map material = reporte(id); //Topo ese reporte y lo divido, primero en la compra y luego el detalle Map<String, String> compra = (Map) material.get("Compra"); List<Map> detalle = (List) material.get("Detalle"); //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento. Document document = new Document(); OutputStream os = response.getOutputStream(); //Creo una instancia a partir del documento y del canal PdfWriter.getInstance(document, os); //Abro el documento document.open(); Image logo = Image.getInstance(url + "/public/images/logo.png"); logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4)); document.add(logo); //Creo una fuente para la letra en negrilla final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); //Escribo y agrego un primer parrafo con los datos basicos de la compra Paragraph headerDerecha = new Paragraph(); headerDerecha.add(new Chunk("Nombre del Proveedor: ", helveticaBold)); headerDerecha.add(new Chunk(compra.get("nombreProveedor") + "\n")); headerDerecha.add(new Chunk("Factura del Proveedor: ", helveticaBold)); headerDerecha.add(new Chunk(compra.get("facturaProveedor") + "\n")); headerDerecha.add(new Chunk("Fecha Compra: ", helveticaBold)); headerDerecha.add(new Chunk(compra.get("fechaCompra") + "\n")); //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte Paragraph headerIzquierda = new Paragraph(); headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold)); headerIzquierda.add(new Chunk("Direccin: ", helveticaBold)); headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n")); headerIzquierda.add(new Chunk("Telfono: ", helveticaBold)); headerIzquierda.add(new Chunk("2583697 \n")); //Agrego los dos anteriores parrafos al Header PdfPTable header = new PdfPTable(2); header.getDefaultCell().setBorder(0); header.addCell(headerIzquierda); header.addCell(headerDerecha); header.setWidthPercentage(100f); header.setSpacingAfter(20); document.add(header); //Creo la tabla del detalle PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 }); tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Compra", helveticaBold)); tituloCell.setBorder(0); tituloCell.setColspan(4); tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER); tablaDetalle.addCell(tituloCell); //Aqui creo cada cabecera tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY); tablaDetalle.addCell(new Phrase("ID", helveticaBold)); tablaDetalle.addCell(new Phrase("Nombre", helveticaBold)); tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold)); tablaDetalle.addCell(new Phrase("Valor", helveticaBold)); tablaDetalle.getDefaultCell().setBackgroundColor(null); //Aqui agrego la tabla cada articulo. for (Map<String, String> next : detalle) { tablaDetalle.addCell(next.get("idArticulo")); tablaDetalle.addCell(next.get("descripcionArticulo")); tablaDetalle.addCell(next.get("cantidad")); tablaDetalle .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo")))); } //Creo el Footer headerIzquierda = new Paragraph(); headerIzquierda.add(new Chunk("Total: ", helveticaBold)); headerIzquierda .add(new Chunk(currencyFormatter.format(Integer.parseInt(compra.get("totalCompra"))))); PdfPCell footerCell = new PdfPCell(headerIzquierda); footerCell.setBorder(0); footerCell.setColspan(4); footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tablaDetalle.addCell(footerCell); //Establesco el tamao y posicion de la tabla, luego la agrego al documento tablaDetalle.setWidthPercentage(100f); tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT); document.add(tablaDetalle); //Cierro el documento y lo envio con flush. document.close(); response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\""); os.flush(); os.close(); } catch (DocumentException de) { throw new IOException(de.getMessage()); } break; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="PDF mediante iReports"> case "Imprimir2": { try { int id = Integer.parseInt(request.getParameter("id")); String source = url + "/reports/newReport1.jrxml"; JasperPrint jasperPrint = null; JasperReport jasperReport = null; JasperDesign jasperDesign = null; System.out.println(source); String reportPath = request.getServletContext().getRealPath("reports") + "\\newReport1.jrxml"; jasperDesign = JRXmlLoader.load(reportPath); jasperReport = JasperCompileManager.compileReport(jasperDesign); jasperPrint = JasperFillManager.fillReport(jasperReport, reporte(id), daoModelCompra.getConnection()); JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream()); } catch (Exception ex) { for (StackTraceElement ruta : ex.getStackTrace()) { System.err.println(ruta); } } } break; //</editor-fold> } } }
From source file:Controller.ControllerVenta.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w.ja va 2 s .co 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 { response.setContentType("text/html;charset=UTF-8"); if (request.getParameter("action") != null) { String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); String action = request.getParameter("action"); switch (action) { case "Registrar": { String documentoUsuario = (request.getParameter("documentoUsuario")); String documentoCliente = null; String nombreCliente = null; int numeroVenta = 0; if (Validador.validarDocumento(request.getParameter("documentoCliente")) & Validador.validarNombresCompletos(request.getParameter("txtNombreCliente")) & Validador.validarNumero(request.getParameter("txtNumeroVenta"))) { documentoCliente = (request.getParameter("documentoCliente")); nombreCliente = (request.getParameter("txtNombreCliente")); numeroVenta = Integer.parseInt(request.getParameter("txtNumeroVenta")); } else { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(Mensaje(false, null, "Ha ingresado datos incorrectos")); break; } int lenght = Integer.parseInt(request.getParameter("size")); int totalCompra = Integer.parseInt(request.getParameter("txtTotalVenta")); listOjbDetalleMovimientos = new ArrayList<>(); for (int i = 0; i < lenght; i++) { _objDetalleMovimiento = new ObjDetalleMovimiento(); _objDetalleMovimiento .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]"))); _objDetalleMovimiento .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]"))); _objDetalleMovimiento.setPrecioArticulo( Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]"))); _objDetalleMovimiento.setTotalDetalleMovimiento( _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo()); _objDetalleMovimiento.setDescuento(lenght); listOjbDetalleMovimientos.add(_objDetalleMovimiento); } _objUsuario.setDocumentoUsuario(documentoUsuario); _objVenta.setIdVenta(numeroVenta); _objVenta.setDocumentoCliente(documentoCliente); _objVenta.setNombreCliente(nombreCliente); _objVenta.setTotalVenta(totalCompra); daoModelVenta = new ModelVenta(); String salida = Mensaje(daoModelVenta.Add(_objVenta, _objUsuario, listOjbDetalleMovimientos), "La venta ha sido registrada", "Ha ocurrido un error"); daoModelVenta.Signout(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(salida); break; } case "Consultar": { int id = Integer.parseInt(request.getParameter("id")); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(consultarDetalle(id)); break; } case "Enlistar": { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(getTableVenta()); break; } case "Contador": { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(getContador()); break; } case "Imprimir": { response.setContentType("application/pdf"); try { Locale loc = Locale.getDefault(); NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc); //Primero obtengo el id del Movimiento int id = Integer.parseInt(request.getParameter("id")); //Obtengo el reporte a manera de Map Map material = reporte(id); //Topo ese reporte y lo divido, primero en la compra y luego el detalle Map<String, String> venta = (Map) material.get("Venta"); List<Map> detalle = (List) material.get("Detalle"); //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento. Document document = new Document(); OutputStream os = response.getOutputStream(); //Creo una instancia a partir del documento y del canal PdfWriter.getInstance(document, os); //Abro el documento document.open(); Image logo = Image.getInstance(url + "/public/images/logo.png"); logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4)); document.add(logo); //Creo una fuente para la letra en negrilla final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); //Escribo y agrego un primer parrafo con los datos basicos de la compra Paragraph headerDerecha = new Paragraph(); headerDerecha.add(new Chunk("Id. de la Venta: ", helveticaBold)); headerDerecha.add(new Chunk(venta.get("numeroVenta") + "\n")); headerDerecha.add(new Chunk("Nombre del Cliente: ", helveticaBold)); headerDerecha.add(new Chunk(venta.get("nombreCliente") + "\n")); headerDerecha.add(new Chunk("Documento del Cliente: ", helveticaBold)); headerDerecha.add(new Chunk(venta.get("documentoCliente") + "\n")); headerDerecha.add(new Chunk("Fecha Venta: ", helveticaBold)); headerDerecha.add(new Chunk(venta.get("fechaVenta") + "\n")); //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte Paragraph headerIzquierda = new Paragraph(); headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold)); headerIzquierda.add(new Chunk("Direccin: ", helveticaBold)); headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n")); headerIzquierda.add(new Chunk("Telfono: ", helveticaBold)); headerIzquierda.add(new Chunk("2583697 \n")); //Agrego los dos anteriores parrafos al Header PdfPTable header = new PdfPTable(2); header.getDefaultCell().setBorder(0); header.addCell(headerIzquierda); header.addCell(headerDerecha); header.setWidthPercentage(100f); header.setSpacingAfter(20); document.add(header); //Creo la tabla del detalle PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 }); tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Venta", helveticaBold)); tituloCell.setBorder(0); tituloCell.setColspan(4); tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER); tablaDetalle.addCell(tituloCell); //Aqui creo cada cabecera tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY); tablaDetalle.addCell(new Phrase("ID", helveticaBold)); tablaDetalle.addCell(new Phrase("Nombre", helveticaBold)); tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold)); tablaDetalle.addCell(new Phrase("Valor", helveticaBold)); tablaDetalle.getDefaultCell().setBackgroundColor(null); //Aqui agrego la tabla cada articulo. for (Map<String, String> next : detalle) { tablaDetalle.addCell(next.get("idArticulo")); tablaDetalle.addCell(next.get("descripcionArticulo")); tablaDetalle.addCell(next.get("cantidad")); tablaDetalle .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo")))); } //Creo el Footer headerIzquierda = new Paragraph(); headerIzquierda.add(new Chunk("Total: ", helveticaBold)); headerIzquierda .add(new Chunk(currencyFormatter.format(Integer.parseInt(venta.get("totalVenta"))))); PdfPCell footerCell = new PdfPCell(headerIzquierda); footerCell.setBorder(0); footerCell.setColspan(4); footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tablaDetalle.addCell(footerCell); //Establesco el tamao y posicion de la tabla, luego la agrego al documento tablaDetalle.setWidthPercentage(100f); tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT); document.add(tablaDetalle); //Cierro el documento y lo envio con flush. document.close(); response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\""); os.flush(); os.close(); } catch (DocumentException de) { throw new IOException(de.getMessage()); } break; } } } }
From source file:Controller.CrearPDF.java
/** * We create a PDF document with iText using different elements to learn * to use this library./*from w w w. j a v a2 s.c om*/ * Creamos un documento PDF con iText usando diferentes elementos para aprender * a usar esta librera. * @param pdfNewFile <code>String</code> * pdf File we are going to write. * Fichero pdf en el que vamos a escribir. */ // public void createPDF(File pdfNewFile, ReparacionEntity reparacion) throws Exception { public void createPDF(File pdfNewFile) throws Exception { // We create the document and set the file name. // Creamos el documento e indicamos el nombre del fichero. try { // ClienteController cc = new ClienteController(); // Cliente cliente = cc.buscarPorId(reparacion.getCliente()); Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile)); } catch (FileNotFoundException fileNotFoundException) { System.out.println("No such file was found to generate the PDF " + "(No se encontr el fichero para generar el pdf)" + fileNotFoundException); } document.open(); // We add metadata to PDF // Aadimos los metadatos del PDF document.addTitle("Table export to PDF (Exportamos la tabla a PDF)"); document.addSubject("Using iText (usando iText)"); document.addKeywords("Java, PDF, iText"); document.addAuthor("Cdigo Xules"); document.addCreator("Cdigo Xules"); // First page // Primera pgina Chunk chunk = new Chunk("RDEN DE TRABAJO", categoryFont); Chunk c2 = new Chunk("\n\n\nCentro de Formacin SATCAR6\n" + "Calle Artes Grficas n1 Nave 12 A\n" + "Pinto (28320), Madrid", smallFont); Chunk c3 = new Chunk("Datos del Cliente", smallBold); // Chunk c4 = new Chunk("Nombre: "+cliente.getRazonSocial(),smallBold); // Chunk c5 = new Chunk("Poblacin: "+cliente.getPoblacion(),smallBold); // Chunk c6 = new Chunk("Provincia: "+cliente.getProvincia(),smallBold); // Chunk c7 = new Chunk("Cdigo Postal: "+cliente.getCp(),smallBold); // Chunk c8 = new Chunk("Num Telfono: Pepito"+cliente.getTlf1(),smallBold); Chunk c4 = new Chunk("Nombre: Jesus Eduardo Garcia Toril", smallBold); Chunk c5 = new Chunk("Poblacin: Pinto", smallBold); Chunk c6 = new Chunk("Provincia: Madrid", smallBold); Chunk c7 = new Chunk("Cdigo Postal: 28320", smallBold); Chunk c8 = new Chunk("Num Telfono: 659408182", smallBold); Paragraph parrafo = new Paragraph(chunk); Paragraph p2 = new Paragraph(c2); Paragraph p3 = new Paragraph(c3); Phrase ph1 = new Phrase(c4); Phrase ph2 = new Phrase(c5); Phrase ph3 = new Phrase(c6); Phrase ph4 = new Phrase(c7); Phrase ph5 = new Phrase(c8); // Let's create de first Chapter (Creemos el primer captulo) // We add an image (Aadimos una imagen) Image image; try { parrafo.setAlignment(Element.ALIGN_CENTER); image = Image.getInstance(iTextExampleImage); image.setAbsolutePosition(0, 750); p2.setAlignment(Element.ALIGN_LEFT); document.add(parrafo); document.add(image); document.add(p2); document.add(p3); document.add(ph1); document.add(ph2); document.add(ph3); document.add(ph4); document.add(ph5); } catch (BadElementException ex) { System.out.println("Image BadElementException" + ex); } // Second page - some elements // Segunda pgina - Algunos elementos // List by iText (listas por iText) String text = "test 1 2 3 "; for (int i = 0; i < 5; i++) { text = text + text; } List list = new List(List.UNORDERED); ListItem item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); text = "a b c align "; for (int i = 0; i < 5; i++) { text = text + text; } item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); text = "supercalifragilisticexpialidocious "; for (int i = 0; i < 3; i++) { text = text + text; } item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); // How to use PdfPTable // Utilizacin de PdfPTable // We use various elements to add title and subtitle // Usamos varios elementos para aadir ttulo y subttulo Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont); anchor.setName("Table export to PDF (Exportamos la tabla a PDF)"); Chapter chapTitle = new Chapter(new Paragraph(anchor), 1); Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont); Section paragraphMore = chapTitle.addSection(paragraph); paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)")); Integer numColumns = 6; Integer numRows = 120; // We create the table (Creamos la tabla). PdfPTable table = new PdfPTable(numColumns); // Now we fill the PDF table // Ahora llenamos la tabla del PDF PdfPCell columnHeader; // Fill table rows (rellenamos las filas de la tabla). for (int column = 0; column < numColumns; column++) { columnHeader = new PdfPCell(new Phrase("COL " + column)); columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(columnHeader); } table.setHeaderRows(1); // Fill table rows (rellenamos las filas de la tabla). for (int row = 0; row < numRows; row++) { for (int column = 0; column < numColumns; column++) { table.addCell("Row " + row + " - Col" + column); } } // We add the table (Aadimos la tabla) paragraphMore.add(table); // We add the paragraph with the table (Aadimos el elemento con la tabla). document.add(chapTitle); document.close(); System.out.println("Your PDF file has been generated!(Se ha generado tu hoja PDF!"); } catch (DocumentException documentException) { System.out.println( "The file not exists (Se ha producido un error al generar un documento): " + documentException); } }
From source file:controller.CreateTranscript.java
private void CreateTranscript(MyPerson p) {//,PrintWriter out){ Document document = new Document(); String name = p.getFName() + p.getLName(); try {//w w w. j a va 2 s .co m if (p.getUserType() == 6) { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\" + name + ".pdf")); document.open(); PdfPTable table = new PdfPTable(8); // 8 columns. table.setWidthPercentage(100); //Width 100% table.setSpacingBefore(10f); //Space before table table.setSpacingAfter(10f); //Space after table //Set Column widths float[] columnWidths = { 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f }; table.setWidths(columnWidths); PdfPCell cell1 = new PdfPCell(new Paragraph("Subject Name")); cell1.setBorderColor(BaseColor.BLUE); cell1.setPaddingLeft(10); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell2 = new PdfPCell(new Paragraph("Subject Code")); cell2.setBorderColor(BaseColor.BLUE); cell2.setPaddingLeft(10); cell2.setHorizontalAlignment(Element.ALIGN_CENTER); cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell3 = new PdfPCell(new Paragraph("Written Grade")); cell3.setBorderColor(BaseColor.BLUE); cell3.setPaddingLeft(10); cell3.setHorizontalAlignment(Element.ALIGN_CENTER); cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell4 = new PdfPCell(new Paragraph("Midterm Grade")); cell4.setBorderColor(BaseColor.BLUE); cell4.setPaddingLeft(10); cell4.setHorizontalAlignment(Element.ALIGN_CENTER); cell4.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell5 = new PdfPCell(new Paragraph("Final Exam Grade")); cell5.setBorderColor(BaseColor.BLUE); cell5.setPaddingLeft(10); cell5.setHorizontalAlignment(Element.ALIGN_CENTER); cell5.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell6 = new PdfPCell(new Paragraph("Final Grade")); cell6.setBorderColor(BaseColor.BLUE); cell6.setPaddingLeft(10); cell6.setHorizontalAlignment(Element.ALIGN_CENTER); cell6.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell7 = new PdfPCell(new Paragraph("Term")); cell7.setBorderColor(BaseColor.BLUE); cell7.setPaddingLeft(10); cell7.setHorizontalAlignment(Element.ALIGN_CENTER); cell7.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell8 = new PdfPCell(new Paragraph("Registration Date")); cell8.setBorderColor(BaseColor.BLUE); cell8.setPaddingLeft(10); cell8.setHorizontalAlignment(Element.ALIGN_CENTER); cell8.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); table.addCell(cell4); table.addCell(cell5); table.addCell(cell6); table.addCell(cell7); table.addCell(cell8); ModelOfStudent modelOfStudent = new ModelOfStudent(); ResultSet rs = modelOfStudent.ViewMyCourses(p.getCode()); // if(!rs.next()){out.println("<font color='blue'>There is no Courses Untill Now ^_^ </font>");} while (rs.next()) { table.addCell(rs.getString("SubjectName")); table.addCell(rs.getString("ID")); table.addCell(rs.getString("WritenGrade")); table.addCell(rs.getString("MidtermGrade")); table.addCell(rs.getString("FinalExamGrade")); table.addCell(rs.getString("FinalGrade")); table.addCell(rs.getString("Term")); table.addCell(rs.getString("StudentRegisterSubjectDate")); /* String SubjectRegisterDate=String.valueOf(rs.getDate("SubjectRegisterDate")); table.addCell(SubjectRegisterDate); */ } //To avoid having the cell border and the content overlap, if you are having thick cell borders //cell1.setUserBorderPadding(true); //cell2.setUserBorderPadding(true); //cell3.setUserBorderPadding(true); document.add(new Paragraph("University: " + MyPerson.ReturnUniversityName(p.getCode()))); document.add(new Paragraph("Faculity: " + MyPerson.ReturnFaculityName(p.getCode()))); document.add( new Paragraph("Student Name: " + p.getFName() + " " + p.getMName() + " " + p.getLName())); document.add(new Paragraph("Level: " + MyPerson.ReturnLevelName(p.getCode()))); document.add(new Paragraph("Department: " + MyPerson.ReturnDepartmentName(p.getCode()))); document.add(table); System.out.println( "<script type='text/javascript' > alert('Successfull Creating Transcript ^_^ ');history.back();</script>"); //out.println("Successfull Creating Transcript ^_^"); document.close(); writer.close(); } //end of if student } catch (Exception e) { System.out.println("<script type='text/javascript' > alert('Failed Creating Transcript ^_^ Error:" + e.getMessage() + " ');history.back();</script>"); // out.println(""+e.getMessage()); e.printStackTrace(); } }
From source file:controller.pdf.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www. j a v a2 s . c om*/ * * @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 { response.setContentType("application/pdf"); OutputStream out = response.getOutputStream(); try { String especialidad = request.getParameter("especialidad"); String turno = request.getParameter("turno"); String dia = request.getParameter("dia"); Document documento = new Document(); documento.setPageSize(PageSize.A4); documento.setPageSize(PageSize.A4.rotate()); // Rectangle one = new Rectangle(70,140); // documento.setPageSize(one); // documento.setMargins(2, 2, 2, 2); PdfWriter.getInstance(documento, out); documento.open(); Paragraph par1 = new Paragraph(); Font fonttitulo = new Font(Font.FontFamily.HELVETICA, 25, Font.BOLD, BaseColor.BLACK); if (turno.equalsIgnoreCase("M")) { par1.add(new Phrase("Citas del dia: " + dia + " Turno Maana", fonttitulo)); } else { par1.add(new Phrase("Citas del dia: " + dia + " Turno Tarde", fonttitulo)); } par1.setAlignment(Element.ALIGN_CENTER); par1.add(new Phrase(Chunk.NEWLINE)); par1.add(new Phrase(Chunk.NEWLINE)); par1.add(new Phrase(Chunk.NEWLINE)); documento.add(par1); PdfPTable tabla = new PdfPTable(9); PdfPCell celda1 = new PdfPCell( new Paragraph("Codigo Cita", FontFactory.getFont("Arial", 12, Font.BOLD))); PdfPCell celda2 = new PdfPCell( new Paragraph("Especialidad", FontFactory.getFont("Arial", 12, Font.BOLD))); PdfPCell celda3 = new PdfPCell( new Paragraph("Codigo Paciente", FontFactory.getFont("Arial", 12, Font.BOLD))); PdfPCell celda4 = new PdfPCell(new Paragraph("Nombre", FontFactory.getFont("Arial", 12, Font.BOLD))); PdfPCell celda5 = new PdfPCell( new Paragraph("Apellido Paterno", FontFactory.getFont("Arial", 12, Font.BOLD))); PdfPCell celda6 = new PdfPCell( new Paragraph("Apellido Materno", FontFactory.getFont("Arial", 12, Font.BOLD))); PdfPCell celda7 = new PdfPCell(new Paragraph("Hora", FontFactory.getFont("Arial", 12, Font.BOLD))); PdfPCell celda8 = new PdfPCell(new Paragraph("Doctor", FontFactory.getFont("Arial", 12, Font.BOLD))); PdfPCell celda9 = new PdfPCell(new Paragraph("Da", FontFactory.getFont("Arial", 12, Font.BOLD))); tabla.addCell(celda1); tabla.addCell(celda2); tabla.addCell(celda3); tabla.addCell(celda4); tabla.addCell(celda5); tabla.addCell(celda6); tabla.addCell(celda7); tabla.addCell(celda8); tabla.addCell(celda9); try { Connection conex = conexion.obtener(); PreparedStatement consulta2 = conex.prepareStatement("call pacientegeneral_select();"); ResultSet resultado2 = consulta2.executeQuery(); while (resultado2.next()) { PreparedStatement consulta = conex.prepareStatement("call cita_select();"); ResultSet resultado = consulta.executeQuery(); while (resultado.next()) { if (turno.equalsIgnoreCase("M") && resultado.getString(4).charAt(6) == 'A' && resultado.getInt(3) == resultado2.getInt(1) && resultado.getString(7).equalsIgnoreCase(dia) && resultado.getString(2).equalsIgnoreCase(especialidad)) { tabla.addCell(resultado.getString(1)); tabla.addCell(resultado.getString(2)); tabla.addCell(resultado2.getString(1)); tabla.addCell(resultado2.getString(2)); tabla.addCell(resultado2.getString(3)); tabla.addCell(resultado2.getString(4)); tabla.addCell(resultado.getString(4)); tabla.addCell(resultado.getString(5)); tabla.addCell(resultado.getString(7)); } } } conexion.cerrar(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.toString()); } try { Connection conex = conexion.obtener(); PreparedStatement consulta2 = conex.prepareStatement("call pacientegeneral_select();"); ResultSet resultado2 = consulta2.executeQuery(); while (resultado2.next()) { PreparedStatement consulta = conex.prepareStatement("call cita_select();"); ResultSet resultado = consulta.executeQuery(); while (resultado.next()) { if (turno.equalsIgnoreCase("T") && resultado.getString(4).charAt(6) == 'P' && resultado.getInt(3) == resultado2.getInt(1) && resultado.getString(7).equalsIgnoreCase(dia) && resultado.getString(2).equalsIgnoreCase(especialidad)) { tabla.addCell(resultado.getString(1)); tabla.addCell(resultado.getString(2)); tabla.addCell(resultado2.getString(1)); tabla.addCell(resultado2.getString(2)); tabla.addCell(resultado2.getString(3)); tabla.addCell(resultado2.getString(4)); tabla.addCell(resultado.getString(4)); tabla.addCell(resultado.getString(5)); tabla.addCell(resultado.getString(7)); } } } conexion.cerrar(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.toString()); } float[] columnWidths = new float[] { 15f, 30f, 18f, 23f, 23f, 23f, 20f, 25f, 18f }; tabla.setWidths(columnWidths); documento.add(tabla); documento.close(); } catch (Exception ex) { ex.getMessage(); } String redirectURL = "citasemana.jsp"; response.sendRedirect(redirectURL); }
From source file:controller.pdfcita.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w. ja v a 2 s. 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 { response.setContentType("application/pdf"); OutputStream out = response.getOutputStream(); String codigocita = request.getParameter("codigocita"); String nombre = request.getParameter("nombre"); String especialidad = request.getParameter("especialidad"); String fecha = request.getParameter("fecha"); String hora = request.getParameter("hora"); String doctor = request.getParameter("doctor"); try { try { Document documento = new Document(); Rectangle one = new Rectangle(400, 280); documento.setPageSize(one); PdfWriter.getInstance(documento, out); documento.open(); Paragraph par1 = new Paragraph(); Font fontitulo = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK); par1.add(new Phrase("Cita", fontitulo)); par1.setAlignment(Element.ALIGN_CENTER); par1.add(new Phrase(Chunk.NEWLINE)); par1.add(new Phrase(Chunk.NEWLINE)); documento.add(par1); Paragraph par2 = new Paragraph(); Font fontescrip = new Font(Font.FontFamily.TIMES_ROMAN, 9, Font.NORMAL, BaseColor.BLACK); par2.add( new Phrase("LUGAR DE CONSULTA : POLICL?NICO NUESTRA SEORA DE LOS ANGELES", fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase("CODIGO DE CITA : " + codigocita, fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase("PACIENTE : " + nombre, fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase("ESPECIALIDAD : " + especialidad, fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase("FECHA : " + fecha, fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase("HORA DE CITA : " + hora, fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase("DOCTOR(A) : " + doctor, fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase("COSTO DE CITA : 10.00 SOLES", fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase( "El paciente tendr que imprimir esta cita y acercarse a caja para cancelar el monto de la cita para posteriormente acudir a su cita en el consultorio establecido en el recibo.", fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); //par2.add(new Phrase(Chunk.NEWLINE)); par2.add(new Phrase( " - Administracin", fontescrip)); par2.add(new Phrase(Chunk.NEWLINE)); par2.setAlignment(Element.ALIGN_JUSTIFIED); documento.add(par2); documento.close(); } catch (Exception ex) { ex.getMessage(); } } finally { out.close(); } //// try{ // // // // Document document = new Document(); // Rectangle one = new Rectangle(70,140); // document.setPageSize(one); // // document.open(); // Paragraph par1=new Paragraph(); // Font fonttitulo=new Font(Font.FontFamily.HELVETICA,25,Font.BOLD,BaseColor.BLACK); // // par1.add(new Phrase("Citas del dia: Turno Maana",fonttitulo)); // document.add(par1); // // // // //// Paragraph p = new Paragraph("Hi"); //// document.add(p); //// document.setPageSize(two); //// document.setMargins(20, 20, 20, 20); //// document.newPage(); //// document.add(p); // document.close(); // // // //// String especialidad=request.getParameter("especialidad"); //// String turno=request.getParameter("turno"); //// String dia=request.getParameter("dia"); // //// Document documento=new Document(); //// documento.setPageSize(PageSize.A4); //// documento.setPageSize(PageSize.A4.rotate()); //// PdfWriter.getInstance(documento, out); //// //// documento.open(); // //// Paragraph par1=new Paragraph(); //// Font fonttitulo=new Font(Font.FontFamily.HELVETICA,25,Font.BOLD,BaseColor.BLACK); //// if (turno.equalsIgnoreCase("M")) { //// par1.add(new Phrase("Citas del dia: "+dia+" Turno Maana",fonttitulo)); //// } //// else{par1.add(new Phrase("Citas del dia: "+dia+" Turno Tarde",fonttitulo));} //// //// //// par1.setAlignment(Element.ALIGN_CENTER); //// par1.add(new Phrase(Chunk.NEWLINE)); //// par1.add(new Phrase(Chunk.NEWLINE)); //// documento.add(par1); //// //// PdfPTable tabla=new PdfPTable(9); //// PdfPCell celda1=new PdfPCell(new Paragraph("Codigo Cita",FontFactory.getFont("Arial", 12, Font.BOLD))); //// PdfPCell celda2=new PdfPCell(new Paragraph("Especialidad",FontFactory.getFont("Arial", 12, Font.BOLD))); //// PdfPCell celda3=new PdfPCell(new Paragraph("Codigo Paciente",FontFactory.getFont("Arial", 12, Font.BOLD))); //// PdfPCell celda4=new PdfPCell(new Paragraph("Nombre",FontFactory.getFont("Arial", 12, Font.BOLD))); //// PdfPCell celda5=new PdfPCell(new Paragraph("Apellido Paterno",FontFactory.getFont("Arial", 12, Font.BOLD))); //// PdfPCell celda6=new PdfPCell(new Paragraph("Apellido Materno",FontFactory.getFont("Arial", 12, Font.BOLD))); //// PdfPCell celda7=new PdfPCell(new Paragraph("Hora",FontFactory.getFont("Arial", 12, Font.BOLD))); //// PdfPCell celda8=new PdfPCell(new Paragraph("Doctor",FontFactory.getFont("Arial", 12, Font.BOLD))); //// PdfPCell celda9=new PdfPCell(new Paragraph("Da",FontFactory.getFont("Arial", 12, Font.BOLD))); // //// tabla.addCell(celda1); //// tabla.addCell(celda2); //// tabla.addCell(celda3); //// tabla.addCell(celda4); //// tabla.addCell(celda5); //// tabla.addCell(celda6); //// tabla.addCell(celda7); //// tabla.addCell(celda8); //// tabla.addCell(celda9); //// //// try{ //// //// Connection conex=conexion.obtener(); //// //// PreparedStatement consulta2=conex.prepareStatement("call pacientegeneral_select();"); //// ResultSet resultado2=consulta2.executeQuery(); //// //// while(resultado2.next()){ //// //// PreparedStatement consulta=conex.prepareStatement("call cita_select();"); //// ResultSet resultado=consulta.executeQuery(); //// //// while(resultado.next()){ //// //// if (turno.equalsIgnoreCase("M") && resultado.getString(4).charAt(6)=='A' && resultado.getInt(3)==resultado2.getInt(1) && resultado.getString(7).equalsIgnoreCase(dia) && resultado.getString(2).equalsIgnoreCase(especialidad)) { //// //// tabla.addCell(resultado.getString(1)); //// tabla.addCell(resultado.getString(2)); //// tabla.addCell(resultado2.getString(1)); //// tabla.addCell(resultado2.getString(2)); //// tabla.addCell(resultado2.getString(3)); //// tabla.addCell(resultado2.getString(4)); //// tabla.addCell(resultado.getString(4)); //// tabla.addCell(resultado.getString(5)); //// tabla.addCell(resultado.getString(7)); //// //// } //// //// } //// } //// //// conexion.cerrar(); //// }catch(Exception ex){JOptionPane.showMessageDialog(null, ex.toString());} // // // // //// try{ //// //// Connection conex=conexion.obtener(); //// //// PreparedStatement consulta2=conex.prepareStatement("call pacientegeneral_select();"); //// ResultSet resultado2=consulta2.executeQuery(); //// //// while(resultado2.next()){ //// //// PreparedStatement consulta=conex.prepareStatement("call cita_select();"); //// ResultSet resultado=consulta.executeQuery(); //// //// while(resultado.next()){ //// //// if (turno.equalsIgnoreCase("T") && resultado.getString(4).charAt(6)=='P' && resultado.getInt(3)==resultado2.getInt(1) && resultado.getString(7).equalsIgnoreCase(dia) && resultado.getString(2).equalsIgnoreCase(especialidad)) { //// //// tabla.addCell(resultado.getString(1)); //// tabla.addCell(resultado.getString(2)); //// tabla.addCell(resultado2.getString(1)); //// tabla.addCell(resultado2.getString(2)); //// tabla.addCell(resultado2.getString(3)); //// tabla.addCell(resultado2.getString(4)); //// tabla.addCell(resultado.getString(4)); //// tabla.addCell(resultado.getString(5)); //// tabla.addCell(resultado.getString(7)); //// //// } //// //// } //// } //// //// conexion.cerrar(); //// }catch(Exception ex){JOptionPane.showMessageDialog(null, ex.toString());} // // // // // // //// float[] columnWidths = new float[]{15f, 30f, 18f, 23f, 23f, 23f, 20f, 25f, 18f}; //// tabla.setWidths(columnWidths); //// //// documento.add(tabla); // document.close(); // // }catch(Exception ex){ex.getMessage();} // // String redirectURL="principal.jsp"; //// response.sendRedirect(redirectURL); }
From source file:controller.PdfManager.java
/** * This method will generate an pdf for the applicant * @param email the email of the user/*www . java2s . com*/ * @param competences the competences that the applican has added * @param dates the availability periods that the applicant added * @throws IOException */ public void downloadPDF(String email, List<CompetenceProfileDTO> competences, List<String> dates) throws IOException { FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); try { Font font1 = new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD); Font font2 = new Font(Font.FontFamily.HELVETICA, 25, Font.UNDERLINE); Font font3 = new Font(Font.FontFamily.HELVETICA, 14); Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); Paragraph h1 = new Paragraph("" + email + " Application", font1); h1.setAlignment(Element.ALIGN_CENTER); document.add(h1); //Add all competences document.add(new Paragraph("Competences", font2)); for (CompetenceProfileDTO s : competences) { document.add(new Paragraph( "Work: " + s.getName() + " Years of Experience: " + s.getYearsOfExperience() + " ", font3)); } document.add(new Paragraph("Availability", font2)); for (String ava : dates) { document.add(new Paragraph("" + ava + "", font3)); } document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setHeader("Content-Disposition", "inline; filename=\"" + email + "\".pdf"); response.setContentType("application/pdf"); // the contentlength response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream OutputStream os = response.getOutputStream(); baos.writeTo(os); os.flush(); os.close(); } catch (DocumentException e) { throw new IOException(e.getMessage()); } }
From source file:Controller.PrintOrderManagedBean.java
public void executePDF(String maDH) { try {/* ww w . java2 s . com*/ DonHang donhang = new DonHang(); donhang.init(maDH); float CONVERT = 28.346457f;// 1 cm FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); //response.setHeader("Content-disposition","inline; filename=kiran.pdf"); response.setHeader("Pragma", "public"); response.setContentType("application/pdf"); //response.setHeader("Content-Disposition", "attachment;filename=\"ContactList.pdf\""); response.addHeader("Content-disposition", "attachment;filename=\"DataListBean.pdf\""); //step 1: creation of a document-object Document document = new Document(PageSize.A4, 0.5f * CONVERT, 0.5f * CONVERT, 1.0f * CONVERT, 1.0f * CONVERT); //step 2: we create a writer that listens to the document // and directs a PDF-stream to a temporary buffer ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); PdfWriter writer = PdfWriter.getInstance(document, baos); BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(bf, 18, Font.BOLD); Font font11 = new Font(bf, 11, Font.NORMAL); Font font11_bo = new Font(bf, 11, Font.BOLD); Font font12 = new Font(bf, 12, Font.NORMAL); Font font10 = new Font(bf, 10, Font.NORMAL); Font font9 = new Font(bf, 9, Font.NORMAL); //step 3: we open the document document.open(); PdfPTable tab_Header1; tab_Header1 = new PdfPTable(1); tab_Header1.setWidthPercentage(100); tab_Header1.setHorizontalAlignment(Element.ALIGN_CENTER); PdfPCell cell1; cell1 = new PdfPCell(new Phrase("CNG TY TNHH ABC FASHION", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell( new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S?T: 0909465621", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("?N GIAO HNG", font12)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Bn Bn:", font11_bo)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tn: CNG TY TNHH ABC FASHION", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell( new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S in thoi: 0909465621", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Bn Mua:", font11_bo)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tn: " + donhang.getTenKH(), font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("?a ch: " + donhang.getDiaChiKH(), font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S in thoi: " + donhang.getSoDTKH(), font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Bn Vn chuyn:", font11_bo)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tn:....................................", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("?a ch:...............................", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S in thoi:...............................", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Danh sch hng ha:", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); ///////////////////////////////bn sn phm float[] crDonHang = { 1.0f * CONVERT, 4.0f * CONVERT, 1.0f * CONVERT, 2.0f * CONVERT, 2.0f * CONVERT }; PdfPTable tab_Header2; tab_Header2 = new PdfPTable(crDonHang.length); tab_Header2.setWidthPercentage(100); tab_Header2.setWidths(crDonHang); tab_Header2.setHorizontalAlignment(Element.ALIGN_CENTER); NumberFormat formatter = new DecimalFormat("#,###,###"); String[] crheader = { "STT", "Tn Hng", "S Lng", "Gi Bn(VN?)", "Thnh Ti?n(VN?)" }; for (int i = 0; i < crheader.length; i++) { PdfPCell cell = new PdfPCell(new Phrase(crheader[i], font11)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tab_Header2.addCell(cell); } int stt = 1; for (SanPhamDH sp : donhang.getListSP()) { PdfPCell cell = new PdfPCell(new Phrase(String.valueOf(stt), font11)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tab_Header2.addCell(cell); cell = new PdfPCell(new Phrase(sp.getTenSP(), font11)); cell.setHorizontalAlignment(Element.ALIGN_LEFT); tab_Header2.addCell(cell); cell = new PdfPCell(new Phrase(sp.getSoluong(), font11)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); tab_Header2.addCell(cell); cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getGiaSP())), font11)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); tab_Header2.addCell(cell); cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getThanhTien())), font11)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); tab_Header2.addCell(cell); stt++; } cell1 = new PdfPCell(tab_Header2); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tng ti?n hng: " + formatter.format( Double.parseDouble(donhang.getTienTamTinh() == null ? "0" : donhang.getTienTamTinh())) + " VN?", font11)); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tng ti?n vn chuyn: " + formatter.format(Double .parseDouble(donhang.getTienVanChuyen() == null ? "0" : donhang.getTienVanChuyen())) + " VN?", font11)); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tng ti?n thanh ton: " + formatter.format(Double.parseDouble(donhang.getTongTien())) + " VN?", font11)); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S ti?n thanh ton bng ch: " + DocTien.doctien(donhang.getTongTien().replaceAll(" ", "")) + "ng", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase(" ", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("TP H Ch Minh, ngy thng nm ", font11)); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setPaddingRight(1.0f * CONVERT); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase(" ", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); PdfPTable tab_Header3; tab_Header3 = new PdfPTable(3); tab_Header3.setWidthPercentage(100); tab_Header3.setHorizontalAlignment(Element.ALIGN_CENTER); cell1 = new PdfPCell(new Phrase("Ng?i nhn hng", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("Ng?i giao hng", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("Ng?i bn hng", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(tab_Header3); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setBorder(0); tab_Header1.addCell(cell1); document.add(tab_Header1); document.close(); //step 6: we output the writer as bytes to the response output // the contentlength is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); baos.flush(); faces.responseComplete(); } catch (Exception e) { e.printStackTrace(); } }