List of usage examples for com.lowagie.text Document add
public boolean add(Element element) throws DocumentException
Element
to the Document
. From source file:com.allinfinance.system.util.PdfUtil.java
License:Open Source License
public static void create(String path, List<Object[]> list, LinkedHashMap<String, List<Object[]>> map) throws Exception { BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); ///*from w w w. j av a 2s . c o m*/ Font font17 = new Font(bfChinese, 17, Font.BOLD); Font font8 = new Font(bfChinese, 8, Font.NORMAL); Font font10 = new Font(bfChinese, 10, Font.NORMAL); Font font10Bold = new Font(bfChinese, 10, Font.BOLD); Font font8Red = new Font(bfChinese, 8, Font.NORMAL); font8Red.setColor(Color.RED); Font font8Green = new Font(bfChinese, 8, Font.NORMAL); font8Green.setColor(Color.GREEN); logger.info("Starting build document..."); Document document = new Document(PageSize.A4, 36, 36, 36, 36); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path)); document.open(); LINECANVAS border = new LINECANVAS(); // float[] widths = { 0.1f, 0.35f, 0.55f }; PdfPTable table = new PdfPTable(widths); table.setWidthPercentage(100); table.getDefaultCell().setBorder(PdfPCell.NO_BORDER); table.getDefaultCell().setFixedHeight(12); //CELL PdfPCell cellMchntId = new PdfPCell(new Paragraph("XXXXXXXXXXXXXXX", font8)); cellMchntId.setBorder(PdfPCell.BOTTOM); cellMchntId.setHorizontalAlignment(Element.ALIGN_CENTER); PdfPCell cellMchntName = new PdfPCell(new Paragraph("?", font8)); cellMchntName.setBorder(PdfPCell.BOTTOM); cellMchntName.setHorizontalAlignment(Element.ALIGN_CENTER); // Image img = Image.getInstance( ServletActionContext.getServletContext().getResource("/ext/resources/images/Title_logo.gif")); img.scalePercent(70); float w = img.getScaledWidth(); float h = img.getScaledHeight(); writer.getDirectContent().addImage(img, w, 0, 0, h, 36, PageSize.A4.getHeight() - 36 - h); // PdfPCell cell = new PdfPCell(new Paragraph("?", font17)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setColspan(3); cell.setFixedHeight(h); cell.setBorder(PdfPCell.NO_BORDER); table.addCell(cell); cell = new PdfPCell(); cell.setFixedHeight(20); cell.setColspan(3); cell.setBorder(PdfPCell.NO_BORDER); table.addCell(cell); table.addCell(new Paragraph("?", font8)); table.addCell(cellMchntId); table.addCell(" "); table.addCell(new Paragraph("??", font8)); table.addCell(cellMchntName); table.addCell(" "); document.add(table); document.add(new Paragraph("\n\n")); //? PdfPTable t = new PdfPTable(1); Iterator<Object[]> it0 = list.iterator(); int i = 1; while (it0.hasNext()) { Object[] obj = it0.next(); PdfPCell c = new PdfPCell(); c.addElement(new Paragraph("Q" + String.valueOf(i++) + "" + obj[1].toString(), font10Bold)); List<Object[]> opts = map.get(obj[0].toString()); String opt = ""; Iterator<Object[]> it1 = opts.iterator(); while (it1.hasNext()) { Object[] o = it1.next(); opt += " "; opt += o[1].toString(); opt += " "; } c.addElement(new Paragraph(opt.trim(), font10)); c.setBorder(PdfPCell.NO_BORDER); if (i - 1 != list.size()) { c.setCellEvent(border); } t.addCell(c); } PdfPTable oTable = new PdfPTable(1); oTable.setWidthPercentage(100); PdfPCell ce = new PdfPCell(t); ce.setBorderColor(Color.GRAY); oTable.addCell(ce); document.add(oTable); document.close(); logger.info("Finish build document..."); }
From source file:com.aripd.clms.service.ContractServiceBean.java
@Override public void generatePdf(ContractEntity contract) { String baseFontUrl = "/fonts/Quivira.otf"; FontFactory.register(baseFontUrl);//from ww w .j a v a 2s .co m ByteArrayOutputStream output = new ByteArrayOutputStream(); try { BaseFont bf = BaseFont.createFont(baseFontUrl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font18n = new Font(bf, 18, Font.NORMAL); Font font12n = new Font(bf, 12, Font.NORMAL); Font font8n = new Font(bf, 8, Font.NORMAL); Font font8nbu = new Font(bf, 8, Font.BOLD | Font.UNDERLINE); Font font8ng = new Font(bf, 8, Font.NORMAL, Color.DARK_GRAY); Font font6n = new Font(bf, 6, Font.NORMAL); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, output); document.open(); addMetaData(document); addTitlePage(document, contract); Image imgBlue = Image.getInstance(1, 1, 3, 8, new byte[] { (byte) 0, (byte) 0, (byte) 255, }); imgBlue.scaleAbsolute(document.getPageSize().getWidth(), 10); imgBlue.setAbsolutePosition(0, document.getPageSize().getHeight() - imgBlue.getScaledHeight()); PdfImage stream = new PdfImage(imgBlue, "", null); stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789")); PdfIndirectObject ref = writer.addToBody(stream); imgBlue.setDirectReference(ref.getIndirectReference()); document.add(imgBlue); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100); PdfPCell cell = new PdfPCell(new Paragraph(contract.getName(), font18n)); cell.setBorder(Rectangle.NO_BORDER); cell.setColspan(2); cell.setPadding(5); table.addCell(cell); cell = new PdfPCell(new Paragraph("Version: " + contract.getVersion(), font8n)); cell.setBorder(Rectangle.NO_BORDER); cell.setColspan(2); cell.setPadding(5); table.addCell(cell); cell = new PdfPCell(new Paragraph("Review: " + contract.getReview(), font8n)); cell.setBorder(Rectangle.NO_BORDER); cell.setColspan(2); cell.setPadding(5); table.addCell(cell); cell = new PdfPCell(new Paragraph(contract.getRemark(), font12n)); cell.setBorder(Rectangle.NO_BORDER); cell.setColspan(2); cell.setPadding(5); table.addCell(cell); document.add(table); // Start a new page document.newPage(); HTMLWorker htmlWorker = new HTMLWorker(document); htmlWorker.parse(new StringReader(contract.getRemark())); // Start a new page document.newPage(); document.add(new Paragraph("Review Board", font18n)); document.add(new LineSeparator(0.5f, 100, null, 0, -5)); table = new PdfPTable(3); table.setWidthPercentage(100); cell = new PdfPCell(new Paragraph("Review Board", font18n)); cell.setColspan(3); table.addCell(cell); cell = new PdfPCell(new Paragraph("Version", font12n)); table.addCell(cell); cell = new PdfPCell(new Paragraph("Date", font12n)); table.addCell(cell); cell = new PdfPCell(new Paragraph("Review", font12n)); table.addCell(cell); for (HistoryContractEntity history : historyContractService.listing(contract)) { cell = new PdfPCell(new Paragraph(history.getVersion().toString(), font8n)); table.addCell(cell); cell = new PdfPCell(new Paragraph(history.getStartdate().toString(), font8n)); table.addCell(cell); cell = new PdfPCell(new Paragraph(history.getReview(), font8n)); table.addCell(cell); } document.add(table); document.close(); FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.reset(); response.addHeader("Content-Type", "application/force-download"); String filename = URLEncoder.encode(contract.getName() + ".pdf", "UTF-8"); // response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + filename); response.getOutputStream().write(output.toByteArray()); response.getOutputStream().flush(); context.responseComplete(); context.renderResponse(); } catch (BadPdfFormatException | IOException ex) { Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.aripd.clms.service.ContractServiceBean.java
private static void addTitlePage(Document document, ContractEntity contract) throws DocumentException { Paragraph preface = new Paragraph(); // We add one empty line addEmptyLine(preface, 1);/*from ww w . j a v a 2 s . c om*/ // Lets write a big header preface.add(new Paragraph(contract.getName())); addEmptyLine(preface, 1); // Will create: Report generated by: _name, _date preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date())); addEmptyLine(preface, 3); preface.add(new Paragraph("This document describes something which is very important ")); addEmptyLine(preface, 8); preface.add( new Paragraph("This document is a preliminary version and not subject to your license agreement.")); document.add(preface); // Start a new page document.newPage(); }
From source file:com.aryjr.nheengatu.pdf.PDFDocument.java
License:Open Source License
public void generateFile(final OutputStream out) throws IOException { final Document document; if (styleSheet == null || styleSheet.getStyles() == null || !styleSheet.getStyles().containsKey("@page")) { document = new Document(PageSize.A4); document.setMargins(3.0f * PDFDocument.CM_UNIT, 2.0f * PDFDocument.CM_UNIT, 1.0f * PDFDocument.CM_UNIT, 2.0f * PDFDocument.CM_UNIT); System.out.println("Processamento: terminou setMargins"); } else {//www . j av a2s. c om Style style = ((Style) (styleSheet.getStyles().get("@page"))); if ("landscape".equals(style.getPropertyValue("size"))) { document = new Document(PageSize.A4.rotate()); } else { document = new Document(PageSize.A4); } String s = style.getPropertyValue("margin-left"); Float f = styleMeasure(s, "3cm"); document.setMargins(styleMeasure(style.getPropertyValue("margin-left"), "3cm"), styleMeasure(style.getPropertyValue("margin-right"), "2cm"), styleMeasure(style.getPropertyValue("margin-top"), "1cm"), styleMeasure(style.getPropertyValue("margin-bottom"), "2cm")); System.out.println("Processamento: terminou setMargins do else"); } try { final PdfWriter writer = PdfWriter.getInstance(document, out); writer.setPageEvent(new PDFPageBreak(writer, document, headFirstPage, footFirstPage, head, foot)); document.open(); final MultiColumnText mct = new MultiColumnText(); // set up 3 even columns with 10pt space between mct.addRegularColumns(document.left(), document.right(), 0f, 1); System.out.println("Processamento: prestes a extract visible components"); // Extracting the document content extractVisibleComponents(body, document, mct, null, null); document.add(mct); document.close(); } catch (final DocumentException de) { System.err.println(de.getMessage()); } }
From source file:com.aryjr.nheengatu.pdf.PDFDocument.java
License:Open Source License
private void extractVisibleComponents(final Tag tag, final Document doc, final MultiColumnText mct, final Paragraph paragraph, final List list) throws DocumentException { final Iterator tags = tag.tags(); Object component;//from ww w.j a va2 s .c om Image image; PDFTable table; final TagsManager tm = TagsManager.getInstance(); PDFDocument.log.info("extractVisibleComponents"); // PDFDocument.log.info(tm.states.size()); // PDFDocument.log.info(tm.getTextIndent()); // if (paragraph != null) // PDFDocument.log.info(paragraph.getFirstLineIndent()); while (tags.hasNext()) { component = tags.next(); if (component instanceof Text) { System.out.println("Processamento: Iniciou while -> if instanceof text"); String s = ((Text) component).getText(); if (s.contains("\\\"")) { s = s.replace("\\\"", "\""); ((Text) component).setText(s); } PDFDocument.log.info("text: " + ((Text) component).getText()); // PDFDocument.log.info(tm.states.size()); // PDFDocument.log.info(tm.getTextIndent()); // PDFDocument.log.info(tm.getSpacingBefore()); // PDFDocument.log.info(tm.getSpacingAfter()); // If it's a text, create a iText text component for it if (paragraph != null) paragraph.add(PDFText.createChunk((Text) component)); else if (list != null) list.add(PDFText.createParagraph((Text) component, tm)); else mct.addElement(PDFText.createParagraph((Text) component, tm)); System.out.println("Processamento: terminou while -> if instanceof text"); } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("br")) { // PDFDocument.log.info("br"); // PDFDocument.log.info(tm.states.size()); // PDFDocument.log.info(tm.getTextIndent()); // If it's a HTML line break if (paragraph == null) { mct.addElement(new Paragraph("\n")); } else { paragraph.add("\n"); } System.out.println("Processamento: Iniciou while -> if instanceof tag br"); } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("p")) { // If it's a HTML paragraph, create a iText paragraph for it tm.checkTag((Tag) component); final Paragraph p = PDFText.createParagraph(null, tm); PDFDocument.log.info("p"); PDFDocument.log.info(tm.getFont().getSize()); PDFDocument.log.info(p.getLeading()); // PDFDocument.log.info(tm.states.size()); // PDFDocument.log.info(tm.getTextIndent()); // PDFDocument.log.info("align:"); // PDFDocument.log.info(((Tag) // component).getPropertyValue("align")); // PDFDocument.log.info(tm.getAlign()); // Paragraph p = new Paragraph(); // p.setAlignment(tm.getAlign()); // p.setKeepTogether(true); // // float b = tm.getSpacingBefore(); // // float a = tm.getSpacingAfter(); // p.setSpacingBefore(tm.getSpacingBefore()); // p.setSpacingAfter(tm.getSpacingAfter()); // p.setFirstLineIndent(tm.getTextIndent()); extractVisibleComponents((Tag) component, doc, mct, p, list); if (paragraph != null) paragraph.add(p); else mct.addElement(p); // String align = ((Tag) component).getPropertyValue("align"); // if (align != null) { // p.setAlignment(align.toLowerCase()); // } tm.back(); System.out.println("Processamento: Iniciou while -> if instanceof tag p"); } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("ol")) { // If it's a HTML paragraph, create a iText paragraph for it tm.checkTag((Tag) component); if (tm.getListStyleType() == null) { ((GraphicsState) tm.states.get(tm.states.size() - 1)).setListStyleType("upper-roman"); } else if (tm.getListStyleType().equals("upper-roman")) { ((GraphicsState) tm.states.get(tm.states.size() - 1)).setListStyleType("lower-alpha"); } final List l = new RomanList(tm.getListStyleType(), 30); if (list != null) list.add(l); else mct.addElement(l); extractVisibleComponents((Tag) component, doc, mct, null, l); tm.back(); System.out.println("Processamento: Iniciou while -> if instanceof tag ol"); } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("ul")) { // If it's a HTML paragraph, create a iText paragraph for it final List l = new List(false, false, 20.0f); tm.checkTag((Tag) component); if (paragraph != null) paragraph.add(l); else mct.addElement(l); extractVisibleComponents((Tag) component, doc, mct, null, l); tm.back(); System.out.println("Processamento: Iniciou while -> if instanceof tag ul"); } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("li")) { // If it's a HTML paragraph, create a iText paragraph for it final ListItem li = new ListItem(tm.getFont().getSize() * 1.25f); li.setSpacingAfter(tm.getFont().getSize() * 0.5f); PDFDocument.log.info("li"); PDFDocument.log.info(tm.getFont().getSize()); PDFDocument.log.info(li.getLeading()); tm.checkTag((Tag) component); if (list == null) mct.addElement(li); else list.add(li); extractVisibleComponents((Tag) component, doc, mct, li, list); tm.back(); } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("img")) { // If it's a HTML image, create a iText image component for it try { // TODO the image path can't be static image = PDFImage.createImage((Tag) component); if (paragraph == null) { mct.addElement(image); } else { paragraph.add(image); } } catch (final Exception e) { e.printStackTrace(); } System.out.println("Processamento: Iniciou while -> if instanceof tag img"); } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("table")) { // If it's a HTML table, create a iText table component for it try { table = PDFTable.createTable((Tag) component); mct.addElement(table); } catch (final Exception e) { e.printStackTrace(); } } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("div")) { final String s = ((Tag) component).getPropertyValue("style"); if (s != null && s.equals("PAGE-BREAK-AFTER: always")) { doc.add(mct); mct.nextColumn(); } tm.checkTag((Tag) component); extractVisibleComponents((Tag) component, doc, mct, paragraph, list); tm.back(); System.out.println("Processamento: Iniciou while -> if instanceof tag div"); } else { // If it's an another tag, check the name and call this method // again // PDFDocument.log.info("other!"); // PDFDocument.log.info(tm.states.size()); // PDFDocument.log.info(tm.getTextIndent()); tm.checkTag((Tag) component); extractVisibleComponents((Tag) component, doc, mct, paragraph, list); tm.back(); System.out.println("Processamento: Iniciou while -> else if"); } } }
From source file:com.aurel.track.util.PdfUtils.java
License:Open Source License
public static void createPdfFromText(StringBuilder text, File pdfFile) { Document output = null; try {/*from ww w .j a v a2s . c o m*/ BufferedReader input = new BufferedReader(new StringReader(text.toString())); // Size DIN A4 // see com.lowagie.text.PageSize for a complete list of page-size constants. output = new Document(PageSize.A4, 40, 40, 40, 40); float fntSize, lineSpacing; fntSize = 9f; lineSpacing = 11f; Font font1 = FontFactory.getFont(FontFactory.COURIER, fntSize); Font font2 = FontFactory.getFont(FontFactory.COURIER, fntSize); font2.setColor(Color.BLUE); Font font3 = FontFactory.getFont(FontFactory.COURIER, fntSize); font3.setColor(Color.RED); PdfWriter.getInstance(output, new FileOutputStream(pdfFile)); output.open(); output.addAuthor("Steinbeis"); output.addSubject("Debug Info"); output.addTitle(pdfFile.getName()); String line = ""; while (null != (line = input.readLine())) { Font ft = font1; if (line.startsWith("%")) { ft = font2; } if (line.startsWith("% ^^^") || line.startsWith("% vvv")) { ft = font3; } Paragraph p = new Paragraph(lineSpacing, line, ft); p.setAlignment(Element.ALIGN_JUSTIFIED); output.add(p); } output.close(); input.close(); } catch (Exception e) { LOGGER.debug("Problem creating debug info pdf file", e); } }
From source file:com.bean.UserBean.java
public void gerarPDF1() { try {/*from ww w . j av a 2s . c om*/ Document doc = new Document(PageSize.A4); OutputStream os = new FileOutputStream("C:/Users/lprates/Downloads/out.pdf"); PdfWriter.getInstance(doc, os); doc.open(); Paragraph p = new Paragraph("Meu primeiro arquivo PDF!"); doc.add(p); doc.close(); os.close(); //abre pdf usando o PDF Reader instalado na maquina do Usuario Desktop.getDesktop().open(new File("C:/Users/lprates/Downloads/out.pdf")); } catch (Exception e) { } }
From source file:com.bean.UserBean.java
public void gerarPDF2() { try {//from ww w. jav a 2 s . co m Document doc = new Document(); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter docWriter = null; docWriter = PdfWriter.getInstance(doc, baosPDF); doc.open(); doc.add(new Paragraph("This document was created by a class named: " + this.getClass().getName())); doc.add(new Paragraph("This document was created on " + new java.util.Date())); doc.close(); docWriter.close(); FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); externalContext.setResponseContentType("application/pdf"); // com a opcao inline abre o PDF no browser do usuario //externalContext.setResponseHeader("Content-Disposition", "inline; filename=\"my.pdf\""); // com a opcao attachment faz download do PDF no computador do usuario externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"my.pdf\""); OutputStream responseOutputStream = externalContext.getResponseOutputStream(); baosPDF.writeTo(responseOutputStream); responseOutputStream.flush(); baosPDF.reset(); facesContext.responseComplete(); } catch (Exception e) { } }
From source file:com.bytecode.customexporter.PDFCustomExporter.java
@Override public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle, boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor, MethodExpression postProcessor, boolean subTable) throws IOException { try {// w w w . ja va2 s. co m Document document = new Document(); if (orientation.equalsIgnoreCase("Landscape")) document.setPageSize(PageSize.A4.rotate()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); StringTokenizer st = new StringTokenizer(tableId, ","); while (st.hasMoreElements()) { String tableName = (String) st.nextElement(); UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(), tableName); if (component == null) { throw new FacesException("Cannot find component \"" + tableName + "\" in view."); } if (!(component instanceof DataTable || component instanceof DataList)) { throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName() + "\", exporter must target a PrimeFaces DataTable/DataList."); } if (preProcessor != null) { preProcessor.invoke(context.getELContext(), new Object[] { document }); } if (!document.isOpen()) { document.open(); } if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) { Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE, Font.BOLD); Paragraph title = new Paragraph(tableTitle, tableTitleFont); document.add(title); Paragraph preface = new Paragraph(); addEmptyLine(preface, 3); document.add(preface); } PdfPTable pdf; DataList list = null; DataTable table = null; if (component instanceof DataList) { list = (DataList) component; pdf = exportPDFTable(context, list, pageOnly, encodingType); } else { table = (DataTable) component; pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable); } if (pdf != null) { document.add(pdf); } // add a couple of blank lines Paragraph preface = new Paragraph(); addEmptyLine(preface, datasetPadding); document.add(preface); if (postProcessor != null) { postProcessor.invoke(context.getELContext(), new Object[] { document }); } } document.close(); writePDFToResponse(context.getExternalContext(), baos, filename); } catch (DocumentException e) { throw new IOException(e.getMessage()); } }
From source file:com.byterefinery.rmbench.export.diagram.PDFDiagramExporter.java
License:Open Source License
protected void doExport(OutputStream out, IFigure figure) { Rectangle bounds = getBounds(figure); Document document = new Document(new com.lowagie.text.Rectangle(bounds.width, bounds.height)); PdfWriter pdf;//from w ww .j a va 2s . co m try { pdf = PdfWriter.getInstance(document, out); document.open(); document.add(new Chunk(" ")); } catch (DocumentException e) { ExportPlugin.logError(e); return; } PdfContentByte contentbytes = pdf.getDirectContent(); PdfTemplate template = contentbytes.createTemplate(bounds.width, bounds.height); Graphics2D graphics2d = template.createGraphics(bounds.width, bounds.height); try { GraphicsToGraphics2DAdaptor graphics = new GraphicsToGraphics2DAdaptor(graphics2d, bounds.getTranslated(bounds.getLocation().negate())); graphics.translate(bounds.getLocation().negate()); figure.paint(graphics); } finally { graphics2d.dispose(); contentbytes.addTemplate(template, 0, 0); document.close(); } }