List of usage examples for com.itextpdf.text Document close
boolean close
To view the source code for com.itextpdf.text Document close.
Click Source Link
From source file:com.miraflorescarwash.controller.PdfController.java
private void crearPdfClientesFreq(Document doc, List<ClienteReporte> reporteCompras, PdfWriter writer) { Paragraph parrafo;//from w w w . jav a2 s. com PdfPTable tabla; String txt; PdfPCell cell; Phrase frase; String fuente; JFreeChart chart; int i, w, h; fuente = "arial"; if (reporteCompras.isEmpty()) { return; } try { // // Se abre el documento. doc.open(); txt = "Miraflores Car Wash"; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 10, Font.BOLD, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); txt = "Clientes Frecuentes"; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 30, Font.BOLD, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_CENTER); doc.add(parrafo); LineSeparator ls = new LineSeparator(); doc.add(new Chunk(ls)); doc.add(Chunk.NEWLINE); tabla = new PdfPTable(3); frase = new Phrase("Id", FontFactory.getFont(fuente, 12, Font.BOLD, BaseColor.WHITE)); cell = new PdfPCell(frase); cell.setBackgroundColor(BaseColor.RED); tabla.addCell(cell); frase = new Phrase("Nombre", FontFactory.getFont(fuente, 12, Font.BOLD, BaseColor.WHITE)); cell = new PdfPCell(frase); cell.setBackgroundColor(BaseColor.RED); tabla.addCell(cell); frase = new Phrase("Dinero", FontFactory.getFont(fuente, 12, Font.BOLD, BaseColor.WHITE)); cell = new PdfPCell(frase); cell.setBackgroundColor(BaseColor.RED); tabla.addCell(cell); i = 1; for (ClienteReporte clienteReporte : reporteCompras) { if (i % 2 == 0) { cell = new PdfPCell(); cell.setBackgroundColor(new BaseColor(244, 119, 119)); frase = new Phrase(clienteReporte.getId() + ""); cell.setPhrase(frase); tabla.addCell(cell); frase = new Phrase(clienteReporte.getApellido() + " " + clienteReporte.getNombre()); cell.setPhrase(frase); tabla.addCell(cell); frase = new Phrase("S/. " + clienteReporte.getTotal() + "0"); cell.setPhrase(frase); tabla.addCell(cell); } else { tabla.addCell(clienteReporte.getId() + ""); tabla.addCell(clienteReporte.getApellido() + " " + clienteReporte.getNombre()); tabla.addCell("S/. " + clienteReporte.getTotal() + "0"); } i++; } doc.add(tabla); doc.newPage(); txt = "Miraflores Car Wash"; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 10, Font.BOLD, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); chart = clienteService.generarChartReporte(reporteCompras); w = 500; h = 500; PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2d = tp.createGraphics(w, h, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, w, h); chart.draw(g2d, r2d); cb.addTemplate(tp, 50, 250); g2d.dispose(); doc.close(); } catch (DocumentException ex) { } }
From source file:com.miraflorescarwash.controller.PdfController.java
private void crearPdfClientesEvolucion(Document doc, List<ClienteReporte> reporteCompras, PdfWriter writer) { Paragraph parrafo;/*from w w w . j a v a 2 s. c o m*/ PdfPTable tabla; String txt; PdfPCell cell; Phrase frase; String fuente; JFreeChart chart; ClienteReporte cliente; int i, w, h; fuente = "arial"; if (reporteCompras.isEmpty()) { return; } try { // cliente = reporteCompras.get(0); // Se abre el documento. doc.open(); txt = "Miraflores Car Wash"; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 10, Font.BOLD, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); txt = "Evolucin de Clientes "; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 30, Font.BOLD, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_CENTER); doc.add(parrafo); LineSeparator ls = new LineSeparator(); doc.add(new Chunk(ls)); txt = "Id: "; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 14, Font.BOLD, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); txt = cliente.getId() + ""; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 14, Font.NORMAL, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); // doc.add(Chunk.NEWLINE); txt = "Nombres: "; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 14, Font.BOLD, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); txt = cliente.getNombre(); parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 14, Font.NORMAL, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); // doc.add(Chunk.NEWLINE); txt = "Apellidos: "; parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 14, Font.BOLD, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); txt = cliente.getApellido(); parrafo = new Paragraph(txt, FontFactory.getFont(fuente, 14, Font.NORMAL, BaseColor.BLACK)); parrafo.setAlignment(Element.ALIGN_LEFT); doc.add(parrafo); // doc.add(Chunk.NEWLINE); chart = clienteService.generarChartReporteMes(reporteCompras); w = 500; h = 500; PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2d = tp.createGraphics(w, h, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, w, h); chart.draw(g2d, r2d); cb.addTemplate(tp, 50, 50); g2d.dispose(); doc.close(); } catch (DocumentException ex) { } }
From source file:com.mobicage.rogerthat.enterprise.samples.hr.bizz.GenerateExpenseNote.java
License:Open Source License
public int handle(final User user, final User manager, final ExpenseNote en) throws MalformedURLException, IOException, DocumentException { log.info("Building list of expenses ..."); List<Expense> expenses = Expense.list(en); log.info("Retrieved " + expenses.size() + " expenses from the datastore"); log.info("Creating ExpenseNoteDocOutputStream"); ExpenseNoteDocOutputStream stream = new ExpenseNoteDocOutputStream(en); Document document = new Document(); PdfWriter.getInstance(document, stream); document.open();/*from w w w.j a v a 2 s.co m*/ document.addTitle("Expense note " + en.id + " of " + user.name); document.addSubject("Expense note generated by Rogerthat Enterprise!"); document.addKeywords("expense note"); document.addAuthor(user.name); document.addCreator("Rogerthat OneApp Enterprise Mobility"); Paragraph preface = new Paragraph(); preface.add(new Paragraph("TP Vision expense note", titleFont)); preface.add(new Paragraph(" ")); DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy"); Date date = new Date(); preface.add(new Paragraph("Date: " + dateFormat.format(date))); preface.add(new Paragraph("Requestor: " + user.name)); preface.add(new Paragraph("Approver: " + manager.name)); preface.add(new Paragraph(" ")); PdfPTable table = new PdfPTable(7); table.setWidthPercentage(110); table.setWidths(new int[] { 5, 15, 15, 35, 10, 15, 10 }); addHeader(table, "Id"); addHeader(table, "Date"); addHeader(table, "Nature"); addHeader(table, "Description"); addHeader(table, "Account"); addHeader(table, "Amount"); addHeader(table, "Voucher"); table.setHeaderRows(1); Collections.sort(expenses, new Comparator<Expense>() { @Override public int compare(Expense e1, Expense e2) { return (int) (e1.date - e2.date); } }); int i = 0; double total = 0; for (Expense expense : expenses) { PdfPCell c1 = new PdfPCell(new Phrase("" + ++i)); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); table.addCell(dateFormat.format(new Date(expense.date * 1000))); table.addCell(expense.nature); table.addCell(expense.description); table.addCell("" + expense.account); c1 = new PdfPCell(new Phrase(DECIMAL_FORMAT.format(expense.amount) + " " + expense.currency)); c1.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(c1); table.addCell(expense.voucher); total += expense.amount; } preface.add(table); preface.add(new Paragraph(" ")); preface.add(new Paragraph("Total: " + DECIMAL_FORMAT.format(total), titleFont)); document.add(preface); i = 0; for (Expense expense : expenses) { i++; if (expense.receipt == null) continue; document.newPage(); Paragraph receipt = new Paragraph(); receipt.add(new Paragraph("Attachment " + i, titleFont)); document.add(receipt); Image image = Image.getInstance(new URL(expense.receipt)); image.setRotationDegrees(-90); float scaler = (document.getPageSize().getWidth() / image.getWidth()) * 100; image.scalePercent(scaler); document.add(image); } document.close(); stream.close(); return stream.getSize(); }
From source file:com.mstoyanov.music_lessons.pdf.CreatePDF.java
License:Open Source License
public boolean exportPDF() { // Checks if external storage is available: if (!isExternalStorageWritable()) { Toast.makeText(context, "External storage not accessible!", Toast.LENGTH_SHORT).show(); return false; }//w w w . ja va2s . c om // Get the path to the user's public downloads directory: String fileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/Schedule.pdf"; try { Document document = new Document(PageSize.LETTER.rotate()); PdfWriter.getInstance(document, new FileOutputStream(fileName)); // Create a new letter sized document in landscape mode: document.setPageSize(PageSize.LETTER.rotate()); document.setMargins(72, 36, 36, 36); document.open(); addMetaData(document); addContent(document); document.close(); } catch (Exception e) { e.printStackTrace(); } Toast.makeText(context, "Schedule exported to external storage/Download", Toast.LENGTH_LONG).show(); return true; }
From source file:com.mx.ipn.clases.PDF.java
public void crearpdf(String nombre, String appat, String apmat) throws FileNotFoundException, DocumentException { // Creacion del documento con los margenes // Creacion del documento con los margenes Document document = new Document(PageSize.A4, 35, 30, 50, 50); try {/*w w w. j a v a 2 s .c o m*/ // El archivo pdf que vamos a generar FileOutputStream fileOutputStream = new FileOutputStream("AvisoPrivacidad.pdf"); // Obtener la instancia del PdfWriter PdfWriter.getInstance(document, fileOutputStream); // Abrir el documento document.open(); // Crear las fuentes para el contenido y los titulos Font fontContenido = FontFactory.getFont(FontFactory.TIMES_ROMAN.toString(), 9, Font.NORMAL, BaseColor.DARK_GRAY); Font fontTitulos = FontFactory.getFont(FontFactory.TIMES_BOLD, 11, Font.UNDERLINE, BaseColor.DARK_GRAY); Font nomb = FontFactory.getFont(FontFactory.TIMES_BOLD, 9, Font.NORMAL, BaseColor.DARK_GRAY); // Creacion del parrafo Paragraph paragraph = new Paragraph(); // Agregar un titulo con su respectiva fuente paragraph.add(new Phrase("Aviso de Privacidad", fontTitulos)); paragraph.setAlignment(Element.ALIGN_CENTER); // Agregar saltos de linea paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); // Agregar contenido con su respectiva fuente paragraph.add(new Phrase( "Con fundamento en los artculos 15, 16 y de acuerdo a lo Previsto en la Ley Federal de Proteccin de Datos" + "Personales, hacemos de su conocimiento que ZERCHERS, S.A. de C.V., es una empresa legalmente" + "constituido de conformidad con las leyes mexicanas, con domicilio en Av. Juan de Dios Btiz s/n, Gustavo" + "A. Madero, Nueva Industrial Vallejo, 07700 Ciudad de Mxico; y como responsable del tratamiento de sus" + "datos personales, del uso que se le d a los mismos y de su proteccin. Hace de su conocimiento que la" + "informacin de nuestros clientes es tratada de forma estrictamente confidencial por lo que, al proporcionar" + "sus datos personales. Estos sern utilizados nica y exclusivamente para los siguientes fines: " + "Proveer los servicios y productos que ha solicitado; notificarle sobre nuevos servicios o productos que" + "tengan relacin con los ya contratados o adquiridos; comunicarle sobre cambios en los mismos; evaluar la" + "calidad de los servicios que brindamos; mantener actualizada nuestra base de datos con sus datos" + "recientes y en general, para dar cumplimiento a las obligaciones que hemos contrado con usted.", fontContenido)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase( " Para las finalidades antes mencionadas, requerimos obtener los siguientes datos personales:", fontContenido)); paragraph.setAlignment(Element.ALIGN_JUSTIFIED); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); // Agregar el parrafo al documento document.add(paragraph); document.add(Tabla_Simple()); paragraph = new Paragraph(); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase( "Para prevenir el acceso no autorizado a sus datos personales y con el fin de asegurar que la informacin sea " + "utilizada para los fines establecidos en este aviso de privacidad, hemos establecido diversos procedimientos" + " con la finalidad de evitar el uso o divulgacin no autorizados de sus datos, permitindonos tratarlos debidamente." + " As mismo, le informamos que sus datos personales pueden ser Transmitidos para ser tratados por personas " + "distintas a esta empresa. Todos sus datos personales son tratados de acuerdo a la legislacin aplicable y " + "vigente en el pas, por ello le informamos que usted tiene en todo momento los derechos (ARCO) de acceder, " + "rectificar, cancelar u oponerse al tratamiento que le damos a sus datos personales; derecho que podr " + "hacer valer a travs del ?rea de Privacidad encargada de la seguridad de datos personales en el " + "Telfono 5729 6000.", fontContenido)); paragraph.setAlignment(Element.ALIGN_JUSTIFIED); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase( " A travs de estos canales usted podr actualizar sus datos y especificar el medio por el cual desea recibir " + "informacin, ya que en caso de no contar con esta especificacin de su parte, ZERCHERS, S.A. de C.V., " + "establecer libremente el canal que considere pertinente para enviarle informacin. Este aviso de" + " privacidad podr ser modificado por ZERCHERS, S.A. de C.V., dichas modificaciones sern oportunamente " + "informadas a travs de correo electrnico, telfono, pgina web o cualquier otro medio de comunicacin" + " que ZERCHERS, S.A. de C.V., determine para tal efecto.", fontContenido)); paragraph.setAlignment(Element.ALIGN_JUSTIFIED); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(" ATENTAMENTE", nomb)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(" Direccin General TT/SisPLD", nomb)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(" Consiento que mis datos personales sensibles sean tratados conforme a" + "los trminos y condiciones del presente aviso de privacidad.", fontContenido)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase("Nombre: " + nombre + " " + appat + " " + apmat, nomb)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase("____________________________________", fontContenido)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(Chunk.NEWLINE)); paragraph.add(new Phrase(" ltima Fecha de Emisin: Mayo 13, 2016", fontContenido)); document.add(paragraph); // Cerrar el documento document.close(); // Abrir el archivo File file = new File("AvisoPrivacidad.pdf"); Desktop.getDesktop().open(file); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.myapp.struts.transaction.transactionAction.java
public ActionForward generatememberreport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws SQLException, Exception { if (Constants.isSessionActive(request)) { transactionForm transactionForm = (transactionForm) form; try {/*from w w w.j a va 2 s. co m*/ Date utilDate = new Date(); java.sql.Date date = new java.sql.Date(utilDate.getTime()); Font bigFont = FontFactory.getFont(FontFactory.HELVETICA, "Windows-1254", 12, Font.BOLD, BaseColor.BLACK); Font bigFont_Uderline = FontFactory.getFont(FontFactory.HELVETICA, "Windows-1254", 12, Font.BOLD | Font.UNDERLINE, BaseColor.BLACK); Font boldfont = FontFactory.getFont(FontFactory.HELVETICA, "Windows-1254", 9, Font.BOLD); Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); //Or whatever format fits best your needs. Paragraph para1 = new Paragraph("PALKE JEWELLERS", bigFont); para1.setAlignment(Element.ALIGN_CENTER); document.add(para1); para1 = new Paragraph("MEMBER ACCOUNT DETAILS", bigFont); para1.setAlignment(Element.ALIGN_CENTER); document.add(para1); para1 = new Paragraph(transactionForm.getSelectedmember(), boldfont); para1.setAlignment(Element.ALIGN_LEFT); document.add(para1); para1 = new Paragraph( transactionForm.getMemberaddress() + "\n" + transactionForm.getMembercontactno(), boldfont); para1.setAlignment(Element.ALIGN_LEFT); document.add(para1); Groups obj = (Groups) hmGroups.get(transactionForm.getGroupid() + ""); if (obj != null) { para1 = new Paragraph("Group : " + obj.getGroupname(), font); para1.setAlignment(Element.ALIGN_LEFT); document.add(para1); para1 = new Paragraph("Paid Amount : " + transactionForm.getTotalpaidamount(), font); para1.setAlignment(Element.ALIGN_LEFT); document.add(para1); para1 = new Paragraph("Prize Amount : " + transactionForm.getDrawamount(), font); para1.setAlignment(Element.ALIGN_LEFT); document.add(para1); para1 = new Paragraph("Total Amount : " + transactionForm.getTotalamount(), boldfont); para1.setAlignment(Element.ALIGN_LEFT); document.add(para1); para1 = new Paragraph("Status : " + transactionForm.getStatus(), boldfont); para1.setAlignment(Element.ALIGN_RIGHT); document.add(para1); if (transactionForm.getStatus().equalsIgnoreCase("Settled")) { para1 = new Paragraph(transactionForm.getSettlementcomment(), boldfont); para1.setAlignment(Element.ALIGN_RIGHT); document.add(para1); } String dateStr = sdf.format(date); para1 = new Paragraph("DATED:" + dateStr, font); para1.setAlignment(Element.ALIGN_RIGHT); document.add(para1); // add a couple of blank lines document.add(Chunk.NEWLINE); if (transactionForm.getLstPayment() != null && transactionForm.getLstPayment().size() > 0) { PdfPTable table2 = new PdfPTable(7); float[] columnWidths = { 1.5f, 1.5f, 3f, 4f, 4f, 7f, 2f }; table2.setWidthPercentage(100); table2.setWidths(columnWidths); para1 = new Paragraph("Sl No.", font); para1.setAlignment(Element.ALIGN_CENTER); PdfPCell cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph("Term", font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph("Receipt No.", font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph("Receipt Date", font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph("Payment Mode", font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph("Remarks", font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph("Paid Amount", font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); int x = 1; double total = 0; //Iterator it = hmPayments.entrySet().iterator(); //while (it.hasNext()) { if (hmPayments.size() > 0) { for (int i = 1; i <= obj.getNoofinstallment(); i++) { //float f = columnWidths[i]; Payment f1 = (Payment) hmPayments.get(i + ""); //} //Map.Entry pairs = (Map.Entry) it.next(); //Payment f1 = (Payment) pairs.getValue(); String term = i + ""; para1 = new Paragraph(Integer.toString(x), font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); x++; para1 = new Paragraph(term, font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph(f1.getPaymentid() + "", font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph(sdf.format(f1.getPaiddate()), font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph(f1.getPaymentmode() == 1 ? "Cash" : "Cheque/NEFT", font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); para1 = new Paragraph(f1.getRemarks(), font); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); //para1 = new Paragraph(f1.getPaidamount() + "", boldfont); para1 = new Paragraph((int) obj.getInstallmentamount() + "", boldfont); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); table2.addCell(cell); total = total + obj.getInstallmentamount(); if (hmPayments.size() == i) { break; } } para1 = new Paragraph("Total", boldfont); para1.setAlignment(Element.ALIGN_LEFT); cell = new PdfPCell(para1); cell.setColspan(6); table2.addCell(cell); //String numberStr = String.format("%.2f", total + ""); para1 = new Paragraph(total + "", boldfont); para1.setAlignment(Element.ALIGN_CENTER); cell = new PdfPCell(para1); //cell.setColspan(7); table2.addCell(cell); table2.setHorizontalAlignment(Element.ALIGN_LEFT); document.add(table2); } else { para1 = new Paragraph("NO PAYMENTS FOUND", boldfont); para1.setAlignment(Element.ALIGN_CENTER); document.add(para1); } } else { para1 = new Paragraph("NO RECORDS FOUND", boldfont); para1.setAlignment(Element.ALIGN_CENTER); document.add(para1); } document.add(Chunk.NEWLINE); //document.close(); //fileInputStream = new FileInputStream(new File("C:\\reports\\PaymentReports.pdf")); document.close(); ServletOutputStream outputStream = response.getOutputStream(); baos.writeTo(outputStream); response.setHeader("Content-Disposition", "attachment; filename=\"PaymentStatusReport.pdf\""); response.setContentType("application/pdf"); outputStream.flush(); outputStream.close(); return mapping.findForward("display"); } else { para1 = new Paragraph("NO RECORDS FOUND", boldfont); para1.setAlignment(Element.ALIGN_CENTER); document.add(para1); document.close(); ServletOutputStream outputStream = response.getOutputStream(); baos.writeTo(outputStream); response.setHeader("Content-Disposition", "attachment; filename=\"PaymentStatusReport.pdf\""); response.setContentType("application/pdf"); outputStream.flush(); outputStream.close(); return mapping.findForward("display"); } } catch (DocumentException i) { System.out.println(i); return mapping.findForward("fail"); } catch (IOException i) { System.out.println(i); return mapping.findForward("fail"); } } else { return mapping.findForward("exp"); } }
From source file:com.mycom.products.mywebsite.backend.util.DownloadHandler.java
License:Open Source License
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET) protected final void downloadUserInformation(@PathVariable int id, HttpServletRequest request, final HttpServletResponse response) throws ServletException, BusinessException, DocumentException { UserBean user = userService.select(id, FetchMode.EAGER); if (user == null) { return;/*from w w w .ja v a2 s. c om*/ } Document document = new Document(); document.setMargins(70, 70, 20, 20); try { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=\"" + user.getName() + "_profile.pdf\""); PdfWriter.getInstance(document, response.getOutputStream()); document.open(); Image profileImage = null; try { profileImage = Image.getInstance(user.getContent().getFilePath()); } catch (Exception e) { // e.printStackTrace(); } if (profileImage != null) { profileImage.setAlignment(Image.MIDDLE | Image.TEXTWRAP); profileImage.setBorder(Image.BOX); profileImage.setBorderWidth(5); BaseColor bgcolor = WebColors.getRGBColor("#E5E3E3"); profileImage.setBorderColor(bgcolor); profileImage.scaleToFit(100, 100); document.add(profileImage); } document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); // Adding Table Data PdfPTable table = new PdfPTable(2); // 2 columns. table.setWidthPercentage(100); // Width 100% table.setSpacingBefore(15f); // Space before table table.setSpacingAfter(15f); // Space after table // Set Column widths float[] columnWidths = { 1f, 2f, }; table.setWidths(columnWidths); // Name setTableHeader("Name", table); setTableContent(user.getName(), table); // Gender setTableHeader("Gender", table); String gender = "Male"; if (user.getGender() == Gender.FEMALE) { gender = "Female"; } setTableContent(gender, table); // Age setTableHeader("Age", table); setTableContent("" + user.getAge(), table); // Date of Birth setTableHeader("DOB", table); DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); setTableContent(dateFormatter.format(user.getDob()), table); // Email setTableHeader("Email", table); setTableContent(user.getEmail(), table); // NRC setTableHeader("NRC", table); setTableContent(user.getNrc(), table); // Phone setTableHeader("Phone", table); setTableContent(user.getPhone(), table); // Roles String roleStr = ""; List<RoleBean> roles = user.getRoles(); if (roles != null && roles.size() > 0) { Iterator<RoleBean> itr = roles.iterator(); while (itr.hasNext()) { RoleBean role = itr.next(); roleStr += role.getName(); if (itr.hasNext()) { roleStr += ","; } } } setTableHeader("Role(s)", table); setTableContent(roleStr, table); // Address setTableHeader("Address", table); setTableContent(user.getAddress(), table); document.add(table); document.add(new Paragraph(new Date().toString())); } catch (Exception e) { e.printStackTrace(); } document.close(); }
From source file:com.mycompany.bandaru_exam.accountDriver.java
/** * @param args the command line arguments *//*from w w w.j a v a2 s . c o m*/ public static void main(String[] args) throws FileNotFoundException, DocumentException, BadElementException, IOException { // TODO code application logic here ReadfromExcel rd = new ReadfromExcel(); List<Account> accountList = rd.getAccountListFromExcel(); for (Account a : accountList) { System.out.println(a.getFirstName()); OutputStream file = new FileOutputStream(new File(a.getLastName() + ".pdf")); Document document = new Document(); PdfWriter.getInstance(document, file); //Inserting Image in PDF Image image = Image.getInstance("logo.png"); image.scaleAbsolute(600f, 100f);//image width,height //Now Insert Every Thing Into PDF Document document.open();//PDF document opened........ document.add(image); document.add(new Paragraph("Welcome! " + a.getFirstName() + " " + a.getLastName() + "!")); document.add(new Paragraph(" ")); document.add(new Paragraph(" " + "Below are your Account Details :")); document.add(new Paragraph(" " + "First Name:" + a.getFirstName())); document.add(new Paragraph(" " + "Last Name:" + a.getLastName())); document.add(new Paragraph(" " + "Account Number:" + a.getAccNumber())); document.add(new Paragraph(" " + "Account Balance:$" + a.getBalance())); document.close(); file.close(); } }
From source file:com.mycompany.mavenproject1.Createpdf.java
public void createPDF(String pdfFilename) { Document doc = new Document(); PdfWriter docWriter = null;/* w w w . j a va 2 s . c o m*/ initializeFonts(); try { String path = "C:\\Users\\Thaskioglu\\Downloads\\" + pdfFilename; docWriter = PdfWriter.getInstance(doc, new FileOutputStream(path)); doc.addAuthor("FabulousCar"); doc.addCreationDate(); doc.addProducer(); doc.addCreator("FabulousCar"); doc.addTitle("Invoice"); doc.setPageSize(PageSize.LETTER); doc.open(); PdfContentByte cb = docWriter.getDirectContent(); boolean beginPage = true; int y = 0; for (int i = 0; i < 100; i++) { if (beginPage) { beginPage = false; generateLayout(doc, cb); generateHeader(doc, cb); y = 615; } generateDetail(doc, cb, i, y); y = y - 15; if (y < 50) { printPageNumber(cb); doc.newPage(); beginPage = true; } } printPageNumber(cb); } catch (DocumentException dex) { dex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (doc != null) { doc.close(); } if (docWriter != null) { docWriter.close(); } } }
From source file:com.mycompany.mavenproject1.HelloWorld.java
/** * Creates a PDF document./*from w w w.j a v a 2s . com*/ * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdf(String filename) throws DocumentException, IOException { // step 1 Document document = new Document(); // step 2 PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 document.add(new Paragraph("Hello World!")); // step 5 document.close(); }