List of usage examples for com.itextpdf.text.pdf PdfPTable setSpacingAfter
public void setSpacingAfter(final float spacing)
From source file:control.ReportHandler.java
public void writeTotalEnrolledReport() throws DocumentException, FileNotFoundException { Document doc = new Document(); Calendar c = Calendar.getInstance(); String file = "" + c.get(Calendar.DAY_OF_MONTH) + "_" + (c.get(Calendar.MONTH) + 1) + "_" + c.get(Calendar.YEAR) + "_T_" + c.get(Calendar.HOUR_OF_DAY) + "_" + c.get(Calendar.MINUTE) + ".pdf"; PdfWriter.getInstance(doc, new FileOutputStream(new File(his.His.reportEnrolledDir + "/" + file))); doc.open();/*w w w. ja v a 2s . co m*/ PdfPTable totalTable = new PdfPTable(1); totalTable.setSpacingAfter(10f); PdfPTable tableP = new PdfPTable(4); PdfPTable tableGs = new PdfPTable(3); PdfPCell tableGsnameCell = new PdfPCell(new Phrase("Navn", columnFont)); tableGsnameCell.setBackgroundColor(BaseColor.BLACK); PdfPCell tableGsbirthCell = new PdfPCell(new Phrase("Fdselsdag", columnFont)); tableGsbirthCell.setBackgroundColor(BaseColor.BLACK); PdfPCell tableGsPersonCell = new PdfPCell(new Phrase("Person navn", columnFont)); tableGsPersonCell.setBackgroundColor(BaseColor.BLACK); tableGs.addCell(tableGsnameCell); tableGs.addCell(tableGsbirthCell); tableGs.addCell(tableGsPersonCell); PdfPCell tablePnameCell = new PdfPCell(new Phrase("Navn", columnFont)); tablePnameCell.setBackgroundColor(BaseColor.BLACK); PdfPCell tablePaddressCell = new PdfPCell(new Phrase("Adresse", columnFont)); tablePaddressCell.setBackgroundColor(BaseColor.BLACK); PdfPCell tablePenrollerCell = new PdfPCell(new Phrase("Indskriver", columnFont)); tablePenrollerCell.setBackgroundColor(BaseColor.BLACK); PdfPCell tablePtotalGuestsCell = new PdfPCell(new Phrase("Total gster", columnFont)); tablePtotalGuestsCell.setBackgroundColor(BaseColor.BLACK); tableP.addCell(tablePnameCell); tableP.addCell(tablePaddressCell); tableP.addCell(tablePenrollerCell); tableP.addCell(tablePtotalGuestsCell); HashSet<Enrollment> enA = enR.getEnrollments(); int totalCounter = 0; int totalCounter_NoHoene = 0; Iterator<Enrollment> enI = enA.iterator(); while (enI.hasNext()) { totalCounter++; Enrollment en = enI.next(); Person enP = en.getEnrolledPerson(); if (!enP.isHoene()) { totalCounter_NoHoene++; } String nameP = enP.getFirstname() + " " + enP.getMiddlename() + " " + enP.getLastname(); String addressP = enP.getAddress(); User enU = en.getEnrolledByUser(); String nameU = enU.getFirstname() + " " + enU.getMiddlename() + " " + enU.getLastname(); Set<Guest> enGs = en.getGuests(); String totalGs = String.valueOf(enGs.size()); totalCounter += enGs.size(); totalCounter_NoHoene += enGs.size(); PdfPCell namePCell = new PdfPCell(new Phrase(nameP)); PdfPCell birthPCell = new PdfPCell(new Phrase(addressP)); PdfPCell nameUCell = new PdfPCell(new Phrase(nameU)); PdfPCell totalGsCell = new PdfPCell(new Phrase(totalGs)); tableP.addCell(namePCell); tableP.addCell(birthPCell); tableP.addCell(nameUCell); tableP.addCell(totalGsCell); Iterator<Guest> enGsI = enGs.iterator(); while (enGsI.hasNext()) { Guest g = enGsI.next(); String nameG = g.getFirstname() + " " + g.getMiddlename() + " " + g.getLastname(); PdfPCell nameGCell = new PdfPCell(new Phrase(nameG)); PdfPCell birthGCell = new PdfPCell(new Phrase(g.getBirthdayDate())); PdfPCell personGCell = new PdfPCell(new Phrase(nameP)); tableGs.addCell(nameGCell); tableGs.addCell(birthGCell); tableGs.addCell(personGCell); } } PdfPCell totalCell = new PdfPCell(new Phrase("Total indskrevne: " + totalCounter)); totalTable.addCell(totalCell); PdfPCell totalNoHoeneCell = new PdfPCell( new Phrase("Total indskrevne uden hner: " + totalCounter_NoHoene)); totalTable.addCell(totalNoHoeneCell); doc.add(new Phrase("Personer")); doc.add(tableP); doc.add(totalTable); doc.add(new Phrase("Gster")); doc.add(tableGs); doc.close(); }
From source file:Controller.ControllerCompra.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www . j a v a2s . 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("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 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("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.CreateTranscript.java
private void CreateTranscript(MyPerson p) {//,PrintWriter out){ Document document = new Document(); String name = p.getFName() + p.getLName(); try {/*from w w w .jav a 2s .c o 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:cz.zcu.kiv.eegdatabase.logic.pdf.ReservationPDF.java
License:Apache License
public static PdfPTable formatReservation(Reservation reservation) { int padding = 5; GregorianCalendar created = new GregorianCalendar(); created.setTime(reservation.getCreationTime()); GregorianCalendar startTime = new GregorianCalendar(); startTime.setTime(reservation.getStartTime()); GregorianCalendar endTime = new GregorianCalendar(); endTime.setTime(reservation.getEndTime()); String personName = BookingRoomUtils.formatPersonName(reservation.getPerson()); Font title = FontFactory.getFont("Trebuchet MS", "utf-8", 15, Font.BOLD, new BaseColor(59, 70, 00)); Font header = FontFactory.getFont(FontFactory.TIMES_BOLD, 13, Font.BOLD, BaseColor.BLACK); Font value = FontFactory.getFont(FontFactory.TIMES, 13); PdfPTable table = new PdfPTable(2); PdfPCell cell;/* w w w. jav a 2 s. c o m*/ Phrase phrase; phrase = new Phrase("Reservation by " + personName); phrase.setFont(title); cell = new PdfPCell(phrase); cell.setColspan(2); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorderWidthTop(1); cell.setBorderWidthLeft(1); cell.setBorderWidthRight(1); cell.setPadding(padding); cell.setPaddingBottom(5); table.addCell(cell); phrase = new Phrase("Date: "); phrase.setFont(header); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorder(0); cell.setBorderWidthLeft(1); cell.setPadding(padding); table.addCell(cell); phrase = new Phrase(BookingRoomUtils.getDate(startTime)); phrase.setFont(value); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorder(0); cell.setBorderWidthRight(1); cell.setPadding(padding); table.addCell(cell); phrase = new Phrase("Start: "); phrase.setFont(header); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorder(0); cell.setBorderWidthLeft(1); cell.setPadding(padding); table.addCell(cell); phrase = new Phrase(BookingRoomUtils.getHoursAndMinutes(startTime)); phrase.setFont(value); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorder(0); cell.setBorderWidthRight(1); cell.setPadding(padding); table.addCell(cell); phrase = new Phrase("End: "); phrase.setFont(header); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorder(0); cell.setBorderWidthLeft(1); cell.setBorderWidthBottom(1); cell.setPadding(padding); table.addCell(cell); phrase = new Phrase(BookingRoomUtils.getHoursAndMinutes(endTime)); phrase.setFont(value); cell = new PdfPCell(phrase); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorder(0); cell.setBorderWidthRight(1); cell.setBorderWidthBottom(1); cell.setPadding(padding); table.addCell(cell); table.setSpacingBefore(10); table.setSpacingAfter(10); return table; }
From source file:dbms_prj.Display.java
public void create_pdf() throws Exception { Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream(S1 + ".pdf")); Image image = Image.getInstance("src/Travel partners.png"); image.scaleAbsolute(500f, 200f);//from w ww . j a v a 2 s. co m Image ima = Image.getInstance("src/images.jpg"); ima.scaleAbsolute(100f, 100f); ima.setAlignment(Element.ALIGN_CENTER); PdfPTable table = new PdfPTable(9); PdfPCell cell = new PdfPCell(new Paragraph("Ticket")); cell.setColspan(9); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setPadding(10.0f); cell.setBackgroundColor(new BaseColor(140, 221, 8)); table.addCell(cell); table.addCell("PNR"); table.addCell("BOOK_ID"); table.addCell("FLIGHT_NO"); table.addCell("NAME"); table.addCell("SOURCE"); table.addCell("DESTINATION"); table.addCell("STATUS"); table.addCell("FARE"); table.addCell("Date"); table.addCell(S1); table.addCell(S11); table.addCell(S4); table.addCell(S6 + " " + S7); table.addCell(S8); table.addCell(S9); table.addCell(S5); table.addCell(S10); table.addCell(S12); table.setSpacingBefore(30.0f); // Space Before table starts, like margin-top in CSS table.setSpacingAfter(30.0f); doc.open(); //doc.add(new Paragraph("Hello!! Yo this is my first pdf!")); doc.add(image); doc.add(new Paragraph("Ticket created on " + new Date().toString())); doc.add(table); //doc.add(list); doc.add(ima); doc.close(); }
From source file:dbms_prj.Status.java
public void create_pdf() throws Exception { Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream(S1 + ".pdf")); Image image = Image.getInstance("src/Travel partners.png"); image.scaleAbsolute(500f, 200f);//from www . j a v a 2s . co m Image ima = Image.getInstance("src/images.jpg"); ima.scaleAbsolute(100f, 100f); ima.setAlignment(Element.ALIGN_CENTER); PdfPTable table = new PdfPTable(9); PdfPCell cell = new PdfPCell(new Paragraph("Ticket")); cell.setColspan(9); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setPadding(10.0f); table.setTotalWidth(300.0f); cell.setBackgroundColor(new BaseColor(140, 221, 8)); table.addCell(cell); table.addCell("PNR"); table.addCell("BOOK_ID"); table.addCell("FLIGHT_NO"); table.addCell("NAME"); table.addCell("SOURCE"); table.addCell("DESTINATION"); table.addCell("STATUS"); table.addCell("FARE"); table.addCell("Date"); table.addCell(S1); table.addCell(S11); table.addCell(S4); table.addCell(S6 + S7); table.addCell(S8); table.addCell(S9); table.addCell(S5); table.addCell(S10); table.addCell(S2); table.setSpacingBefore(50.0f); // Space Before table starts, like margin-top in CSS table.setSpacingAfter(50.0f); doc.open(); //doc.add(new Paragraph("Hello!! Yo this is my first pdf!")); doc.add(image); //doc.add(new Paragraph("Ticket created on " + new Date().toString())); doc.add(table); //doc.add(list); doc.add(ima); doc.close(); }
From source file:de.fau.osr.util.matrix.MatrixTools.java
License:Open Source License
/** * /**// w w w.ja va2 s .c o m * saves matrix to {@code path} in pdf format * @param matrix matrix to save * @param path file where matrix will be saved */ public static boolean SaveMatrixToPdf(RequirementsTraceabilityMatrixByImpact matrix, File path, String matrixTitle) { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(path)); document.open(); document.addTitle(matrixTitle); Paragraph headerPar = new Paragraph("Traceability Matrix"); headerPar.add(new Paragraph(" ")); //new line document.add(headerPar); java.util.List<String> reqs = matrix.getRequirements(); //table setup PdfPTable table = new PdfPTable(reqs.size() + 1); //reqs + "file name" col table.setHeaderRows(1); table.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); table.setWidthPercentage(100); table.setSpacingBefore(0); table.setSpacingAfter(0); //file name col width/req col width 4:1 float[] widths = new float[reqs.size() + 1]; widths[0] = 4; for (int i = 0; i < reqs.size(); i++) { widths[i + 1] = 1; } table.setWidths(widths); //header row //add filename col to header addCell(table, "File name", 10, Element.ALIGN_LEFT); //add req cols to header for (String req : reqs) { addCell(table, "req-" + req, 8, Element.ALIGN_CENTER); } //content, row by row: for (int i = 0; i < matrix.getFiles().size(); i++) { //filename col String fileName = matrix.getFiles().get(i); addCell(table, fileName, 5, Element.ALIGN_LEFT, 18); //impact value cols for (String req : reqs) { RequirementFileImpactValue value = matrix .getImpactValue(new RequirementFilePair(req, fileName)); if (value == null) { value = new RequirementFileImpactValue(0); } //round DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); String valString = df.format(value.getImpactPercentage()); addCell(table, valString, 10, Element.ALIGN_CENTER); } } document.add(table); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); return false; } finally { document.close(); } return true; }
From source file:documentos.PlanillaServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .ja v a2s . 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, SQLException { response.setContentType("application/pdf"); Connection conexion = null; HttpSession session = request.getSession(true); try { conexion = ds.getConnection(); edificioDAO edifDAO = new edificioDAO(); edifDAO.setConexion(conexion); usuarioDAO usuDAO = new usuarioDAO(); usuDAO.setConexion(conexion); //obtener variable boolean error = false; String idString = (String) request.getParameter("id_edificio"); int idEdificio = 0; try { idEdificio = Integer.parseInt(idString); } catch (Exception ex) { System.out.println("Error al convertir variables :" + ex); error = true; } //obtener datos de edificio segun el id edificio edif = new edificio(); edif = edifDAO.findbyIdEdificio(idEdificio); DetalleEdificioDAO detEdifDAO = new DetalleEdificioDAO(); detEdifDAO.setConexion(conexion); administradorDAO adminDAO = new administradorDAO(); adminDAO.setConexion(conexion); //obtener admin Edificio administrador admin = new administrador(); admin = adminDAO.findbyIdEdificio(idEdificio); //obtener datos de detalleEdif detalleEdificio detalleEdif = new detalleEdificio(); detalleEdif = detEdifDAO.findbyIdEdificio(idEdificio); //obtener datos de usuario segun id edificio usuario usuario = new usuario(); usuario = usuDAO.findbyIdUsuarios(edif.getIdUsuario()); //guardar datos de edif en variables separadas String nombreVendedor = usuario.getNombre(); String apellidoVendedor = usuario.getApellido(); int annoNorma = edif.getAnoEdificio(); String ubicacionMed = detalleEdif.getUbicacionMedidores(); String ciige = detalleEdif.getCiigeAnterior(); String testDePruebas = detalleEdif.getDespiche(); String nombreEdif = edif.getNombreEdificio(); String correo = admin.getEmailAdmin(); String fonoAdmin = admin.getTelefonoAdmin(); String fonoEdif = edif.getTelefonoEdificio(); String rutEdif = edif.getRutEdificio(); String dirEdif = edif.getDireccionEdificio(); String nomAdmin = admin.getNombreAdmin(); String rutAdmin = admin.getRutAdmin(); int cantidadDe = edif.getCantCasas() + edif.getCantDepartamentos() + edif.getCantLocales() + edif.getCantLavanderias(); int cantPisos = edif.getCantPisos(); int idEmpresaGas = edif.getIdGas(); //determinar el nombre de la empresa de gas segun su id String empresagas = ""; if (idEmpresaGas == 1) { empresagas = "GASVALPO"; } if (idEmpresaGas == 2) { empresagas = "LIPIGAS"; } if (idEmpresaGas == 3) { empresagas = "ABASTIBLE"; } if (idEmpresaGas == 4) { empresagas = "GASCO"; } if (idEmpresaGas == 5) { empresagas = "OTROS"; } int annoEdif = edif.getAnoEdificio(); int potencia = edif.getPotenciaReal(); int cantidaConductos = edif.getCantConductos(); int cantidadCalderas = edif.getCantCalderas(); //Crear documento Document document = new Document(); Image logo = Image.getInstance(getClass().getResource("logo.png")); PdfWriter.getInstance(document, response.getOutputStream()); Font fuenteNegrita = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD); Font fuenteNormal = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL); Font fuenteEPiePagina = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.BOLD); Font fuentePiePagina = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD); // step 3 document.open(); // step 4 logo.setAbsolutePosition(270f, 750f); logo.scalePercent(65f); PdfPTable tablaEncabezado = new PdfPTable(2); PdfPTable tablaContenido = new PdfPTable(2); tablaEncabezado.addCell(new Paragraph("PLANILLA CIIG-e INSPECCIN PERIODICA")); tablaEncabezado.addCell(logo); tablaContenido.setSpacingBefore(15); tablaContenido.setSpacingAfter(20); tablaContenido.addCell(new Paragraph("VENDEDORA", fuenteNormal)); tablaContenido.addCell(new Paragraph(nombreVendedor + " " + apellidoVendedor, fuenteNormal)); tablaContenido.addCell(new Paragraph("AO DEL EDIFICIO Y NORMA APLICAR", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(annoEdif), fuenteNormal)); tablaContenido .addCell(new Paragraph("UBICACIN MEDIDORES: EN LOS PISOS, FUERA DEL EDIFICO", fuenteNormal)); tablaContenido.addCell(new Paragraph(ubicacionMed, fuenteNormal)); tablaContenido .addCell(new Paragraph("NRO CIIGE DE LA INSPECCION ANTERIOR (VER PAGINA SEC)", fuenteNormal)); tablaContenido.addCell(new Paragraph(ciige, fuenteNormal)); tablaContenido.addCell(new Paragraph("T DE PRUEBAS, DESPICHE OTRO (COCINA)", fuenteNormal)); tablaContenido.addCell(new Paragraph(testDePruebas, fuenteNormal)); tablaContenido.addCell(new Paragraph("NOMBRE: EDIFICIO, CONDOMINIO, PROPIETARIO, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(nombreEdif, fuenteNormal)); tablaContenido.addCell(new Paragraph("CORREO ELECTRONICO", fuenteNormal)); tablaContenido.addCell(new Paragraph(correo, fuenteNormal)); tablaContenido.addCell(new Paragraph("FONO ADMINISTRADOR /FONO EDIFICIO", fuenteNormal)); tablaContenido.addCell(new Paragraph("Fono Administrador :" + fonoAdmin + " Fono Edificio :" + fonoEdif, fuenteNormal)); tablaContenido.addCell(new Paragraph("R.U.T EDIFICIO, CONDOMINIO, PROPIETARIOS, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(rutEdif, fuenteNormal)); tablaContenido.addCell(new Paragraph("DIRECCIN DEL EDIFICO", fuenteNormal)); tablaContenido.addCell(new Paragraph(dirEdif, fuenteNormal)); tablaContenido.addCell(new Paragraph("NOMBRE ADMINISTRADOR, PROPIETARIO, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(nomAdmin, fuenteNormal)); tablaContenido.addCell(new Paragraph("RUT: ADMINISTRADOR, PROPIETARIO, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(rutAdmin, fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE: DEPTOS, CASAS, LOCALES, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantidadDe), fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE PISOS INMUEBLE", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantPisos), fuenteNormal)); tablaContenido.addCell(new Paragraph("EMPRESA DISTRIBUIDORA DE GAS", fuenteNormal)); tablaContenido.addCell(new Paragraph(empresagas, fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE INSTALACIONES", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantidadDe), fuenteNormal)); tablaContenido.addCell(new Paragraph("TIPO DE ARTEFACTOS INSTALADOS", fuenteNormal)); tablaContenido.addCell(new Paragraph("", fuenteNormal)); tablaContenido.addCell(new Paragraph("POTENCIA TOTAL INSTALADA", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(potencia), fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE CONDUCTOS COLECTIVOS", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantidaConductos), fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE CALDERAS CENTRALES", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantidadCalderas), fuenteNormal)); document.add(tablaEncabezado); document.add(tablaContenido); Paragraph textoIng = new Paragraph("IngeneriaRSLimitada", fuenteEPiePagina); textoIng.setAlignment(Element.ALIGN_CENTER); Paragraph textPie = new Paragraph( "Calle Montaa 754 Oficina 37-A Via Del Mar / ingenieria.sr@gmail.com - Fono 032-2697175 / 92564059", fuentePiePagina); textPie.setAlignment(Element.ALIGN_CENTER); document.add(textoIng); document.add(textPie); document.close(); } catch (DocumentException de) { throw new IOException(de.getMessage()); } }
From source file:eeebees.PDFGen.java
public static void main(String[] args) { try {//from www.j av a 2s .c om OutputStream file = new FileOutputStream(new File("D:\\PDF_Java4s.pdf")); Document document = new Document(); PdfWriter.getInstance(document, file); //Inserting Image in PDF //Image image = Image.getInstance ("src/pdf/java4s.png"); //image.scaleAbsolute(120f, 60f);//image width,height //Inserting Table in PDF PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Paragraph("Java4s.com")); cell.setColspan(3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setPadding(10.0f); cell.setBackgroundColor(new BaseColor(140, 221, 8)); table.addCell(cell); table.addCell("Name"); table.addCell("Address"); table.addCell("Country"); table.addCell("Java4s"); table.addCell("NC"); table.addCell("United States"); table.setSpacingBefore(30.0f); // Space Before table starts, like margin-top in CSS table.setSpacingAfter(30.0f); // Space After table starts, like margin-Bottom in CSS //Inserting List in PDF List list = new List(true, 30); list.add(new ListItem("Java4s")); list.add(new ListItem("Php4s")); list.add(new ListItem("Some Thing...")); //Text formating in PDF Chunk chunk = new Chunk("Welecome To Java4s Programming Blog..."); chunk.setUnderline(+1f, -2f);//1st co-ordinate is for line width,2nd is space between Chunk chunk1 = new Chunk("Php4s.com"); chunk1.setUnderline(+4f, -8f); chunk1.setBackground(new BaseColor(17, 46, 193)); //Now Insert Every Thing Into PDF Document document.open();//PDF document opened........ //document.add(image); document.add(Chunk.NEWLINE); //Something like in HTML :-) document.add(new Paragraph("Dear Java4s.com")); document.add(new Paragraph("Document Generated On - " + new Date().toString())); document.add(table); document.add(chunk); document.add(chunk1); document.add(Chunk.NEWLINE); //Something like in HTML :-) document.newPage(); //Opened new page document.add(list); //In the new page we are going to add list document.close(); file.close(); System.out.println("Pdf created successfully.."); } catch (Exception e) { e.printStackTrace(); } }