List of usage examples for com.itextpdf.text.pdf.draw LineSeparator LineSeparator
public LineSeparator(float lineWidth, float percentage, BaseColor lineColor, int align, float offset)
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] createModelPages(Contact contact, List<Model> models, Toc tableOfContents) throws IOException, DocumentException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Document document = iTextUtil.createNewDocument(); PdfWriter writer = PdfWriter.getInstance(document, bos); document.open();/* w w w. j a v a2 s . c o m*/ // create a PdfPTable for every model (so we can measure the height) final List<PdfPTable> modelPageTables = new ArrayList<>(); Collections.sort(models); for (Model model : models) { if (model != null) { modelPageTables.add(createModelPage(contact, model, writer)); } } // put the PdfPTable Models tables on PDF pages (multiple per page if possible) byte[] pages = new byte[] {}; int height = 0; List<String> pageNames = new ArrayList<>(); int i = 0; for (PdfPTable modelPageTable : modelPageTables) { // create a new pdf page, if necessary if (height != 0 && (height + modelPageTable.getTotalHeight() + 20 /* for the line separator */ ) >= iTextUtil.PAGE_HEIGHT) { writer.close(); document.close(); bos.close(); byte[] page = bos.toByteArray(); tableOfContents.addEntries(2, pageNames, page, true, Toc.MODEL_SORT_PREFIX + "___" + IntUtil.format(++i)); pages = iTextUtil.merge(pages, page); height = 0; pageNames.clear(); bos = new ByteArrayOutputStream(); document = iTextUtil.createNewDocument(); writer = PdfWriter.getInstance(document, bos); document.open(); } else if (height != 0) { // if not the first model on the page, draw a separator document.add(new Paragraph( new Chunk(new LineSeparator(.25f, 80f, BaseColor.LIGHT_GRAY, Element.ALIGN_CENTER, -2)))); document.add(new Paragraph(new Chunk(" "))); } // rerender the table (with a valid pdfWriter) document.add(createModelPage(contact, models.get(modelPageTables.indexOf(modelPageTable)), writer)); height += modelPageTable.getTotalHeight(); pageNames.add(models.get(modelPageTables.indexOf(modelPageTable)).getProductNameProcessed()); } writer.close(); document.close(); byte[] page = bos.toByteArray(); tableOfContents.addEntries(2, pageNames, page, true, Toc.MODEL_SORT_PREFIX + "___" + IntUtil.format(++i)); pages = iTextUtil.merge(pages, page); return pages; }
From source file:com.athena.chameleon.engine.core.PDFDocGenerator.java
License:Apache License
/** * //from w ww . ja v a2 s .c om * PDF Title Page * * @param doc * @param writer */ public static void setTitleMainPage(Document doc, PdfWriter writer, PDFCommonEventHelper event, Upload upload) throws Exception { Font fnTitle = new Font(bfKorean, 20, Font.BOLD); Font fnLabel = new Font(bfKorean, 11, Font.BOLD); Font fnText = new Font(bfKorean, 11); LineSeparator UNDERLINE = new LineSeparator(1, 80, null, com.itextpdf.text.Element.ALIGN_CENTER, -5); doc.newPage(); doc.add(Chunk.NEWLINE); event.setTitleFlag(true); int toc = writer.getPageNumber(); Image img = Image.getInstance(PDFDocGenerator.class.getResource("/image/title.gif")); img.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER); img.scalePercent(80, 80); doc.add(img); Paragraph titlePh = new Paragraph(MessageUtil.getMessage("pdf.message.main.title"), fnTitle); titlePh.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER); titlePh.setSpacingBefore(50); titlePh.setSpacingAfter(30); doc.add(titlePh); doc.add(UNDERLINE); PdfPTable t1 = new PdfPTable(2); t1.setSpacingBefore(20); t1.setWidths(new int[] { 110, 290 }); t1.getDefaultCell().setBorder(0); t1.getDefaultCell().setFixedHeight(32); t1.addCell(new Phrase(MessageUtil.getMessage("pdf.message.main.label.project_name"), fnLabel)); t1.addCell(new Phrase(upload.getProjectNm(), fnText)); t1.addCell(new Phrase(MessageUtil.getMessage("pdf.message.main.label.department"), fnLabel)); t1.addCell(new Phrase(upload.getDepartment(), fnText)); t1.addCell(new Phrase(MessageUtil.getMessage("pdf.message.main.label.focus_name"), fnLabel)); t1.addCell(new Phrase(MessageUtil.getMessage("pdf.message.main.text.focus_name"), fnText)); t1.addCell(new Phrase(MessageUtil.getMessage("pdf.message.main.label.product"), fnLabel)); t1.addCell(new Phrase(MessageUtil.getMessage("pdf.message.main.text.product", upload.getBeforeWas(), upload.getAfterWas()), fnText)); doc.add(t1); doc.add(UNDERLINE); Paragraph executedPh = new Paragraph(MessageUtil.getMessage("pdf.message.main.label.executed"), fnLabel); executedPh.setSpacingBefore(30); executedPh.setSpacingAfter(15); executedPh.setIndentationLeft(50); doc.add(executedPh); PdfPTable t2 = new PdfPTable(2); t2.getDefaultCell().setFixedHeight(28); t2.getDefaultCell().setVerticalAlignment(com.itextpdf.text.Element.ALIGN_MIDDLE); t2.getDefaultCell().setBackgroundColor(new BaseColor(217, 217, 217)); t2.addCell(new Phrase(MessageUtil.getMessage("pdf.message.main.label.owner"), fnLabel)); t2.addCell(new Phrase(MessageUtil.getMessage("pdf.message.main.label.project_role"), fnLabel)); t2.getDefaultCell().setBackgroundColor(new BaseColor(255, 255, 255)); t2.addCell(new Phrase(upload.getPerson(), fnText)); t2.addCell(new Phrase(upload.getOrgRole(), fnText)); doc.add(t2); doc.newPage(); int total = writer.reorderPages(null); int[] order = new int[total]; for (int i = 0; i < total; i++) { order[i] = i + toc; if (order[i] > total) order[i] -= total; } // apply the new order writer.reorderPages(order); }
From source file:comisionesafis.informes.FacturasComisionesAgentes.java
public boolean generar() { // Abrimos el fichero de comisiones Periodos periodos = new Periodos(pb.getFicheroComisiones()); String sSQL = ""; Statement stmt;/* w w w . j a v a 2s .c o m*/ ResultSet rsComisiones; String sFactura1; String sFactura2; // Generamos la sentencia de Seleccin de Datos try { // Generamos el PDF Document documento = new Document(PageSize.A4, 80, 80, 50, 50); FileOutputStream salida = new FileOutputStream("FacturasComisionesAgentes.pdf"); PdfWriter writer = PdfWriter.getInstance(documento, salida); writer.setInitialLeading(0); // Obtenemos una instancia de nuestro manejador de eventos FacturasComisionesAgentesPie pie = new FacturasComisionesAgentesPie(); //Asignamos el manejador de eventos al escritor. writer.setPageEvent(pie); // Abrimos el Documento documento.open(); sSQL = "SELECT * "; sSQL += " FROM ResumenComisiones"; sSQL += " ORDER BY CodAgente"; stmt = conexion.createStatement(); rsComisiones = stmt.executeQuery(sSQL); while (rsComisiones.next()) { // Generamos los prrafos // Datos del agente Paragraph pAgente[] = new Paragraph[5]; pAgente[0] = new Paragraph(); pAgente[0].add(rsComisiones.getString("Nombre")); pAgente[0].setAlignment(Paragraph.ALIGN_LEFT); pAgente[1] = new Paragraph(); pAgente[1].add(rsComisiones.getString("Direccion")); pAgente[1].setAlignment(Paragraph.ALIGN_LEFT); pAgente[2] = new Paragraph(); pAgente[2].add(rsComisiones.getString("CodPostal") + " " + rsComisiones.getString("Poblacion")); pAgente[2].setAlignment(Paragraph.ALIGN_LEFT); pAgente[3] = new Paragraph(); pAgente[3].add(rsComisiones.getString("Provincia")); pAgente[3].setAlignment(Paragraph.ALIGN_LEFT); pAgente[4] = new Paragraph(); pAgente[4].add(rsComisiones.getString("NIF")); pAgente[4].setAlignment(Paragraph.ALIGN_LEFT); // creating separators LineSeparator separador = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2); // Datos fijos Paragraph pPelayo[] = new Paragraph[5]; pPelayo[0] = new Paragraph(); pPelayo[0].add("PELAYO VIDA"); pPelayo[0].setAlignment(Paragraph.ALIGN_RIGHT); pPelayo[1] = new Paragraph(); pPelayo[1].add("CL SANTA ENGRACIA 69"); pPelayo[1].setAlignment(Paragraph.ALIGN_RIGHT); pPelayo[2] = new Paragraph(); pPelayo[2].add("28010 MADRID"); pPelayo[2].setAlignment(Paragraph.ALIGN_RIGHT); pPelayo[3] = new Paragraph(); pPelayo[3].add("MADRID"); pPelayo[3].setAlignment(Paragraph.ALIGN_RIGHT); pPelayo[4] = new Paragraph(); pPelayo[4].add("06422"); pPelayo[4].setAlignment(Paragraph.ALIGN_RIGHT); // Fecha Paragraph pFecha = new Paragraph(); pFecha = new Paragraph("Madrid, a " + periodos.extraeFechaLarga()); pFecha.setAlignment(Paragraph.ALIGN_RIGHT); // Lnea 1 de FACTURA Paragraph pFactura1 = new Paragraph(); sFactura1 = "FACTURA: n factura "; sFactura1 += rsComisiones.getString("CodAgente") + " - "; sFactura1 += periodos.extraePeriodoMY("MM-YYYY"); pFactura1 = new Paragraph(sFactura1); // Lnea 2 de FACTURA Paragraph pFactura2 = new Paragraph(); sFactura2 = "Factura por la prestacin de servicios relativos a las operaciones "; sFactura2 += "de intermediacin de seguros realizadas para su entidad del mes de "; sFactura2 += periodos.extraePeriodoMY("MM YYYY"); ; pFactura2 = new Paragraph(sFactura2); // Datos Econmicos float[] anchuras = { 5f, 2f }; PdfPTable table = new PdfPTable(anchuras); table.getDefaultCell().setBorder(0); // Tipo de letra para la tabla Font font = new Font(Font.FontFamily.COURIER, 11, Font.NORMAL); PdfPCell celda = new PdfPCell(); celda = new PdfPCell(new Phrase("Comisiones pagadas", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(celda); celda = new PdfPCell( new Phrase(Double.toString(rsComisiones.getDouble("TotalComisiones")) + " ", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(celda); celda = new PdfPCell(new Phrase("Otros conceptos", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(celda); celda = new PdfPCell(new Phrase(" ", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(celda); celda = new PdfPCell(new Phrase( "Retencin (" + Double.toString(rsComisiones.getDouble("RetencionPorcentaje")) + "%)", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(celda); Double dblRetencion = rsComisiones.getDouble("TotalComisiones") * (rsComisiones.getDouble("RetencionPorcentaje") / 100); celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(dblRetencion) + " ", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(celda); celda = new PdfPCell(new Phrase("Conceptos no sujetos", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(celda); celda = new PdfPCell(new Phrase(" ", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(celda); celda = new PdfPCell(new Phrase("Total a pagar", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(celda); Double dblTotalPagar = rsComisiones.getDouble("TotalComisiones") - dblRetencion; celda = new PdfPCell(new Phrase(Numeros.formateaDosDecimales(dblTotalPagar) + " ", font)); celda.setBorder(Rectangle.NO_BORDER); celda.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(celda); // Literal: Operacin exenta de IVA Paragraph pColetilla = new Paragraph(); pColetilla.add("Operacin exenta de IVA"); // Aadimos los prrafos al Documento for (int i = 0; i < 5; i++) documento.add(pAgente[i]); documento.add(new Paragraph(" ")); documento.add(separador); for (int i = 0; i < 5; i++) documento.add(pPelayo[i]); documento.add(new Paragraph(" ")); documento.add(pFecha); documento.add(new Paragraph(" ")); documento.add(pFactura1); documento.add(separador); documento.add(pFactura2); // Agregamos la tabla al documento documento.add(new Paragraph(" ")); documento.add(table); documento.add(new Paragraph(" ")); documento.add(new Paragraph(" ")); documento.add(pColetilla); documento.newPage(); } documento.close(); return true; } catch (Exception e) { return false; } }
From source file:net.sf.texprinter.generators.PDFGenerator.java
License:Open Source License
/** * Generates a PDF file from a Question object. * /*from w ww .java2 s . com*/ * @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:uy.edu.ort.arqliv.obligatorio.client.DemoConsole1.java
public static void createPdf(String filename) throws IOException, DocumentException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open();//from ww w . java 2s. c om BaseFont bf; Font font; for (int i = 0; i < FONTS.length; i++) { bf = BaseFont.createFont(FONTS[i][0], FONTS[i][1], BaseFont.EMBEDDED); document.add(new Paragraph(String.format("Font file: %s with encoding %s", FONTS[i][0], FONTS[i][1]))); document.add(new Paragraph(String.format("iText class: %s", bf.getClass().getName()))); font = new Font(bf, 12); document.add(new Paragraph(TEXT, font)); document.add(new LineSeparator(0.5f, 100, null, 0, -5)); } document.close(); }