List of usage examples for com.itextpdf.text Paragraph setAlignment
public void setAlignment(int alignment)
From source file:Model.Emprestimo.java
private void resultado() { Document documento = new Document(); Livro l;//from ww w . j a v a 2 s.co m try { PdfWriter.getInstance(documento, new FileOutputStream("Emprestimo" + id() + ".pdf")); } catch (DocumentException ex) { Logger.getLogger(Emprestimo.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(Emprestimo.class.getName()).log(Level.SEVERE, null, ex); } documento.open(); try { Paragraph pa = new Paragraph(); Font fonte = new Font(Font.FontFamily.TIMES_ROMAN, 28, Font.BOLD, new BaseColor(0, 0, 225)); pa.setFont(fonte); pa.setAlignment(Element.ALIGN_CENTER); pa.setSpacingAfter(50); pa.add("Emprestimo"); documento.add(pa); fonte = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0)); pa = new Paragraph(); pa.setFont(fonte); pa.setAlignment(Element.ALIGN_LEFT); pa.add("id: " + Integer.toString(id())); documento.add(pa); pa = new Paragraph(); pa.setFont(fonte); pa.setAlignment(Element.ALIGN_LEFT); pa.add("ra: " + Integer.toString(this.getRa())); documento.add(pa); String lin = ""; String[] h = this.Livros.split("/"); for (int c = 0; c < h.length; c++) { l = new Livro(); l.consultar(Integer.parseInt(h[c])); lin = lin + l.getNome() + "\n"; } pa = new Paragraph(); pa.setFont(fonte); pa.setAlignment(Element.ALIGN_LEFT); pa.add("Livros: " + lin); documento.add(pa); pa = new Paragraph(); pa.setFont(fonte); pa.setAlignment(Element.ALIGN_LEFT); pa.add("Data de Realizao: " + this.dataR); documento.add(pa); pa = new Paragraph(); pa.setFont(fonte); pa.setAlignment(Element.ALIGN_LEFT); pa.add("Data de Devoluo: " + this.dataD); documento.add(pa); } catch (DocumentException ex) { Logger.getLogger(Emprestimo.class.getName()).log(Level.SEVERE, null, ex); } documento.close(); }
From source file:Model.GerarRelatorio.java
public void toParagraphs(String linha, int alinhamento) { Paragraph p = new Paragraph(); p.add(linha);//from w w w. jav a 2 s. c o m p.setAlignment(alinhamento); paragrafos.add(p); }
From source file:Model.GerarRelatorio.java
public void toParagraphs(String linha, int alinhamento, Font font) { Paragraph p = new Paragraph(linha, font); p.setAlignment(alinhamento); paragrafos.add(p);/*from w w w .j av a2 s. com*/ }
From source file:model.PDFModel.java
License:Open Source License
public void createDailyPDF(String fileName, String date) throws DocumentException, FileNotFoundException, BadElementException, IOException { Document pdf = new Document(); PdfWriter.getInstance(pdf, new FileOutputStream(fileName)); Paragraph tittle = new Paragraph("RESTAURACJA LITERA"); tittle.setAlignment(Element.ALIGN_CENTER); Image logo = Image.getInstance("logo.png"); logo.setAlignment(Element.ALIGN_RIGHT); Paragraph headerParagraph = new Paragraph("Raport Dzienny " + date); headerParagraph.setAlignment(Element.ALIGN_CENTER); pdf.open();//w w w . ja v a 2 s . c o m pdf.add(logo); pdf.add(tittle); pdf.add(new Paragraph(" ")); pdf.add(headerParagraph); for (int i = 0; i < 10; i++) { pdf.add(createTablePDFTable(i + 1, date)); } pdf.add(createDailyTable(date)); pdf.close(); System.out.println("closed"); }
From source file:modelo.cobros.Pago.java
public void imprimirPDF() { Document documento = new Document(); FileOutputStream ficheroPdf;// ww w . j a v a 2s .c om try { String userhome = System.getProperty("user.home"); ficheroPdf = new FileOutputStream(userhome + "/Desktop/ejemplo.PDF"); PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20); } catch (Exception ex) { System.out.println(ex.toString()); } try { documento.open(); Paragraph parrafo1 = new Paragraph("FERRETERIA", FontFactory.getFont("arial", 24, Font.BOLD)); documento.add(parrafo1); parrafo1.setAlignment(Chunk.ALIGN_MIDDLE); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); Paragraph parrafo4 = new Paragraph("FECHA: " + factura.getFecha(), FontFactory.getFont("arial", 12)); documento.add(parrafo4); Paragraph parrafo2 = new Paragraph("VENDEDOR: " + factura.getVendedor().getNombre(), FontFactory.getFont("arial", 12)); documento.add(parrafo2); Paragraph parrafo3 = new Paragraph("CLIENTE: " + factura.getCliente().getNombre(), FontFactory.getFont("arial", 12)); documento.add(parrafo3); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); PdfPTable tabla = new PdfPTable(5); //el numero indica la cantidad de Columnas tabla.addCell("Cdigo"); tabla.addCell("Descripcin"); tabla.addCell("Cantidad"); tabla.addCell("Unidad"); tabla.addCell("Precio"); for (LineaDetalle linea : factura.getDetalles()) { tabla.addCell(linea.getProducto().getCodigo()); tabla.addCell(linea.getProducto().getDescripcion()); tabla.addCell(Integer.toString(linea.getCantidad())); tabla.addCell(linea.getProducto().getUnidadMedida()); tabla.addCell(String.valueOf(linea.getProducto().getPrecio())); } // esto nos crea una tabla de 3 Columnas por dos Filas documento.add(tabla); documento.add(new Paragraph(" ")); documento.add(new Paragraph("SUBTOTAL A PAGAR: " + String.valueOf(factura.subTotal()))); documento.add(new Paragraph("DESCUENTO: " + String.valueOf(factura.getDescuento()))); documento.add(new Paragraph("TOTAL A PAGAR: " + String.valueOf(factura.calculateTotalPago()))); documento.close(); } catch (Exception ex) { System.out.println(ex.toString()); } }
From source file:Modelo.CotizacionDAO.java
public void writePdf(OutputStream outputStream, Cotizacion x, int idcotizacion) throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/YYYY"); Calendar cdos = Calendar.getInstance(); Date datediamas = new Date(); Date dateaniomas = new Date(); cdos.add(Calendar.DATE, 1);//from w ww . ja v a2 s . com datediamas = cdos.getTime(); String fechadiamas = df.format(datediamas); cdos.add(Calendar.YEAR, 1); dateaniomas = cdos.getTime(); String fechavencimiento = df.format(dateaniomas); Document document = new Document(PageSize.LETTER, 50, 50, 50, 30); Font boldFontTitulo = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); Font boldFontTexto = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD); Font FontTexto = new Font(Font.FontFamily.HELVETICA, 10); // document.setPageSize(null); PdfWriter writer = PdfWriter.getInstance(document, outputStream); Image imagen = Image.getInstance("http://54.67.56.185/BSeguros_pa18/img/BSeguroLogo.png"); // Image imagen = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\BSeguroLogo.png"); Image imagen2 = Image.getInstance( "http://54.67.56.185/BSeguros_pa18/img/Aseguradoras/" + x.getId_aseguradora() + ".png"); //Image imagen2 = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\Mapfre.png"); document.open(); PdfContentByte canvas = writer.getDirectContent(); Rectangle rect = new Rectangle(36, 36, 579, 756); rect.setBorder(Rectangle.BOX); rect.setBorderWidth(2); canvas.rectangle(rect); document.addTitle("Cotizacion"); document.addSubject("Cotizacion"); document.addKeywords("Cotizacion, seguros"); document.addAuthor("BSeguro"); document.addCreator("Bseguro"); imagen.scaleAbsoluteHeight(30f); imagen.setAbsolutePosition(45f, 720f); imagen2.scaleAbsoluteHeight(30f); imagen2.setAbsolutePosition(450f, 720f); document.add(imagen); document.add(imagen2); Paragraph paragraph2 = new Paragraph("DATOS DE TU POLIZA", boldFontTitulo); paragraph2.setAlignment(Element.ALIGN_CENTER); document.add(paragraph2); //creas una tabla con un ancho de 3 celdas, el salto a la siguiente fila sera automatico PdfPTable table = new PdfPTable(3); table.getDefaultCell().setBorder(0); PdfPCell cell; Paragraph saltodelinea = new Paragraph(" "); document.add(saltodelinea); document.add(new Paragraph(" Datos de tu poliza folio: " + "BC" + x.getId_aseguradora().substring(0, 1) + x.getMetododepago().substring(0, 1) + ": 0000" + idcotizacion, boldFontTitulo)); document.add(new Paragraph(" Vigencia de la poliza del: " + fechadiamas + " al: " + fechavencimiento, boldFontTitulo)); document.add(saltodelinea); document.add(new Paragraph(" Datos del Contratante: ", boldFontTitulo)); //document.add(saltodelinea); //agrego otra tabla table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(new Paragraph("Nombre: ", boldFontTexto)); PdfPCell celdaNombre = new PdfPCell( new Paragraph(x.getNombre_contratante() + " " + x.getApellido_paterno(), FontTexto)); celdaNombre.setColspan(5); celdaNombre.setBorder(0); table.addCell(celdaNombre); table.addCell(new Paragraph("RFC : ", boldFontTexto)); PdfPCell celdaRFC = new PdfPCell(new Paragraph(x.getRfc(), FontTexto)); celdaRFC.setColspan(5); celdaRFC.setBorder(0); table.addCell(celdaRFC); table.addCell(new Paragraph("Direccion: ", boldFontTexto)); PdfPCell celdaDir = new PdfPCell( new Paragraph(x.getCall() + ", " + x.getNo_ext() + ", " + x.getNo_int() + ", " + x.getColonia() + ", " + x.getDelegacion() + ", " + x.getEstado() + ", " + x.getCp(), FontTexto)); celdaDir.setColspan(5); celdaDir.setBorder(0); table.addCell(celdaDir); table.addCell(new Paragraph("Email: ", boldFontTexto)); table.addCell(AddCell(x.getMail(), 5)); table.addCell(new Paragraph("Telefono ", boldFontTexto)); PdfPCell celdaTel = new PdfPCell(new Paragraph(x.getTelefono(), FontTexto)); celdaTel.setColspan(5); celdaTel.setBorder(0); table.addCell(celdaTel); document.add(table); document.add(saltodelinea); document.add(new Paragraph(" Datos del Vehiculo: ", boldFontTitulo)); // document.add(saltodelinea); //agrego otra tabla table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(new Paragraph("Marca: ", boldFontTexto)); table.addCell(AddCell(x.getId_marca(), 5)); table.addCell(new Paragraph("Modelo:", boldFontTexto)); table.addCell(AddCell(x.getId_anio().toString(), 5)); table.addCell(new Paragraph("Tipo: ", boldFontTexto)); table.addCell(AddCell(x.getId_submarca(), 5)); table.addCell(new Paragraph("Version: ", boldFontTexto)); table.addCell(AddCell(x.getId_modelo(), 5)); table.addCell(new Paragraph("No. De Serie: ", boldFontTexto)); table.addCell(AddCell(x.getSerie(), 5)); document.add(table); document.add(saltodelinea); document.add(new Paragraph(" Informacion de la Poliza: ", boldFontTitulo)); // document.add(saltodelinea); //agrego otra tabla table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(new Paragraph("Pago: ", boldFontTexto)); table.addCell(AddCell(x.getTipo_pago(), 5)); table.addCell(new Paragraph("Aseguradora: ", boldFontTexto)); table.addCell(AddCell(x.getId_aseguradora(), 5)); document.add(table); document.add(saltodelinea); document.add(new Paragraph(" Detalles de la Cobertura: Cobertura Amplia ", boldFontTitulo)); // document.add(saltodelinea); //agrego otra tabla table = new PdfPTable(3); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(new Paragraph("Cobertura ", boldFontTexto)); table.addCell(new Paragraph("Responsabilidad Civil", boldFontTexto)); table.addCell(new Paragraph("Deducible ", boldFontTexto)); table.addCell(new Paragraph("Daos Materiales", FontTexto)); table.addCell(new Paragraph("Valor Comercial", FontTexto)); table.addCell(new Paragraph("5%", FontTexto)); table.addCell(new Paragraph("Robo Total", FontTexto)); table.addCell(new Paragraph("Valor Comercial", FontTexto)); table.addCell(new Paragraph("10%", FontTexto)); table.addCell(new Paragraph("Responsabilidad Civil", FontTexto)); table.addCell(new Paragraph("$4,000,000.00", FontTexto)); table.addCell(new Paragraph("", FontTexto)); table.addCell(new Paragraph("Gastos Medicos Ocupantes", FontTexto)); table.addCell(new Paragraph("$500,000.00", FontTexto)); table.addCell(new Paragraph("", FontTexto)); table.addCell(new Paragraph("Asistencia Legal", FontTexto)); table.addCell(new Paragraph("Amparada", FontTexto)); table.addCell(new Paragraph("", FontTexto)); table.addCell(new Paragraph("Asistencia Vial", FontTexto)); table.addCell(new Paragraph("Amparada", FontTexto)); table.addCell(new Paragraph("", FontTexto)); document.add(table); document.add(saltodelinea); document.add(new Paragraph(" Informacion del Pago ", boldFontTitulo)); document.add(new Paragraph(" Instrumento de Pago: " + x.getMetododepago(), boldFontTexto)); //agrego otra tabla table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(AddCell("Concepto ", 2)); table.addCell(AddCell("Monto", 4)); table.addCell(AddCell("Prima Total ", 2)); table.addCell(AddCell(x.getMonto(), 4)); table.addCell(AddCell("Prima Inicial", 2)); table.addCell(AddCell(x.getMonto(), 4)); table.addCell(AddCell("Pago Subsecuente ", 2)); table.addCell(AddCell("0", 4)); document.add(table); document.add(saltodelinea); if (x.getCobertura_auto_siempre() == true) { document.add(new Paragraph(" Informacion de Modulos HDI ", boldFontTitulo)); table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(AddCell("Modulos ", 2)); table.addCell(AddCell("Contratados", 4)); table.addCell(AddCell("HDI - Autos por Siempre ", 2)); table.addCell(AddCell("$ 1,799.00", 4)); document.add(table); } else { if (x.getCobertura_auto_amante() == true) { document.add(new Paragraph(" Informacion de Modulos HDI ", boldFontTitulo)); table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(AddCell("Modulos ", 2)); table.addCell(AddCell("Contratados", 4)); table.addCell(AddCell("HDI - Amante de los Autos ", 2)); table.addCell(AddCell("$ 1,799.00", 4)); document.add(table); } else { } document.add(saltodelinea); } document.add(new Paragraph("* Estaras asegurado a partir de las 12 horas del siguiente dia habil.", boldFontTexto)); document.close(); }
From source file:modelo.GeneratorPDF.java
public static void main(String[] args) { // criao do documento Document document = new Document(PageSize.A4, 72, 72, 72, 72); try {//from w w w.j a v a2 s. com PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\Amanda\\Desktop\\teste.pdf")); document.open(); Font f = new Font(FontFamily.COURIER, 20, Font.BOLD); // adicionando um pargrafo no documento Paragraph p1 = new Paragraph("Gerando PDF - Java", f); p1.setAlignment(Element.ALIGN_CENTER); document.add(p1); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } document.close(); }
From source file:mvjce.PDF.java
public static void create(int sino) {// sino = SI.No // TODO code application logic here try {/*from w w w . j av a 2 s . c o m*/ //Create Document instance. Document document = new Document(); //Create OutputStream instance. OutputStream outputStream = new FileOutputStream( new File("/home/narein/NetBeansProjects/" + sem + cl + "/" + usn + ".pdf")); //Create PDFWriter instance. PdfWriter.getInstance(document, outputStream); //Open the document. document.open(); //image position Image imageCenter = Image.getInstance("/home/narein/Downloads/mvj.png"); //imageCenter.setAlignment(Image.MIDDLE); imageCenter.setAbsolutePosition(235, 780); imageCenter.scaleAbsolute(146f, 53f); //Permanently affiliated para PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100); table.addCell(getCell( "\n\n\nPermanently affiliated to VTU, Govt. of Karnataka\nApproved by AICTE, New Delhi\nNear ITPB, Bengaluru- 560067\n\n" + hod_name + ", HOD - " + dep, PdfPCell.ALIGN_LEFT)); table.addCell(getCell("\n\n\n\nPh: 080-42991000\nFax: 080-28452443\nWebsite: www.mvjce.edu.in\nEmail: " + hod_email + "\n\n", PdfPCell.ALIGN_RIGHT)); //line across pdf final LineSeparator lineSeparator = new LineSeparator(); Chunk linebreak = new Chunk(lineSeparator); Phrase p = new Phrase("\nPROGRESS REPORT\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.UNDERLINE | Font.BOLD)); Paragraph para = new Paragraph(p); para.setAlignment(Element.ALIGN_CENTER); Chunk glue = new Chunk(new VerticalPositionMark()); Paragraph p1 = new Paragraph("\nRef:", new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD)); p1.add(new Chunk(glue)); //get current date DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy"); LocalDate localDate = LocalDate.now(); //add date to pdf p1.add(new Phrase("Date: " + dtf.format(localDate) + "\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD))); Phrase dear_prnts = new Phrase("Dear Parents,\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD)); Phrase The_acad = new Phrase( " The academic performance of your ward Mr/Ms " + name + " of Semester " + sem + " bearing the USN " + usn + " is as follows,\n\n", new Font(FontFamily.TIMES_ROMAN, 9)); Phrase Rem = new Phrase("Remarks\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.UNDERLINE | Font.BOLD)); Phrase your_ward = new Phrase( "\nYour ward's overall performance is Good / Satisfactory / Poor / Very Poor\n", new Font(FontFamily.TIMES_ROMAN, 9)); Phrase you_are = new Phrase("\nYou are requested to:\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD)); Phrase req = new Phrase(""); Paragraph para2 = new Paragraph( "1) Advice your ward to attend classes regularly\n2) Note that he/she may likely be detainedfrom appearing for examinations\n" + "3) Advice your ward to improve in Test/Exam performance particularly in subject\n4) Meet the Head of the Department\n5) Meet the principal\n", new Font(FontFamily.TIMES_ROMAN, 9)); Chunk glue1 = new Chunk(new VerticalPositionMark()); Paragraph p3 = new Paragraph("\nSIGNATURE:\n\nNAME OF PROCTOR:\n\nCONTACT NUMBER:", new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD)); p3.add(new Chunk(glue1)); p3.add(new Phrase( "SIGNATURE OF HOD\n\n Kindly attend the Parent Teacher Meeting to be held on the date informed to your ward.\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD))); Phrase Note = new Phrase("\nNOTE:", new Font(FontFamily.TIMES_ROMAN, 10, Font.UNDERLINE | Font.BOLD)); Paragraph p4 = new Paragraph(); p4.add(Note); p4.add(new Phrase( " Parents are requested to contact the proctor (By Email/Letter/Phone) and confirm receipt of this feedback. Parents are also" + "welcome to interact with proctors/subject faculty/ HOD for any discussion/clarification.\n", new Font(FontFamily.TIMES_ROMAN, 9))); //Add content to the document. document.add(imageCenter); document.add(table); document.add(linebreak); document.add(para); document.add(p1); document.add(dear_prnts); document.add(The_acad); document.add(createinternalsTable()); if (internal.equals("1")) { document.add(new Phrase("\nPREVIOUS SEMESTER VTU RESULT\n\n", new Font(FontFamily.TIMES_ROMAN, 10, Font.UNDERLINE | Font.BOLD))); document.add(createexternalTable()); } document.add(Rem); document.add(your_ward); document.add(you_are); document.add(para2); document.add(p3); document.add(p4); //document.add(paragraph);document.add(paragraph1); //Close document and outputStream. document.close(); outputStream.close(); System.out.println("Pdf created successfully."); } catch (Exception e) { e.printStackTrace(); } }
From source file:net.sf.texprinter.generators.PDFGenerator.java
License:Open Source License
/** * Generates a PDF file from a Question object. * /*from ww w.j a v a 2 s . c o m*/ * @param question The question. * @param filename The filename. */ public static void generate(Question question, String filename) { // wait window ProgressMessage pm = new ProgressMessage("TeXPrinter is printing your PDF file."); // start wait window //pm.start(); // log message log.log(Level.INFO, "Starting PDF generation of {0}.", filename); // define a new PDF document Document document = null; // define a new PDF writer PdfWriter writer = null; // lets try try { // create a new PDF document document = new Document(); // define a new PDF Writer writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // set the PDF version writer.setPdfVersion(PdfWriter.VERSION_1_6); // open the document document.open(); // set the title font Font titleFont = new Font(FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK); // set the chunk for the question title Chunk questionTitle = new Chunk(question.getQuestion().getTitle(), titleFont); // create a paragraph from that chunk Paragraph paragraphQuestionTitle = new Paragraph(questionTitle); // log message log.log(Level.INFO, "Adding the question title."); // add the question title to the document document.add(paragraphQuestionTitle); // set the asker font Font askerFont = new Font(FontFamily.HELVETICA, 10, Font.ITALIC, BaseColor.DARK_GRAY); // set the chunk for the asker Chunk questionAsker = new Chunk("Asked by " + question.getQuestion().getUser().getName() + " (" + question.getQuestion().getUser().getReputation() + ") on " + question.getQuestion().getDate() + " (" + String.valueOf(question.getQuestion().getVotes()) + (question.getQuestion().getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // create a paragraph from that chunk Paragraph paragraphQuestionAsker = new Paragraph(questionAsker); // log message log.log(Level.INFO, "Adding both asker and reputation."); // add the asker to the document document.add(paragraphQuestionAsker); // create a line separator LineSeparator line = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -5); // add the line to the document document.add(line); // add a new line document.add(Chunk.NEWLINE); // create a list of elements from the question objects List<Element> questionTextObjects = getPostText(question.getQuestion().getText()); // log message log.log(Level.INFO, "Adding the question text."); // for each element for (Element questionTextObject : questionTextObjects) { // add it to the document document.add(questionTextObject); } // add a new line document.add(Chunk.NEWLINE); // create a new font for the comments title Font commentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK); // create a new chunk based on that font Chunk commentsTitle = new Chunk( "This question has " + question.getQuestion().getComments().size() + ((question.getQuestion().getComments().size() == 1) ? " comment:" : " comments:"), commentsTitleFont); // create a paragraph from that chunk Paragraph paragraphCommentsTitle = new Paragraph(commentsTitle); // if there are comments to this question if (!question.getQuestion().getComments().isEmpty()) { // log message log.log(Level.INFO, "Adding the question comments."); // add that paragraph to the document document.add(paragraphCommentsTitle); // add a new line document.add(Chunk.NEWLINE); // get all the comments List<Comment> questionComments = question.getQuestion().getComments(); // for each comment for (Comment questionComment : questionComments) { // get the elements of the comment text List<Element> questionCommentObjects = getPostText(questionComment.getText()); // for each element for (Element questionCommentObject : questionCommentObjects) { // add it to the document document.add(questionCommentObject); } // create a new paragraph about the comment author Paragraph paragraphCommentAuthor = new Paragraph(questionComment.getAuthor() + " on " + questionComment.getDate() + " (" + String.valueOf(questionComment.getVotes()) + (questionComment.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // set the alignment to the right paragraphCommentAuthor.setAlignment(Element.ALIGN_RIGHT); // add the paragraph to the document document.add(paragraphCommentAuthor); // add a new line document.add(Chunk.NEWLINE); } } // add a line separator document.add(line); // add two new lines document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); // get the list of answers List<Post> answersList = question.getAnswers(); // if there are no answers if (answersList.isEmpty()) { // log message log.log(Level.INFO, "This question has no answers."); // create a new chunk Chunk noAnswersTitle = new Chunk("Sorry, this question has no answers yet.", titleFont); // create a paragraph from that chunk Paragraph paragraphNoAnswersTitle = new Paragraph(noAnswersTitle); // add the paragraph to the document document.add(paragraphNoAnswersTitle); } else { // log message log.log(Level.INFO, "Adding answers."); // there are answers, so create a counter for answers int answerCount = 1; // for each answer for (Post answer : answersList) { // log message log.log(Level.INFO, "Adding answer {0}.", answerCount); // set the message text as empty String answerAccepted = ""; // if the answer is accepted if (answer.isAccepted()) { // add that to the message answerAccepted = " - Marked as accepted."; } // create a new chunk Chunk answerTitle = new Chunk("Answer #" + answerCount, titleFont); // create a paragraph from that chunk Paragraph paragraphAnswerTitle = new Paragraph(answerTitle); // add the paragraph to the document document.add(paragraphAnswerTitle); // increase the counter answerCount++; // create a new chunk Chunk questionAnswerer = new Chunk("Answered by " + answer.getUser().getName() + " (" + answer.getUser().getReputation() + ") on " + answer.getDate() + answerAccepted + " (" + String.valueOf(answer.getVotes()) + (answer.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // create a paragraph from that chunk Paragraph paragraphQuestionAnswerer = new Paragraph(questionAnswerer); // add that paragraph to the document document.add(paragraphQuestionAnswerer); // add a line separator document.add(line); // add a new line document.add(Chunk.NEWLINE); // create a list of elements from the answer text List<Element> answerTextObjects = getPostText(answer.getText()); // for each element for (Element answerTextObject : answerTextObjects) { // add it to the document document.add(answerTextObject); } // add a new line document.add(Chunk.NEWLINE); // create a new font style Font answerCommentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK); // create a new chunk Chunk answerCommentsTitle = new Chunk( "This answer has " + answer.getComments().size() + ((answer.getComments().size() == 1) ? " comment:" : " comments:"), answerCommentsTitleFont); // create a paragraph from that chunk Paragraph paragraphAnswerCommentsTitle = new Paragraph(answerCommentsTitle); // if there are comments for that answer if (!answer.getComments().isEmpty()) { // log message log.log(Level.INFO, "Adding comments for answer {0}.", (answerCount - 1)); // add that paragraph to the document document.add(paragraphAnswerCommentsTitle); // add a new line document.add(Chunk.NEWLINE); // get all the comments List<Comment> answerComments = answer.getComments(); // for each comment for (Comment answerComment : answerComments) { // create a list of elements from the comment text List<Element> answerCommentObjects = getPostText(answerComment.getText()); // for each element for (Element answerCommentObject : answerCommentObjects) { // add it to the document document.add(answerCommentObject); } // create a new paragraph for the comment author Paragraph paragraphAnswerCommentAuthor = new Paragraph( answerComment.getAuthor() + " on " + answerComment.getDate() + " (" + String.valueOf(answerComment.getVotes()) + (answerComment.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // set the aligment to the right paragraphAnswerCommentAuthor.setAlignment(Element.ALIGN_RIGHT); // add the paragraph to the document document.add(paragraphAnswerCommentAuthor); // add a new line document.add(Chunk.NEWLINE); } } // add a line separator document.add(line); // add two new lines document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); } } // log message log.log(Level.INFO, "PDF generation complete, closing {0}.", filename); // close the document document.close(); // stop wait window pm.interrupt(); } catch (IOException ioexception) { // stop wait window pm.interrupt(); // log message log.log(Level.SEVERE, "An IO error occurred while trying to create the PDF file. MESSAGE: {0}", StringUtils.printStackTrace(ioexception)); // critical error, exit Dialogs.showExceptionWindow(); } catch (Exception exception) { // log message log.log(Level.SEVERE, "A generic error occurred while trying to create the PDF file. MESSAGE: {0}", StringUtils.printStackTrace(exception)); // log message log.log(Level.INFO, "I will try to remove the remaining PDF file."); try { // log message log.log(Level.INFO, "Closing both document and writer."); // close the document document.close(); // close the writer writer.close(); } catch (Exception ex) { // log message log.log(Level.WARNING, "I could not close either document or writer. MESSAGE: {0}", StringUtils.printStackTrace(ex)); } try { // reference problematic file File target = new File(filename); // log message log.log(Level.INFO, "Opening problematic file {0}.", filename); // check if file exists if (target.exists()) { // log message log.log(Level.INFO, "File exists, trying to delete it."); // trying to remove it if (target.delete()) { // log message log.log(Level.INFO, "File {0} was successfully removed.", filename); } else { // log message log.log(Level.SEVERE, "File {0} could not be removed.", filename); } } } catch (SecurityException se) { // log message log.log(Level.SEVERE, "A security exception was raised. MESSAGE: {0}", StringUtils.printStackTrace(se)); } // stop wait window pm.interrupt(); // critical error, exit Dialogs.showExceptionWindow(); } }
From source file:net.viralpatel.pdf.FirstPdf.java
public static void main(String[] args) { try {/*ww w. j a va 2 s . co m*/ Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(FILE)); document.open(); // Left Paragraph paragraph = new Paragraph("This is right aligned text"); paragraph.setAlignment(Element.ALIGN_RIGHT); document.add(paragraph); // Centered paragraph = new Paragraph("This is centered text"); paragraph.setAlignment(Element.ALIGN_CENTER); document.add(paragraph); // Left paragraph = new Paragraph("This is left aligned text"); paragraph.setAlignment(Element.ALIGN_LEFT); document.add(paragraph); // Left with indentation paragraph = new Paragraph("This is left aligned text with indentation"); paragraph.setAlignment(Element.ALIGN_LEFT); paragraph.setIndentationLeft(50); document.add(paragraph); document.close(); } catch (Exception e) { e.printStackTrace(); } }