List of usage examples for com.itextpdf.text.pdf PdfPCell setBorder
public void setBorder(final int border)
From source file:Servlet.FacturaCompraServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w.j av a2 s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { HttpSession session = request.getSession(true); boolean sw1 = false; LinkedList<ProductoCompraClass> lista = (LinkedList) session.getAttribute("productoscompra"); Calendar fecha = new GregorianCalendar(); FacturaCompraProductoDAO fvpd = new FacturaCompraProductoDAO(); FacturaCompraDAO fvd = new FacturaCompraDAO(); ProductoDAO pd = new ProductoDAO(); TransaccionDAO td = new TransaccionDAO(); ProveedorClass cc = new ProveedorClass(); AsientoDAO ad = new AsientoDAO(); AsientoClass ac1 = new AsientoClass(); cc = (ProveedorClass) session.getAttribute("proveedorcompra"); String a = session.getAttribute("idFacturacompra").toString(); String b = session.getAttribute("fechaFacturacompra").toString(); ac1 = ad.consultarfecha(b); AsientoClass ac2 = new AsientoClass(); Calendar cal = Calendar.getInstance(); if (ac1.getIdAsiento() == null) { ac2 = new AsientoClass("1", Integer.toString(cal.get(Calendar.YEAR)), b, "1", "", "0", "0"); ad.insertar(ac2); ac2 = ad.consultarfecha(b); } else { int xvr = Integer.parseInt(ac1.getNumeroAsiento()) + 1; ac2 = new AsientoClass(ac1.getNumeroDiario(), ac1.getPeriodoAsiento(), b, String.valueOf(xvr), "", "0", "0"); ad.insertar(ac2); ac2 = ad.consultarfecha(b); } String c = request.getParameter("descuentoFacturacompra").toString(); String d = cc.getIdProveedor(); String e = request.getParameter("ivaFacturacompra"); int hora = fecha.get(Calendar.HOUR_OF_DAY); String hr; if (hora < 10) { hr = "0" + String.valueOf(hora); } else { hr = String.valueOf(hora); } int minuto = fecha.get(Calendar.MINUTE); String mnt; if (minuto < 10) { mnt = "0" + String.valueOf(minuto); } else { mnt = String.valueOf(minuto); } int segundo = fecha.get(Calendar.SECOND); String sgd; if (segundo < 10) { sgd = "0" + String.valueOf(segundo); } else { sgd = String.valueOf(segundo); } String horaactual = hr + ":" + mnt + ":" + sgd; FacturaCompraClass fvc = new FacturaCompraClass(a, horaactual, b, "986789456734", "PARQUE INDUSTRIAL", "001", c, d, e); boolean sw0 = fvd.insertar(fvc); if (sw0) { for (int i = 0; i < lista.size(); i++) { try { String idFactura = session.getAttribute("idFacturacompra").toString(); String idProducto = lista.get(i).getIdProducto().toUpperCase(); String cantidadProducto = lista.get(i).getCantidadProducto().toUpperCase(); FacturaCompraProductoClass u = new FacturaCompraProductoClass(idFactura, idProducto, cantidadProducto); boolean sw = fvpd.insertar(u); if (sw) { int val1 = request.getParameter("formaspagoFacturacompra").toString().indexOf("-"); int val2 = request.getParameter("formaspagoFacturacompra").toString().length(); String cuenta1 = request.getParameter("formaspagoFacturacompra").toString() .substring(val1 + 1, val2); String cuenta2 = "21"; String concepto = "Compra de productos. Factura Compra " + a; String debe = request.getParameter("cedldatotalcompra"); String haber = request.getParameter("cedldatotalcompra"); String referencia = "Factura Compra " + a; String documento = session.getAttribute("idFacturacompra").toString(); String idAsiento = ac2.getIdAsiento(); String numeroDiario = String.valueOf(Integer.parseInt(ac2.getNumeroDiario())); String periodoAsiento = ac2.getPeriodoAsiento(); String fechaAsiento = ac2.getFechaAsiento(); String numeroAsiento = ac2.getNumeroAsiento(); String conceptoAsiento = concepto; String debeAsiento = String.valueOf(Float.parseFloat(debe)); String haberAsiento = String.valueOf(Float.parseFloat(haber)); AsientoClass ac3; ac3 = new AsientoClass(idAsiento, numeroDiario, periodoAsiento, fechaAsiento, numeroAsiento, conceptoAsiento, debeAsiento, haberAsiento); boolean sw5 = ad.modificar(ac3); if (sw5) { TransaccionClass u1 = new TransaccionClass(debe, "0", referencia, documento, cuenta2, ac2.getIdAsiento()); TransaccionClass u2 = new TransaccionClass("0", haber, referencia, documento, cuenta1, ac2.getIdAsiento()); boolean sw3 = td.insertar(u1); boolean sw4 = td.insertar(u2); if (sw3 && sw4) { try { sw1 = sw; boolean sw2 = pd.modificarcantidadcompra( (String) lista.get(i).getIdProducto().toString(), (String) lista.get(i).getCostoProducto().toString(), (String) lista.get(i).getCantidadProducto().toString()); if (sw2) { } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } catch (SQLException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } catch (SQLException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } } ///////////////////////////////////// Document document = new Document(); response.setContentType("application/pdf"); PdfWriter.getInstance(document, response.getOutputStream()); LinkedList<ProductoCompraClass> listaxvr = (LinkedList) session.getAttribute("productoscompra"); PdfPCell cell; int i = 0; float to = 0; document.open(); /* new paragraph instance initialized and add function write in pdf file*/ PdfPTable mitablafactura = new PdfPTable(2); cell = new PdfPCell(new Phrase("Factura")); cell.setBorder(Rectangle.NO_BORDER); mitablafactura.addCell(cell); cell = new PdfPCell(new Phrase("Fecha")); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablafactura.addCell(cell); cell = new PdfPCell(new Phrase(a)); cell.setBorder(Rectangle.NO_BORDER); mitablafactura.addCell(cell); cell = new PdfPCell(new Phrase(b)); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablafactura.addCell(cell); document.add(mitablafactura); document.add(new Phrase("\n")); PdfPTable mitablaproveedor = new PdfPTable(2); cell = new PdfPCell(new Phrase("RUC Proveedor")); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase(cc.getIdentificacionProveedor())); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase("Nombre Proveedor")); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase(cc.getNombreProveedor())); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase("Direccion Proveedor")); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase(cc.getDireccionProveedor())); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase("Telefono Proveedor")); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase(cc.getTelefonoProveedor())); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); document.add(mitablaproveedor); document.add(new Phrase("\n")); PdfPTable mitablasimple = new PdfPTable(4); mitablasimple.addCell("ID"); mitablasimple.addCell("Cantidad"); mitablasimple.addCell("Costo"); mitablasimple.addCell("Total"); for (Iterator iter = listaxvr.iterator(); iter.hasNext();) { ProductoCompraClass customerBean = (ProductoCompraClass) iter.next(); String id = customerBean.getIdProducto(); String cantidad = customerBean.getCantidadProducto(); String costo = customerBean.getCostoProducto(); String total = String.valueOf(Float.valueOf(cantidad) * Float.valueOf(costo)); mitablasimple.addCell(id); mitablasimple.addCell(cantidad); mitablasimple.addCell(costo); mitablasimple.addCell(total); listaxvr.remove(i); i++; to = to + Float.valueOf(total); session.setAttribute("productoscompra", listaxvr); } float descuento = to * (Float.valueOf(c)); IVAClass i1 = new IVAClass(); IVADAO i2 = new IVADAO(); i1 = i2.consultariva(e); float iva = (to - descuento) * Float.valueOf(i1.getValorIva()); float x = to - descuento + iva; mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("SubTotal"); mitablasimple.addCell(String.valueOf(to)); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("Descuento"); mitablasimple.addCell(c); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("SubTotal Descuento"); mitablasimple.addCell(String.valueOf(descuento)); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("IVA"); mitablasimple.addCell(i1.getValorIva()); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("SubTotal IVA"); mitablasimple.addCell(String.valueOf(iva)); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("Total"); mitablasimple.addCell(String.valueOf(x)); document.add(mitablasimple); document.close(); //document instance closed //////////////////////////////////// } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } catch (SQLException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(FacturaCompraServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Servlet.FacturaVentaServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w .ja v a 2 s .c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { HttpSession session = request.getSession(true); boolean sw1 = false; LinkedList<ProductoVentaClass> lista = (LinkedList) session.getAttribute("productos"); Calendar fecha = new GregorianCalendar(); FacturaVentaProductoDAO fvpd = new FacturaVentaProductoDAO(); FacturaVentaDAO fvd = new FacturaVentaDAO(); ProductoDAO pd = new ProductoDAO(); TransaccionDAO td = new TransaccionDAO(); ClienteClass cc = new ClienteClass(); AsientoDAO ad = new AsientoDAO(); AsientoClass ac1 = new AsientoClass(); cc = (ClienteClass) session.getAttribute("cliente"); String a = session.getAttribute("idFactura").toString(); String b = session.getAttribute("fechaFactura").toString(); ac1 = ad.consultarfecha(b); AsientoClass ac2 = new AsientoClass(); Calendar cal = Calendar.getInstance(); if (ac1.getIdAsiento() == null) { ac2 = new AsientoClass("1", Integer.toString(cal.get(Calendar.YEAR)), b, "1", "", "0", "0"); ad.insertar(ac2); ac2 = ad.consultarfecha(b); } else { int xvr = Integer.parseInt(ac1.getNumeroAsiento()) + 1; ac2 = new AsientoClass(ac1.getNumeroDiario(), ac1.getPeriodoAsiento(), b, String.valueOf(xvr), "", "0", "0"); ad.insertar(ac2); ac2 = ad.consultarfecha(b); } String c = request.getParameter("descuentoFactura").toString(); String d = cc.getIdCliente(); String e = request.getParameter("ivaFactura"); int hora = fecha.get(Calendar.HOUR_OF_DAY); String hr; if (hora < 10) { hr = "0" + String.valueOf(hora); } else { hr = String.valueOf(hora); } int minuto = fecha.get(Calendar.MINUTE); String mnt; if (minuto < 10) { mnt = "0" + String.valueOf(minuto); } else { mnt = String.valueOf(minuto); } int segundo = fecha.get(Calendar.SECOND); String sgd; if (segundo < 10) { sgd = "0" + String.valueOf(segundo); } else { sgd = String.valueOf(segundo); } String horaactual = hr + ":" + mnt + ":" + sgd; FacturaVentaClass fvc = new FacturaVentaClass(a, horaactual, b, "986789456734", "PARQUE INDUSTRIAL", "001", c, d, e); boolean sw0 = fvd.insertar(fvc); if (sw0) { for (int i = 0; i < lista.size(); i++) { try { String idFactura = session.getAttribute("idFactura").toString(); String idProducto = lista.get(i).getIdProducto().toUpperCase(); String cantidadProducto = lista.get(i).getCantidadProducto().toUpperCase(); FacturaVentaProductoClass u = new FacturaVentaProductoClass(idFactura, idProducto, cantidadProducto); boolean sw = fvpd.insertar(u); if (sw) { int val1 = request.getParameter("formaspagoFactura").toString().indexOf("-"); int val2 = request.getParameter("formaspagoFactura").toString().length(); String cuenta1 = request.getParameter("formaspagoFactura").toString() .substring(val1 + 1, val2); String cuenta2 = "21"; String concepto = "Venta de productos. Factura Venta " + a; String debe = request.getParameter("cedldatotal"); String haber = request.getParameter("cedldatotal"); String referencia = "Factura Venta " + a; String documento = session.getAttribute("idFactura").toString(); String idAsiento = ac2.getIdAsiento(); String numeroDiario = String.valueOf(Integer.parseInt(ac2.getNumeroDiario())); String periodoAsiento = ac2.getPeriodoAsiento(); String fechaAsiento = ac2.getFechaAsiento(); String numeroAsiento = ac2.getNumeroAsiento(); String conceptoAsiento = concepto; String debeAsiento = String.valueOf(Float.parseFloat(debe)); String haberAsiento = String.valueOf(Float.parseFloat(haber)); AsientoClass ac3; ac3 = new AsientoClass(idAsiento, numeroDiario, periodoAsiento, fechaAsiento, numeroAsiento, conceptoAsiento, debeAsiento, haberAsiento); boolean sw5 = ad.modificar(ac3); if (sw5) { TransaccionClass u1 = new TransaccionClass(debe, "0", referencia, documento, cuenta1, ac2.getIdAsiento()); TransaccionClass u2 = new TransaccionClass("0", haber, referencia, documento, cuenta2, ac2.getIdAsiento()); boolean sw3 = td.insertar(u1); boolean sw4 = td.insertar(u2); if (sw3 && sw4) { try { sw1 = sw; boolean sw2 = pd.modificarcantidadventa( (String) lista.get(i).getIdProducto().toString(), (String) lista.get(i).getCantidadProducto().toString()); if (sw2) { } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } catch (SQLException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } catch (SQLException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } } ///////////////////////////////////// Document document = new Document(); response.setContentType("application/pdf"); PdfWriter.getInstance(document, response.getOutputStream()); LinkedList<ProductoVentaClass> listaxvr = (LinkedList) session.getAttribute("productos"); PdfPCell cell; int i = 0; float to = 0; document.open(); /* new paragraph instance initialized and add function write in pdf file*/ PdfPTable mitablafactura = new PdfPTable(2); cell = new PdfPCell(new Phrase("Factura")); cell.setBorder(Rectangle.NO_BORDER); mitablafactura.addCell(cell); cell = new PdfPCell(new Phrase("Fecha")); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablafactura.addCell(cell); cell = new PdfPCell(new Phrase(a)); cell.setBorder(Rectangle.NO_BORDER); mitablafactura.addCell(cell); cell = new PdfPCell(new Phrase(b)); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablafactura.addCell(cell); document.add(mitablafactura); document.add(new Phrase("\n")); PdfPTable mitablaproveedor = new PdfPTable(2); cell = new PdfPCell(new Phrase("Cedula/RUC Cliente")); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase(cc.getCedula())); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase("Nombre Cliente")); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase(cc.getNombre() + " " + cc.getApellido())); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase("Direccion Cliente")); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase(cc.getDireccion())); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase("Telefono Cliente")); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); cell = new PdfPCell(new Phrase(cc.getTelefono())); cell.setHorizontalAlignment(Element.ALIGN_MIDDLE); cell.setBorder(Rectangle.NO_BORDER); mitablaproveedor.addCell(cell); document.add(mitablaproveedor); document.add(new Phrase("\n")); PdfPTable mitablasimple = new PdfPTable(4); mitablasimple.addCell("ID"); mitablasimple.addCell("Cantidad"); mitablasimple.addCell("Costo"); mitablasimple.addCell("Total"); for (Iterator iter = listaxvr.iterator(); iter.hasNext();) { ProductoVentaClass customerBean = (ProductoVentaClass) iter.next(); String id = customerBean.getIdProducto(); String cantidad = customerBean.getCantidadProducto(); String costo = customerBean.getPrecioProducto(); String total = String.valueOf(Float.valueOf(cantidad) * Float.valueOf(costo)); mitablasimple.addCell(id); mitablasimple.addCell(cantidad); mitablasimple.addCell(costo); mitablasimple.addCell(total); listaxvr.remove(i); i++; to = to + Float.valueOf(total); session.setAttribute("productos", listaxvr); } float descuento = to * (Float.valueOf(c)); IVAClass i1 = new IVAClass(); IVADAO i2 = new IVADAO(); i1 = i2.consultariva(e); float iva = (to - descuento) * Float.valueOf(i1.getValorIva()); float x = to - descuento + iva; mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("SubTotal"); mitablasimple.addCell(String.valueOf(to)); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("Descuento"); mitablasimple.addCell(c); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("SubTotal Descuento"); mitablasimple.addCell(String.valueOf(descuento)); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("IVA"); mitablasimple.addCell(i1.getValorIva()); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("SubTotal IVA"); mitablasimple.addCell(String.valueOf(iva)); mitablasimple.addCell(""); mitablasimple.addCell(""); mitablasimple.addCell("Total"); mitablasimple.addCell(String.valueOf(x)); document.add(mitablasimple); document.close(); //document instance closed //////////////////////////////////// } else { PrintWriter out = response.getWriter(); out.println("Fail registration."); } } catch (SQLException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(FacturaVentaServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:servlet.PdfGenerator.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . j a v a2 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 { Document report = new Document(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(report, baos); DBManager manager = (DBManager) getServletContext().getAttribute("dbmanager"); Group groupToReport = manager.getGroup(Integer.parseInt(request.getParameter("id"))); LinkedList<User> groupUsers = manager.getUsersForGroupAndVisible(groupToReport.getId()); Timestamp lastPosted = manager.getLatestPost(groupToReport); int numberOfPosts = manager.getGroupPosts(groupToReport).size(); String context = request.getServletContext().getRealPath("/"); Iterator<User> groupIterator = groupUsers.iterator(); report.open(); // INSERTING DOCUMENT CONTENT AREA Font title = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 24); Font text = FontFactory.getFont(FontFactory.HELVETICA, 12); Paragraph documentHead = new Paragraph(groupToReport.getName(), title); Paragraph newLine = new Paragraph(Chunk.NEWLINE); Paragraph latestPost = new Paragraph("Latest post inserted on: " + lastPosted, text); Paragraph postsNumberToReport = new Paragraph("Number of posts: " + numberOfPosts, text); //LAYOUT AND FINAL PARAGRAPH EDITING AREA report.add(documentHead); report.add(newLine); report.add(postsNumberToReport); report.add(newLine); report.add(latestPost); report.add(newLine); PdfPTable usersTable = new PdfPTable(5); // LOOP FOR SETTING TABLE while (groupIterator.hasNext()) { User u = groupIterator.next(); String userName = u.getName(); PdfPCell avatarCell = new PdfPCell(Image.getInstance(context + u.getAvatar(request))); avatarCell.setBorder(0); avatarCell.setPaddingBottom(10); avatarCell.setColspan(1); PdfPCell userNameCell = new PdfPCell(new Phrase(userName)); userNameCell.setColspan(4); userNameCell.setBorder(0); userNameCell.setPaddingBottom(10); userNameCell.setPaddingLeft(10); usersTable.addCell(avatarCell); usersTable.addCell(userNameCell); } usersTable.setHorizontalAlignment(PdfPTable.ALIGN_LEFT); report.add(usersTable); report.close(); // SETTING SOME RESPONSE HEADER response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // SETTING THE CONTENT TYPE response.setContentType("application/pdf"); // THE CONTENTLENGHT response.setContentLength(baos.size()); System.out.println("ci sono"); try (OutputStream os = response.getOutputStream()) { baos.writeTo(os); os.flush(); os.close(); } catch (Exception e) { throw new IOException(e.getMessage()); } } catch (DocumentException e) { throw new IOException(e.getMessage()); } }
From source file:Servlets.GenerarPinesGrupo.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String[] idEstudiante = req.getParameterValues("imprimir"); resp.setContentType("application/pdf"); OutputStream out = resp.getOutputStream(); String foto = getServletContext().getRealPath("/recursos/img/logoColegio.png"); req.setCharacterEncoding("UTF-8"); try {//from w w w .j av a 2s . co m try { Document documento = new Document(); PdfWriter.getInstance(documento, out); documento.open(); Paragraph par1 = new Paragraph(); Font fontit = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.GRAY); par1.add(new Phrase("Pin de Acceso HeartsTics", fontit)); par1.setAlignment(Element.ALIGN_CENTER); par1.add(new Phrase(Chunk.NEWLINE)); par1.add(new Phrase(Chunk.NEWLINE)); documento.add(par1); // Image image = Image.getInstance("E:\\ArchivosVarios\\logoColegio.png"); // image.scalePercent(50); Image image = Image.getInstance(foto); image.scalePercent(60); Font fuentetabla = FontFactory.getFont("Arial", 8, Font.BOLD, BaseColor.BLACK); Font fuentetablaPin = FontFactory.getFont("Arial", 10, Font.BOLD, BaseColor.BLACK); Font fuentetablaHeader = FontFactory.getFont("Arial", 9, Font.BOLD, BaseColor.BLACK); Servicio controlador = new Servicio(); for (int i = 0; i < idEstudiante.length; i++) { int idEst = Integer.parseInt(idEstudiante[i]); Pin estudiante = controlador.pinEstudiante(idEst); PdfPTable tabla = new PdfPTable(3); tabla.setWidthPercentage(60); PdfPCell celdaHeader = new PdfPCell( new Paragraph("COLEGIO SAGRADOS CORAZONES", fuentetablaHeader)); celdaHeader.setVerticalAlignment(Element.ALIGN_MIDDLE); celdaHeader.setHorizontalAlignment(Element.ALIGN_CENTER); celdaHeader.setColspan(3); tabla.addCell(celdaHeader); PdfPCell celda01 = new PdfPCell(image); //PdfPCell celda01 = new PdfPCell(new Paragraph("imagen")); celda01.setHorizontalAlignment(Element.ALIGN_CENTER); celda01.setVerticalAlignment(Element.ALIGN_MIDDLE); celda01.setRowspan(2); celda01.setBorder(Rectangle.NO_BORDER); celda01.setBorder(Rectangle.LEFT); tabla.addCell(celda01); PdfPCell celda1 = new PdfPCell(new Paragraph( "Estudiante: " + estudiante.getNombres() + " " + estudiante.getApellidos(), fuentetabla)); PdfPCell celda2 = new PdfPCell(new Paragraph("Pin: " + estudiante.getIdPin(), fuentetablaPin)); PdfPCell celda3 = new PdfPCell( new Paragraph("Fecha creacion: " + estudiante.getInicio(), fuentetabla)); PdfPCell celda4 = new PdfPCell( new Paragraph("Fecha vencimiento: " + estudiante.getFin(), fuentetabla)); celda1.setHorizontalAlignment(Element.ALIGN_CENTER); celda1.setVerticalAlignment(Element.ALIGN_MIDDLE); celda1.setColspan(2); celda1.setBorder(Rectangle.NO_BORDER); celda1.setBorder(Rectangle.RIGHT); celda2.setHorizontalAlignment(Element.ALIGN_CENTER); celda2.setVerticalAlignment(Element.ALIGN_MIDDLE); celda2.setColspan(2); celda2.setBorder(Rectangle.NO_BORDER); celda2.setBorder(Rectangle.RIGHT); PdfPTable tableFecha = new PdfPTable(2); tableFecha.setWidthPercentage(60); celda3.setHorizontalAlignment(Element.ALIGN_CENTER); celda4.setHorizontalAlignment(Element.ALIGN_CENTER); tabla.addCell(celda1); tabla.addCell(celda2); tableFecha.addCell(celda3); tableFecha.addCell(celda4); Paragraph par2 = new Paragraph(); par2.add(new Phrase(Chunk.NEWLINE)); documento.add(par2); documento.add(tabla); documento.add(tableFecha); } documento.close(); } catch (Exception e) { e.getMessage(); } } finally { out.close(); } }
From source file:Servlets.GenerarPinEstudiante.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int idEstudiante = Integer.parseInt(req.getParameter("idEst")); resp.setContentType("application/pdf"); OutputStream out = resp.getOutputStream(); String foto = getServletContext().getRealPath("/recursos/img/logoColegio.png"); req.setCharacterEncoding("UTF-8"); try {/*from w w w. j a va 2 s . c om*/ try { Document documento = new Document(); PdfWriter.getInstance(documento, out); documento.open(); Paragraph par1 = new Paragraph(); Font fontit = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.GRAY); par1.add(new Phrase("Pin de Acceso HeartsTics", fontit)); par1.setAlignment(Element.ALIGN_CENTER); par1.add(new Phrase(Chunk.NEWLINE)); par1.add(new Phrase(Chunk.NEWLINE)); documento.add(par1); // Image image = Image.getInstance("E:\\ArchivosVarios\\logoColegio.png"); // image.scalePercent(50); Image image = Image.getInstance(foto); image.scalePercent(60); Font fuentetabla = FontFactory.getFont("Arial", 8, Font.BOLD, BaseColor.BLACK); Font fuentetablaPin = FontFactory.getFont("Arial", 10, Font.BOLD, BaseColor.BLACK); Font fuentetablaHeader = FontFactory.getFont("Arial", 9, Font.BOLD, BaseColor.BLACK); Servicio controlador = new Servicio(); Pin estudiante = controlador.pinEstudiante(idEstudiante); PdfPTable tabla = new PdfPTable(3); tabla.setWidthPercentage(60); PdfPCell celdaHeader = new PdfPCell(new Paragraph("COLEGIO SAGRADOS CORAZONES", fuentetablaHeader)); celdaHeader.setVerticalAlignment(Element.ALIGN_MIDDLE); celdaHeader.setHorizontalAlignment(Element.ALIGN_CENTER); celdaHeader.setColspan(3); tabla.addCell(celdaHeader); PdfPCell celda01 = new PdfPCell(image); //PdfPCell celda01 = new PdfPCell(new Paragraph("imagen")); celda01.setHorizontalAlignment(Element.ALIGN_CENTER); celda01.setVerticalAlignment(Element.ALIGN_MIDDLE); celda01.setRowspan(2); celda01.setBorder(Rectangle.NO_BORDER); celda01.setBorder(Rectangle.LEFT); tabla.addCell(celda01); PdfPCell celda1 = new PdfPCell(new Paragraph( "Estudiante: " + estudiante.getNombres() + " " + estudiante.getApellidos(), fuentetabla)); PdfPCell celda2 = new PdfPCell(new Paragraph("Pin: " + estudiante.getIdPin(), fuentetablaPin)); PdfPCell celda3 = new PdfPCell( new Paragraph("Fecha creacion: " + estudiante.getInicio(), fuentetabla)); PdfPCell celda4 = new PdfPCell( new Paragraph("Fecha vencimiento: " + estudiante.getFin(), fuentetabla)); celda1.setHorizontalAlignment(Element.ALIGN_CENTER); celda1.setVerticalAlignment(Element.ALIGN_MIDDLE); celda1.setColspan(2); celda1.setBorder(Rectangle.NO_BORDER); celda1.setBorder(Rectangle.RIGHT); celda2.setHorizontalAlignment(Element.ALIGN_CENTER); celda2.setVerticalAlignment(Element.ALIGN_MIDDLE); celda2.setColspan(2); celda2.setBorder(Rectangle.NO_BORDER); celda2.setBorder(Rectangle.RIGHT); PdfPTable tableFecha = new PdfPTable(2); tableFecha.setWidthPercentage(60); celda3.setHorizontalAlignment(Element.ALIGN_CENTER); celda4.setHorizontalAlignment(Element.ALIGN_CENTER); tabla.addCell(celda1); tabla.addCell(celda2); tableFecha.addCell(celda3); tableFecha.addCell(celda4); Paragraph par2 = new Paragraph(); par2.add(new Phrase(Chunk.NEWLINE)); documento.add(par2); documento.add(tabla); documento.add(tableFecha); documento.close(); } catch (Exception e) { e.getMessage(); } } finally { out.close(); } }
From source file:servlets.POPDF.java
private void buildpdf(PurchaseOrderDTO dto, HttpServletResponse response) { Font catFont = new Font(Font.FontFamily.HELVETICA, 24, Font.BOLD); Font subFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD); Font smallBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); String IMG = getServletContext().getRealPath("/img/logo.png"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); VendorDTO venDTO = venModel.getVendor(dto.getVendorno(), ds); DecimalFormat decimal = new DecimalFormat("#0.00"); ArrayList<ProductDTO> products = prodModel.getProdsForVendor(dto.getVendorno(), ds); ArrayList<POLineItemDTO> poLineItems = dto.getItems(); try {//from w ww .j av a2s . c om PdfWriter.getInstance(document, baos); document.open(); Paragraph preface = new Paragraph(); // We add one empty line Image image1 = Image.getInstance(IMG); image1.setAbsolutePosition(55f, 760f); preface.add(image1); preface.setAlignment(Element.ALIGN_RIGHT); // Lets write a big header Paragraph mainHead = new Paragraph(String.format("%55s", "Purchase Order"), catFont); preface.add(mainHead); preface.setAlignment(Element.ALIGN_LEFT); preface.add(new Paragraph(String.format("%82s", "PO#: " + dto.getPONumber()), subFont)); addEmptyLine(preface, 3); preface.add(new Paragraph(String.format("%10s", "Vendor: ", smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getName(), smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getAddress1(), smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getCity(), smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getProvince(), smallBold))); preface.add(new Paragraph(String.format("%5s", venDTO.getPostalCode(), smallBold))); addEmptyLine(preface, 1); // 3 column table PdfPTable table = new PdfPTable(5); PdfPCell cell = new PdfPCell(new Paragraph("Product Code", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Paragraph("Product Description", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Paragraph("Quantity Sold", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Paragraph("Price", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Paragraph("Ext Price", smallBold)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); for (POLineItemDTO item : poLineItems) { cell = new PdfPCell(new Phrase(item.getproductcode())); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); for (ProductDTO prod : products) { if (prod.getProductcode().equals(item.getproductcode())) { cell = new PdfPCell(new Phrase(prod.getProductname())); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } } cell = new PdfPCell(new Phrase(Integer.toString(item.getQuantity()))); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); double extPrice = 0.0; for (ProductDTO prod : products) { if (prod.getProductcode().equals(item.getproductcode())) { cell = new PdfPCell(new Phrase(Double.toString(prod.getCostprice()))); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); extPrice = prod.getCostprice() * item.getQuantity(); } } String extPriceStr = decimal.format(extPrice); cell = new PdfPCell(new Phrase(extPriceStr)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); } //end for double sub = dto.getAmount(); double tax = dto.getAmount() * 0.13; double total = dto.getAmount() * 1.13; String taxStr = decimal.format(tax); String totalStr = decimal.format(total); String subStr = decimal.format(sub); cell = new PdfPCell(new Phrase("Total:")); cell.setColspan(4); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell = new PdfPCell(new Phrase(subStr)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell = new PdfPCell(new Phrase("Tax:")); cell.setColspan(4); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell = new PdfPCell(new Phrase(taxStr)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell = new PdfPCell(new Phrase("Order Total:")); cell.setColspan(4); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); cell = new PdfPCell(new Phrase(totalStr)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setBackgroundColor(BaseColor.YELLOW); table.addCell(cell); preface.add(table); addEmptyLine(preface, 3); preface.setAlignment(Element.ALIGN_CENTER); preface.add(new Paragraph(String.format("%60s", "Generated on: " + dto.getPODate()), subFont)); document.add(preface); 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"); // setting the content type 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 (Exception e) { System.out.println("Error " + e.getMessage()); } }
From source file:servlets.POServlet.java
private void buildpdf(HttpServletResponse response, int ponumber) { Font catFont = new Font(Font.FontFamily.HELVETICA, 24, Font.BOLD); Font subFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD); Font titleFont = new Font(Font.FontFamily.COURIER, 16, Font.BOLD); Font smallBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); String IMG = getServletContext().getRealPath("/img/logo.png"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); //Get the Purchase Order Items - That way we can access the vendor PurchaseOrderModel poModel = new PurchaseOrderModel(); PurchaseOrderDTO poDTO = poModel.getPurchaseOrder(ponumber, ds); ArrayList<PurchaseOrderLineItemDTO> lineitems = poModel.getLineItemsForPoNumber(ponumber, ds); //Have items, now need to get vendor VendorModel vModel = new VendorModel(); VendorDTO vendor = vModel.getVendor(poDTO.getVendorno(), ds); //Product Model - For looking up product names ProductModel prodMod = new ProductModel(); try {//from w w w.j a v a 2s . co m PdfWriter.getInstance(document, baos); document.open(); Paragraph preface = new Paragraph(); // We add one empty line Image image1 = Image.getInstance(IMG); image1.setAbsolutePosition(55f, 650f); image1.scaleAbsolute(200f, 200f); preface.add(image1); preface.add(new Paragraph("Guardians Light Equipment\nBest Exotics in the Cosmos", titleFont)); preface.setAlignment(Element.ALIGN_RIGHT); // Lets write a big header Paragraph mainHead = new Paragraph(String.format("%55s", "Purchase Order"), catFont); preface.add(mainHead); preface.add(new Paragraph(String.format("%82s", "PO#:" + ponumber), subFont)); addEmptyLine(preface, 1); //2 Column Vendor Table PdfPTable vendorTable = new PdfPTable(1); PdfPCell vCell = new PdfPCell(new Phrase("Vendor:", smallBold)); vCell.setHorizontalAlignment(Element.ALIGN_RIGHT); vCell.setBorder(0); vendorTable.addCell(vCell); vendorTable.addCell(GenerateBorderlessCell(vendor.getName(), 0, Element.ALIGN_RIGHT)); vendorTable.addCell(GenerateBorderlessCell(vendor.getAddress1(), 0, Element.ALIGN_RIGHT)); vendorTable.addCell( GenerateBorderlessCell(vendor.getCity() + "," + vendor.getProvince(), 0, Element.ALIGN_RIGHT)); vendorTable.addCell(GenerateBorderlessCell(vendor.getPostalcode(), 0, Element.ALIGN_RIGHT)); preface.add(vendorTable); addEmptyLine(preface, 2); //Generate Headers PdfPTable table = new PdfPTable(5); //Generate the Headers table.addCell(GenerateCellData("Product Code")); table.addCell(GenerateCellData("Product Description")); table.addCell(GenerateCellData("Quantity Sold")); table.addCell(GenerateCellData("Price")); table.addCell(GenerateCellData("Extended Price")); double subTotal = 0.0; for (PurchaseOrderLineItemDTO item : lineitems) { ProductDTO product = prodMod.getProduct(item.getProductcode(), ds); table.addCell(GenerateCellData(product.getProductcode())); table.addCell(GenerateCellData(product.getProductname())); table.addCell(GenerateCellData(String.valueOf(item.getQty()))); double ext = product.getCostprice() * item.getQty(); table.addCell(GenerateCellData("$" + String.format("%.2f", product.getCostprice()))); table.addCell(GenerateCellData("$" + String.format("%.2f", ext))); subTotal += ext; } //Generate Total, Tax, Order Total table.addCell(GenerateBorderlessCell("Subtotal:", 4, Element.ALIGN_RIGHT)); table.addCell(GenerateFinalValue("$" + String.format("%.2f", subTotal))); table.addCell(GenerateBorderlessCell("Tax:", 4, Element.ALIGN_RIGHT)); table.addCell(GenerateFinalValue("$" + String.format("%.2f", subTotal * 0.13))); table.addCell(GenerateBorderlessCell("Order Total:", 4, Element.ALIGN_RIGHT)); PdfPCell totalCell = GenerateFinalValue("$" + String.format("%.2f", poDTO.getTotal())); totalCell.setBackgroundColor(BaseColor.YELLOW); table.addCell(totalCell); preface.add(table); addEmptyLine(preface, 3); preface.setAlignment(Element.ALIGN_CENTER); preface.add(new Paragraph(String.format("%60s", "PO Generated on: " + poDTO.getPodate()), subFont)); document.add(preface); 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-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "inline; filename=\"sample.PDF\""); response.setContentType("application/octet-stream"); try ( // write ByteArrayOutputStream to the ServletOutputStream OutputStream os = response.getOutputStream()) { baos.writeTo(os); os.flush(); } } catch (Exception e) { System.out.println("Error " + e.getMessage()); } }
From source file:servlets.POServlet.java
private PdfPCell GenerateBorderlessCell(String title, int colspan, int alignment) { PdfPCell cell = new PdfPCell(new Phrase(title)); cell.setColspan(colspan);/*from www. jav a 2 s . co m*/ cell.setBorder(0); cell.setHorizontalAlignment(alignment); return cell; }
From source file:sistema.Minuta.java
public void generarMinutaPDF() { Document document = new Document(); try {/*from ww w.j av a2 s .co m*/ String ruta = "C:\\Users\\Gerardo\\Documents\\Facultad 5E\\Programacin Distribuida\\Programas\\SistemaControl\\minutas\\"; PdfWriter.getInstance(document, new FileOutputStream(ruta + "Minuta_Reunion" + id_reunion + ".pdf")); document.open(); PdfPTable table = new PdfPTable(6); // 3 columns. PdfPCell fecha = new PdfPCell(new Paragraph("Fecha")); PdfPCell nReunion = new PdfPCell(new Paragraph("No. Reunin")); fecha.setColspan(3); nReunion.setColspan(3); table.addCell(fecha); table.addCell(nReunion); PdfPCell cFecha = new PdfPCell(new Paragraph(this.fecha)); PdfPCell cNReunion = new PdfPCell(new Paragraph(id_reunion)); cFecha.setColspan(3); cNReunion.setColspan(3); table.addCell(cFecha); table.addCell(cNReunion); PdfPCell asunto = new PdfPCell(new Paragraph("Asunto:")); PdfPCell cAsunto = new PdfPCell(new Paragraph(this.asunto)); cAsunto.setColspan(5); table.addCell(asunto); table.addCell(cAsunto); PdfPCell lugar = new PdfPCell(new Paragraph("Lugar:")); PdfPCell cLugar = new PdfPCell(new Paragraph(this.lugar)); cLugar.setColspan(5); table.addCell(lugar); table.addCell(cLugar); PdfPCell presidente = new PdfPCell(new Paragraph("Presidente:")); PdfPCell cPresidente = new PdfPCell(new Paragraph(this.presidente)); cPresidente.setColspan(5); table.addCell(presidente); table.addCell(cPresidente); PdfPCell secretario = new PdfPCell(new Paragraph("Secretario:")); PdfPCell cSecretario = new PdfPCell(new Paragraph(this.secretario)); cSecretario.setColspan(5); table.addCell(secretario); table.addCell(cSecretario); PdfPCell ordenDia = new PdfPCell(new Paragraph("Orden del da")); ordenDia.setColspan(6); table.addCell(ordenDia); PdfPCell cOrdenDia = new PdfPCell(new Paragraph(this.ordenDia)); cOrdenDia.setColspan(6); table.addCell(cOrdenDia); PdfPCell detalles = new PdfPCell(new Paragraph("Detalles de la reunin")); detalles.setColspan(6); table.addCell(detalles); PdfPCell cDetalles = new PdfPCell(new Paragraph(this.detalles)); cDetalles.setColspan(6); table.addCell(cDetalles); PdfPCell acuerdos = new PdfPCell(new Paragraph("Acuerdos")); acuerdos.setColspan(6); table.addCell(acuerdos); PdfPCell cAcuerdos = new PdfPCell(new Paragraph(this.acuerdos)); cAcuerdos.setColspan(6); table.addCell(cAcuerdos); PdfPCell proximaReunion = new PdfPCell(new Paragraph("Fecha de la prxima reunin")); PdfPCell cProximaReunion = new PdfPCell(new Paragraph("2015-11-30")); proximaReunion.setColspan(3); cProximaReunion.setColspan(3); table.addCell(proximaReunion); table.addCell(cProximaReunion); PdfPCell participantes = new PdfPCell(new Paragraph("Participantes")); participantes.setColspan(6); table.addCell(participantes); PdfPCell profesor = new PdfPCell(new Paragraph("Nombre del profesor")); PdfPCell asistencia = new PdfPCell(new Paragraph("Asistencia")); PdfPCell firma = new PdfPCell(new Paragraph("Firma")); profesor.setColspan(3); asistencia.setColspan(1); firma.setColspan(2); table.addCell(profesor); table.addCell(asistencia); table.addCell(firma); int i = 0; while (i < this.participantes.length) { PdfPCell nProfesor = new PdfPCell(new Paragraph(this.participantes[i])); PdfPCell nAsistencia = new PdfPCell(new Paragraph("Si")); PdfPCell nFirma = new PdfPCell(new Paragraph(" \n ")); nProfesor.setColspan(3); nAsistencia.setColspan(1); nFirma.setColspan(2); nProfesor.setRowspan(2); nAsistencia.setRowspan(2); nFirma.setRowspan(2); table.addCell(nProfesor); table.addCell(nAsistencia); table.addCell(nFirma); i++; } document.add(table); Paragraph pFirmas = new Paragraph(); pFirmas.setAlignment(Element.ALIGN_CENTER); Chunk firmas = new Chunk("Firmas"); pFirmas.add(firmas); document.add(pFirmas); PdfPTable tCargos = new PdfPTable(8); PdfPCell fPresidente = new PdfPCell(new Paragraph("Presidente")); PdfPCell fSecretario = new PdfPCell(new Paragraph("Secretario")); PdfPCell fespacio = new PdfPCell(new Paragraph(" ")); fPresidente.setColspan(3); fSecretario.setColspan(3); fPresidente.setHorizontalAlignment(Element.ALIGN_CENTER); fSecretario.setHorizontalAlignment(Element.ALIGN_CENTER); fPresidente.setBorder(Rectangle.NO_BORDER); fSecretario.setBorder(Rectangle.NO_BORDER); fespacio.setBorder(Rectangle.NO_BORDER); tCargos.addCell(fespacio); tCargos.addCell(fPresidente); tCargos.addCell(fSecretario); tCargos.addCell(fespacio); document.add(tCargos); PdfPTable tFirmas = new PdfPTable(8); PdfPCell firmaPresidente = new PdfPCell(new Paragraph("_____________________")); PdfPCell firmaSecretario = new PdfPCell(new Paragraph("______________________")); PdfPCell tespacio = new PdfPCell(new Paragraph(" ")); PdfPCell nombrePresidente = new PdfPCell(new Paragraph(this.presidente)); PdfPCell nombreSecretario = new PdfPCell(new Paragraph(this.secretario)); firmaPresidente.setColspan(3); firmaSecretario.setColspan(3); firmaPresidente.setRowspan(3); firmaSecretario.setRowspan(3); tespacio.setColspan(1); nombrePresidente.setColspan(3); nombreSecretario.setColspan(3); firmaPresidente.setHorizontalAlignment(Element.ALIGN_CENTER); firmaSecretario.setHorizontalAlignment(Element.ALIGN_CENTER); firmaPresidente.setVerticalAlignment(Element.ALIGN_BOTTOM); firmaSecretario.setVerticalAlignment(Element.ALIGN_BOTTOM); nombrePresidente.setHorizontalAlignment(Element.ALIGN_CENTER); nombreSecretario.setHorizontalAlignment(Element.ALIGN_CENTER); firmaPresidente.setBorder(Rectangle.NO_BORDER); firmaSecretario.setBorder(Rectangle.NO_BORDER); tespacio.setBorder(Rectangle.NO_BORDER); nombrePresidente.setBorder(Rectangle.NO_BORDER); nombreSecretario.setBorder(Rectangle.NO_BORDER); tFirmas.addCell(tespacio); tFirmas.addCell(firmaPresidente); tFirmas.addCell(firmaSecretario); tFirmas.addCell(tespacio); tFirmas.addCell(tespacio); tFirmas.addCell(tespacio); tFirmas.addCell(tespacio); tFirmas.addCell(tespacio); tFirmas.addCell(tespacio); tFirmas.addCell(nombrePresidente); tFirmas.addCell(nombreSecretario); tFirmas.addCell(tespacio); document.add(tFirmas); document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
From source file:src.servlets.ManageAdmin.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from ww w . j a v a 2 s .c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map m = request.getParameterMap(); if (m.containsKey("GetPDF")) { try { String Report = getServletContext().getRealPath("") + "admin\\PDF_Report.pdf"; FileOutputStream file = new FileOutputStream(Report); Document document = new Document(); document.addAuthor("K00140908"); PdfWriter.getInstance(document, file); ///////////////////////ADDING THE FILES TO PDF//////////////////// //Inserting Image in PDF String uploadPath = getServletContext().getRealPath("") + "images\\logo.gif"; Image img = Image.getInstance(uploadPath); img.scaleAbsolute(120f, 60f);// width,height of image in float // Inserting Title in PDF ORIGINAL // Font fontTitle=new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.WHITE); // Chunk title=new Chunk("PDF GENERATION in Java with iText", fontTitle); // title.setBackground(new BaseColor(255,102,0), 1f, 1f, 1f, 3f); // title.setLineHeight(30f); // title.setUnderline(BaseColor.BLACK,5f,0.5f,2f,0.5f,PdfContentByte.LINE_CAP_ROUND); Font fontTitle = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK); Chunk title = new Chunk("Lit Realty System Report", fontTitle); title.setLineHeight(30f); //Inserting Table in PDF PdfPTable table = new PdfPTable(3); table.setWidthPercentage(100); // Sets the width percentage that the table will occupy in the page table.setSpacingAfter(10f); table.setSpacingBefore(15f); table.setWidths(new float[] { 2f, 2f, 2f }); // Sets relative width of table Font fontHeader = new Font(Font.FontFamily.HELVETICA, 15, Font.BOLD, BaseColor.BLUE); PdfPCell headercell = new PdfPCell(new Phrase("Property Photo", fontHeader)); // Creates new cell in table headercell.setBackgroundColor(new BaseColor(230, 230, 243)); headercell.setPaddingBottom(5f); table.addCell(headercell); headercell = new PdfPCell(new Phrase("Property ID", fontHeader)); headercell.setBackgroundColor(new BaseColor(233, 233, 233)); headercell.setPaddingBottom(5f); table.addCell(headercell); headercell = new PdfPCell(new Phrase("Price", fontHeader)); headercell.setBackgroundColor(new BaseColor(233, 233, 233)); headercell.setPaddingBottom(5f); table.addCell(headercell); PdfPCell cell1 = new PdfPCell(img, false); table.addCell(cell1); table.addCell("134000"); table.addCell("213445"); table.addCell("134000"); //Inserting List com.itextpdf.text.List list = new com.itextpdf.text.List(true, 30); list.add(new ListItem("Example1")); list.add(new ListItem("Example2")); list.add(new ListItem("Example3")); //Adding elements into PDF Document document.open(); document.add(img); document.add(title); document.add(Chunk.NEWLINE); document.add(table); document.newPage(); document.add(new Chunk("List of Examples").setUnderline(+1f, -5f)); document.add(list); document.newPage(); document.add(new Chunk("List of Examples").setUnderline(+1f, -5f)); document.add(list); document.newPage(); document.add(new Chunk("List of Properts By Agent X").setUnderline(+1f, -5f)); //////////////////////GET Propertys From Entity/////////////// List<Properties> allPropertiesList = PropertiesDB.getAllProperties(); PdfPTable propertyTable = new PdfPTable(3); PdfPCell propertyHeadingcell1 = new PdfPCell(new Phrase("Photo")); PdfPCell propertyHeadingcell2 = new PdfPCell(new Phrase("Property ID")); PdfPCell propertyHeadingcell3 = new PdfPCell(new Phrase("Price")); propertyHeadingcell1.setBorder(Rectangle.NO_BORDER); propertyHeadingcell2.setBorder(Rectangle.NO_BORDER); propertyHeadingcell3.setBorder(Rectangle.NO_BORDER); propertyTable.addCell(propertyHeadingcell1); propertyTable.addCell(propertyHeadingcell2); propertyTable.addCell(propertyHeadingcell3); document.add(Chunk.NEWLINE); String uploadPathforPropertyPhoto = getServletContext().getRealPath("") + "images\\properties\\thumbnails\\"; Image propertyThumbnail; img.scaleAbsolute(120f, 60f);// width,height of image in float for (Properties anProperty : allPropertiesList) { propertyThumbnail = Image.getInstance(uploadPathforPropertyPhoto + anProperty.getPhoto()); PdfPCell propertycell1 = new PdfPCell(propertyThumbnail, false); propertycell1.setPaddingBottom(20); PdfPCell propertycell2 = new PdfPCell(new Phrase(anProperty.getListingNum().toString())); PdfPCell propertycell3 = new PdfPCell(new Phrase(anProperty.getPrice().toString())); propertycell1.setBorder(Rectangle.NO_BORDER); propertycell2.setBorder(Rectangle.NO_BORDER); propertycell3.setBorder(Rectangle.NO_BORDER); propertyTable.addCell(propertycell1); propertyTable.addCell(propertycell2); propertyTable.addCell(propertycell3); } document.add(Chunk.NEWLINE); document.add(propertyTable); //////////////////////GET Propertys From Entity/////////////// document.close(); file.close(); System.out.println("Pdf created successfully ! :)"); String filePath = Report; File downloadFile = new File(filePath); FileInputStream inStream = new FileInputStream(downloadFile); // if you want to use a relative path to context root: String relativePath = getServletContext().getRealPath(""); System.out.println("relativePath = " + relativePath); // obtains ServletContext ServletContext context = getServletContext(); // gets MIME type of the file String mimeType = context.getMimeType(filePath); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } System.out.println("MIME type: " + mimeType); // modifies response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // forces download String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // obtains response's output stream OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } inStream.close(); outStream.close(); ///////////////// processRequest(request, response); } catch (DocumentException ex) { Logger.getLogger(ManageAdmin.class.getName()).log(Level.SEVERE, null, ex); } } }