public void write(PDFDocument document, PdfPTable tabla) throws DocumentException { com.lowagie.text.List list = new com.lowagie.text.List(false,10f); list.setListSymbol(new Chunk("\u2022")); PdfPCell cell = new PdfPCell(); if(!titulo.equals("")) { cell.addElement(new Phrase(titulo,document.getContext().getDefaultFont())); } for(int i=0; i<campos.size(); i++) { list.add(new ListItem((String)campos.get(i),document.getContext().getDefaultFont())); } cell.addElement(list); cell.setPaddingLeft(30f); cell.setBorder(Rectangle.LEFT | Rectangle.RIGHT); cell.setColspan(2); tabla.addCell(cell); }
@Override public void onEndPage(PdfWriter writer, Document document) { Phrase[] headers = new Phrase[3]; PdfContentByte cb = writer.getDirectContent(); headers[0] = new Phrase("CuacFM"); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, headers[0], document.left() + 80, document.bottom() - 20, 0); Date day = new Date(); headers[1] = new Phrase(DateUtils.format(day, DateUtils.FORMAT_LOCAL)); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, headers[1], (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 20, 0); headers[2] = new Phrase(String.format("Página %d", writer.getCurrentPageNumber())); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, headers[2], document.right() - 80, document.bottom() - 20, 0); }
/** * Constructs a <CODE>PdfPCell</CODE> with an <CODE>Image</CODE>. * The default padding is 0.25 for a border width of 0.5. * * @param image the <CODE>Image</CODE> * @param fit <CODE>true</CODE> to fit the image to the cell */ public PdfPCell(Image image, boolean fit) { super(0, 0, 0, 0); borderWidth = 0.5f; border = BOX; if (fit) { this.image = image; column.setLeading(0, 1); setPadding(borderWidth / 2); } else { column.addText(this.phrase = new Phrase(new Chunk(image, 0, 0))); column.setLeading(0, 1); setPadding(0); } }
/** * Constructs a RtfHeaderFooterGroup by copying the content of the original * RtfHeaderFooterGroup * * @param doc The RtfDocument this RtfHeaderFooter belongs to * @param headerFooter The RtfHeaderFooterGroup to copy * @param type The type of RtfHeaderFooterGroup to create */ public RtfHeaderFooterGroup(RtfDocument doc, RtfHeaderFooterGroup headerFooter, int type) { super(new Phrase(""), false); this.document = doc; this.mode = headerFooter.getMode(); this.type = type; if(headerFooter.getHeaderAll() != null) { this.headerAll = new RtfHeaderFooter(this.document, headerFooter.getHeaderAll(), RtfHeaderFooter.DISPLAY_ALL_PAGES); } if(headerFooter.getHeaderFirst() != null) { this.headerFirst = new RtfHeaderFooter(this.document, headerFooter.getHeaderFirst(), RtfHeaderFooter.DISPLAY_FIRST_PAGE); } if(headerFooter.getHeaderLeft() != null) { this.headerLeft = new RtfHeaderFooter(this.document, headerFooter.getHeaderLeft(), RtfHeaderFooter.DISPLAY_LEFT_PAGES); } if(headerFooter.getHeaderRight() != null) { this.headerRight = new RtfHeaderFooter(this.document, headerFooter.getHeaderRight(), RtfHeaderFooter.DISPLAY_RIGHT_PAGES); } setType(this.type); }
/** * Constructs a RtfHeaderFooter as a copy of an existing RtfHeaderFooter. * For internal use only. * * @param doc The RtfDocument this RtfHeaderFooter belongs to * @param headerFooter The RtfHeaderFooter to copy * @param displayAt The display location of this RtfHeaderFooter */ protected RtfHeaderFooter(RtfDocument doc, RtfHeaderFooter headerFooter, int displayAt) { super(new Phrase(""), false); this.document = doc; this.content = headerFooter.getContent(); this.displayAt = displayAt; for(int i = 0; i < this.content.length; i++) { if(this.content[i] instanceof Element) { try { this.content[i] = this.document.getMapper().mapElement((Element) this.content[i])[0]; } catch(DocumentException de) { de.printStackTrace(); } } if(this.content[i] instanceof RtfBasicElement) { ((RtfBasicElement) this.content[i]).setInHeader(true); } } }
/** * Creates a Phrase object based on a list of properties. * @param attributes * @return a Phrase */ public static Phrase getPhrase(Properties attributes) { Phrase phrase = new Phrase(); phrase.setFont(FontFactory.getFont(attributes)); String value; value = attributes.getProperty(ElementTags.LEADING); if (value != null) { phrase.setLeading(Float.parseFloat(value + "f")); } value = attributes.getProperty(Markup.CSS_KEY_LINEHEIGHT); if (value != null) { phrase.setLeading(Markup.parseLength(value, Markup.DEFAULT_FONT_SIZE)); } value = attributes.getProperty(ElementTags.ITEXT); if (value != null) { Chunk chunk = new Chunk(value); if ((value = attributes.getProperty(ElementTags.GENERICTAG)) != null) { chunk.setGenericTag(value); } phrase.add(chunk); } return phrase; }
/** * How to substiture special characters with Phrase.getInstance. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: // we create a writer that listens to the document PdfWriter.getInstance(document, PdfTestBase.getOutputStream("SymbolSubstitution.pdf")); // step 3: we open the document document.open(); // step 4: document.add(Phrase.getInstance("What is the " + (char) 945 + "-coefficient of the " + (char) 946 + "-factor in the " + (char) 947 + "-equation?\n")); for (int i = 913; i < 970; i++) { document.add(Phrase.getInstance(" " + i + ": " + (char) i)); } // step 5: we close the document document.close(); }
/** * Using FontSelector. */ @Test public void main() throws Exception { // step 1 Document document = new Document(); // step 2 PdfWriter.getInstance(document, PdfTestBase.getOutputStream("fontselection.pdf")); // step 3 document.open(); // step 4 String text = "This text is the first verse of \u275dThe Iliad\u275e. It's not polytonic as it should be " + "with \u2798 and \u279a entoation variants but that's all we have for now.\n\n" + "\u2766\u00a0\u00a0\u039c\u03b7\u03bd\u03b9\u03bd \u03b1\u03b5\u03b9\u03b4\u03b5, \u03b8\u03b5\u03b1, \u03a0\u03b7\u03bb\u03b7\u03b9\u03b1\u03b4\u03b5\u03c9 \u0391\u03c7\u03b9\u03bb\u03b7\u03bf\u03c2"; FontSelector sel = new FontSelector(); sel.addFont(new Font(Font.TIMES_ROMAN, 12)); sel.addFont(new Font(Font.ZAPFDINGBATS, 12)); sel.addFont(new Font(Font.SYMBOL, 12)); Phrase ph = sel.process(text); document.add(new Paragraph(ph)); // step 5 document.close(); }
/** * Demonstrates what happens if you choose a negative leading. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: // we create a writer that listens to the document PdfWriter.getInstance(document, PdfTestBase.getOutputStream("NegativeLeading.pdf")); // step 3: we open the document document.open(); // step 4: document.add(new Phrase(16, "\n\n\n")); document.add(new Phrase( -16, "Hello, this is a very long phrase to show you the somewhat odd effect of a negative leading. You can write from bottom to top. This is not fully supported. It's something between a feature and a bug.")); // step 5: we close the document document.close(); }
@Test public void testTableSpacingPercentage() throws FileNotFoundException, DocumentException { Document document = PdfTestBase .createPdf("testTableSpacingPercentage.pdf"); document.setMargins(72, 72, 72, 72); document.open(); PdfPTable table = new PdfPTable(1); table.setSpacingBefore(20); table.setWidthPercentage(100); PdfPCell cell; cell = new PdfPCell(); Phrase phase = new Phrase("John Doe"); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // This has no // effect cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // This has no effect cell.addElement(phase); table.addCell(cell); document.add(table); document.close(); }
private static void anadirTextoTabla(PdfPTable tabla, String titulo, String desc) { PdfPCell cell = new PdfPCell(); disableBorders(cell); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.addElement(new Phrase(titulo,fuente10)); tabla.addCell(cell); cell = new PdfPCell(); disableBorders(cell); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.addElement(new Phrase(defaultString(desc),fuente10)); tabla.addCell(cell); }
public void printDocHeaderFooter() throws DocumentException { document.resetHeader(); document.resetFooter(); String headerTitle = "Tickler re: " + tickler.getDemographic().getFormattedName() + " DOB:" + tickler.getDemographic().getFormattedDob(); if (newPage) { document.newPage(); newPage = false; } //Header will be printed at top of every page beginning with p2 Phrase headerPhrase = new Phrase(LEADING, headerTitle, boldFont); getDocument().add(headerPhrase); getDocument().add(new Phrase("\n")); }
private PdfPTable createNeedHeader(String name) throws DocumentException { Font whiteFont = new Font(Font.HELVETICA,14,Font.BOLD,Color.WHITE); PdfPTable table = new PdfPTable(3); table.setWidthPercentage(100); table.setWidths(new float[]{0.10f,0.20f,0.70f}); PdfPCell emptyCell = new PdfPCell(); emptyCell.setBorder(0); table.addCell(emptyCell); PdfPCell headerCell = new PdfPCell(); headerCell.setColspan(2); headerCell.setPhrase(new Phrase(name,whiteFont)); headerCell.setHorizontalAlignment(Element.ALIGN_CENTER); headerCell.setBackgroundColor(Color.LIGHT_GRAY); table.addCell(headerCell); return table; }
private float addDynamicPositionedText(String name, String text, float dynamicHeight, EctConsultationFormRequestUtil reqForm) throws DocumentException { if (text != null && text.length() > 0){ Font boldFont = new Font(bf, FONTSIZE, Font.BOLD); Font font = new Font(bf, FONTSIZE, Font.NORMAL); float lineCount = (name.length() + text.length()) / 100; // if there is not enough room on the page for the text start on the next page if ( (height - 264 - dynamicHeight - lineCount*LINEHEIGHT) < LINEHEIGHT*3 ){ nextPage(reqForm); dynamicHeight = LINEHEIGHT - 152; } ct.setSimpleColumn(new Float(85), height - 264 - dynamicHeight - lineCount*LINEHEIGHT, new Float(526), height - 250 - dynamicHeight, LINEHEIGHT, Element.ALIGN_LEFT); ct.addText(new Phrase(name, boldFont)); ct.addText(new Phrase(text, font)); ct.go(); dynamicHeight += lineCount*LINEHEIGHT + LINEHEIGHT*2; } return dynamicHeight; }
protected void writePageAnchor(int pageIndex) throws DocumentException { Map<Attribute,Object> attributes = new HashMap<Attribute,Object>(); fontUtil.getAttributesWithoutAwtFont(attributes, new JRBasePrintText(jasperPrint.getDefaultStyleProvider())); Font pdfFont = getFont(attributes, getLocale(), false); Chunk chunk = new Chunk(" ", pdfFont); chunk.setLocalDestination(JR_PAGE_ANCHOR_PREFIX + reportIndex + "_" + (pageIndex + 1)); tagHelper.startPageAnchor(); ColumnText colText = new ColumnText(pdfContentByte); colText.setSimpleColumn( new Phrase(chunk), 0, pageFormat.getPageHeight(), 1, 1, 0, Element.ALIGN_LEFT ); colText.go(); tagHelper.endPageAnchor(); }
/** * Checks if there is a parent post. * * @param post * The post. * @param locale * The locale. * @param dateFormatter * Date formatter. * @param resourcesManager * The used ResourceManager. * * @param phrase * The phrase to add the information. */ private void handleParentNote(NoteData post, Locale locale, DateFormat dateFormatter, ResourceBundleManager resourcesManager, Phrase phrase) { if (post.getParent() == null) { return; } phrase.add(RtfElementFactory.createChunk("\n", FONT_META_INFORMATION)); phrase.add(RtfElementFactory.createChunk( resourcesManager.getText("export.post.title.reply.prefix", locale) + ": ", FONT_META_INFORMATION)); String fromAt = resourcesManager.getText("blog.post.list.reply.link", locale, post .getParent().getUser().getFirstName() + " " + post.getParent().getUser().getLastName() + " (" + post.getParent().getUser().getAlias() + ")", dateFormatter.format(post.getParent().getCreationDate())); phrase.add(RtfElementFactory.createChunk(fromAt, FONT_META_INFORMATION)); }
/** * Handles the users to be notified of each post. * * @param list * The post. * @param resourcesManager * The used ResourceManager. * * @param phrase * The phrase to add the information. * @param locale * The locale. */ private void handleUsersToBeNotified(Collection<DetailedUserData> list, Phrase phrase, Locale locale, ResourceBundleManager resourcesManager) { if (list == null || list.isEmpty()) { return; } phrase.add(RtfElementFactory.createChunk("\n", FONT_META_INFORMATION)); phrase.add(RtfElementFactory.createChunk( resourcesManager.getText("export.post.title.users", locale) + ":\t", FONT_META_INFORMATION)); String prefix = ""; for (DetailedUserData user : list) { phrase.add(RtfElementFactory.createChunk( prefix + user.getFirstName() + " " + user.getLastName() + " (" + user.getAlias() + ")", FONT_META_INFORMATION)); prefix = ", "; } }
@Override protected void generateReportBody(Document document, BaseReportDto reportData) throws Exception { SearchesByDateReportDto dto = (SearchesByDateReportDto)reportData; Paragraph p1 = new Paragraph(this.getText("REPORTS_SEARCHES_BY_DATE_TITLE")); p1.setAlignment(Paragraph.ALIGN_CENTER); document.add(p1); document.add(new Phrase("\n")); StringBuilder p2Builder = new StringBuilder(); p2Builder.append(this.getText("REPORTS_FROM") + " "); p2Builder.append(dto.getInitialDate()); p2Builder.append(" " + this.getText("REPORTS_TO") + " "); p2Builder.append(dto.getFinalDate()); Paragraph p2 = new Paragraph(this.getHeaderChunk(p2Builder.toString())); p2.setAlignment(Paragraph.ALIGN_LEFT); document.add(p2); document.add(new Phrase("\n")); if (dto != null) { PdfPTable table = createTable(dto); document.add(table); document.add(new Phrase("\n")); } }
@Override protected void generateReportBody(Document document, BaseReportDto reportData) throws Exception { RequestsByDateReportDto dto = (RequestsByDateReportDto)reportData; Paragraph p1 = new Paragraph(this.getText("REPORTS_REQUESTS_BY_DATE_TITLE")); p1.setAlignment(Paragraph.ALIGN_CENTER); document.add(p1); document.add(new Phrase("\n")); StringBuilder header = new StringBuilder(); header.append(this.getText("REPORTS_FROM")); header.append(" ").append(dto.getInitialDate()).append(" "); header.append(this.getText("REPORTS_TO")); header.append(" ").append(dto.getFinalDate()); Paragraph p2 = new Paragraph(this.getHeaderChunk(header.toString())); p2.setAlignment(Paragraph.ALIGN_LEFT); document.add(p2); document.add(new Phrase("\n")); if (dto.getData() != null) { PdfPTable table = createTable(dto.getData()); document.add(table); document.add(new Phrase("\n")); } }
@Override protected void generateReportBody(Document document, BaseReportDto reportData) throws Exception { DelayedLendingsDto dto = (DelayedLendingsDto)reportData; Paragraph p1 = new Paragraph(this.getText("REPORTS_DELAYED_LENDING_TITLE")); p1.setAlignment(Paragraph.ALIGN_CENTER); document.add(p1); document.add(new Phrase("\n")); if (dto.getData().size() != 0) { Paragraph p2 = new Paragraph(this.getHeaderChunk(this.getText("REPORTS_DELAYED_LENDING_TOTAL") + ": " + dto.getData().size())); p2.setAlignment(Paragraph.ALIGN_LEFT); document.add(p2); document.add(new Phrase("\n")); PdfPTable table = createTable(dto.getData()); document.add(table); document.add(new Phrase("\n")); } }
private void writeGraph() throws IOException, DocumentException { final JRobin jrobin = collector.getJRobin(graphName); if (jrobin != null) { final byte[] img = jrobin.graph(range, 960, 400); final Image image = Image.getInstance(img); image.scalePercent(50); final PdfPTable table = new PdfPTable(1); table.setHorizontalAlignment(Element.ALIGN_CENTER); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell("\n"); table.addCell(image); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(new Phrase(getString("graph_units"), cellFont)); addToDocument(table); } else { // just in case request is null and collector.getJRobin(graphName) is null, we must write something in the document addToDocument(new Phrase("\n", cellFont)); } }
private void writeJndiBinding(JndiBinding jndiBinding) throws BadElementException, IOException { final PdfPCell defaultCell = getDefaultCell(); defaultCell.setHorizontalAlignment(Element.ALIGN_LEFT); final String name = jndiBinding.getName(); final String className = jndiBinding.getClassName(); final String contextPath = jndiBinding.getContextPath(); final String value = jndiBinding.getValue(); if (contextPath != null) { final Image image = getFolderImage(); final Phrase phrase = new Phrase("", cellFont); phrase.add(new Chunk(image, 0, 0)); phrase.add(" "); phrase.add(name); addCell(phrase); } else { addCell(name); } addCell(className != null ? className : ""); addCell(value != null ? value : ""); }
private void writeMemoryInformations(MemoryInformations memoryInformations) throws BadElementException, IOException { addCell(memoryInformations.getMemoryDetails().replace(" Mo", ' ' + getString("Mo"))); final long usedPermGen = memoryInformations.getUsedPermGen(); if (usedPermGen > 0) { // perm gen est à 0 sous jrockit final long maxPermGen = memoryInformations.getMaxPermGen(); addCell(getString("Memoire_Perm_Gen") + ':'); if (maxPermGen > 0) { final Phrase permGenPhrase = new Phrase( integerFormat.format(usedPermGen / 1024 / 1024) + ' ' + getString("Mo") + DIVIDE + integerFormat.format(maxPermGen / 1024 / 1024) + ' ' + getString("Mo") + BAR_SEPARATOR, cellFont); final Image permGenImage = Image.getInstance( Bar.toBarWithAlert(memoryInformations.getUsedPermGenPercentage()), null); permGenImage.scalePercent(50); permGenPhrase.add(new Chunk(permGenImage, 0, 0)); currentTable.addCell(permGenPhrase); } else { addCell(integerFormat.format(usedPermGen / 1024 / 1024) + ' ' + getString("Mo")); } } }
public void writeThreads(List<JavaInformations> javaInformationsList) throws IOException { try { document.open(); addParagraph(getString("Threads"), "threads.png"); String eol = ""; final Font normalFont = PdfFonts.NORMAL.getFont(); for (final JavaInformations javaInformations : javaInformationsList) { addToDocument(new Phrase(eol, normalFont)); final PdfThreadInformationsReport pdfThreadInformationsReport = new PdfThreadInformationsReport( javaInformations.getThreadInformationsList(), javaInformations.isStackTraceEnabled(), pdfDocumentFactory, document); pdfThreadInformationsReport.writeIntro(javaInformations); pdfThreadInformationsReport.writeDeadlocks(); pdfThreadInformationsReport.toPdf(); eol = "\n"; } } catch (final DocumentException e) { throw createIOException(e); } document.close(); }
Element createParagraphElement(String paragraphTitle, String iconName) throws DocumentException, IOException { final Paragraph paragraph = new Paragraph("", paragraphTitleFont); paragraph.setSpacingBefore(5); paragraph.setSpacingAfter(5); if (iconName != null) { paragraph.add(new Chunk(getParagraphImage(iconName), 0, -5)); } final Phrase element = new Phrase(' ' + paragraphTitle, paragraphTitleFont); element.setLeading(12); paragraph.add(element); // chapter pour avoir la liste des signets final ChapterAutoNumber chapter = new ChapterAutoNumber(paragraph); // sans numéro de chapitre chapter.setNumberDepth(0); chapter.setBookmarkOpen(false); chapter.setTriggerNewPage(false); return chapter; }
private List<PdfCounterRequestContextReport> writeCurrentRequests( JavaInformations javaInformations, List<Counter> counters, List<PdfCounterReport> pdfCounterReports) throws IOException, DocumentException { final List<PdfCounterRequestContextReport> pdfCounterRequestContextReports = new ArrayList<PdfCounterRequestContextReport>(); final List<CounterRequestContext> rootCurrentContexts; if (currentRequests == null) { rootCurrentContexts = collector.getRootCurrentContexts(counters); } else { rootCurrentContexts = currentRequests; } if (rootCurrentContexts.isEmpty()) { addToDocument(new Phrase(getString("Aucune_requete_en_cours"), normalFont)); } else { final PdfCounterRequestContextReport pdfCounterRequestContextReport = new PdfCounterRequestContextReport( rootCurrentContexts, pdfCounterReports, javaInformations.getThreadInformationsList(), javaInformations.isStackTraceEnabled(), pdfDocumentFactory, getDocument()); pdfCounterRequestContextReport.toPdf(); pdfCounterRequestContextReports.add(pdfCounterRequestContextReport); } return pdfCounterRequestContextReports; }
private void writeThreads(boolean includeDetails) throws DocumentException, IOException { String eol = ""; for (final JavaInformations javaInformations : javaInformationsList) { addToDocument(new Phrase(eol, normalFont)); final PdfThreadInformationsReport pdfThreadInformationsReport = new PdfThreadInformationsReport( javaInformations.getThreadInformationsList(), javaInformations.isStackTraceEnabled(), pdfDocumentFactory, getDocument()); pdfThreadInformationsReport.writeIntro(javaInformations); pdfThreadInformationsReport.writeDeadlocks(); if (includeDetails) { pdfThreadInformationsReport.toPdf(); } eol = "\n"; } }
private void writeCaches(boolean includeDetails) throws DocumentException { String eol = ""; for (final JavaInformations javaInformations : javaInformationsList) { if (!javaInformations.isCacheEnabled()) { continue; } final List<CacheInformations> cacheInformationsList = javaInformations .getCacheInformationsList(); final String msg = getFormattedString("caches_sur", cacheInformationsList.size(), javaInformations.getHost(), javaInformations.getCurrentlyExecutingJobCount()); addToDocument(new Phrase(eol + msg, boldFont)); if (includeDetails) { new PdfCacheInformationsReport(cacheInformationsList, getDocument()).toPdf(); } eol = "\n"; } }
private void writeJobs(Counter rangeJobCounter, boolean includeDetails) throws DocumentException, IOException { String eol = ""; for (final JavaInformations javaInformations : javaInformationsList) { if (!javaInformations.isJobEnabled()) { continue; } final List<JobInformations> jobInformationsList = javaInformations .getJobInformationsList(); final String msg = getFormattedString("jobs_sur", jobInformationsList.size(), javaInformations.getHost(), javaInformations.getCurrentlyExecutingJobCount()); addToDocument(new Phrase(eol + msg, boldFont)); if (includeDetails) { new PdfJobInformationsReport(jobInformationsList, rangeJobCounter, getDocument()) .toPdf(); } eol = "\n"; } }
private void writeDurationAndOverhead() throws DocumentException { final long displayDuration = System.currentTimeMillis() - start; final String tmp = "\n\n" + getString("temps_derniere_collecte") + ": " + collector.getLastCollectDuration() + ' ' + getString("ms") + '\n' + getString("temps_affichage") + ": " + displayDuration + ' ' + getString("ms") + '\n' + getString("Estimation_overhead_memoire") + ": < " + (collector.getEstimatedMemorySize() / 1024 / 1024 + 1) + ' ' + getString("Mo") + '\n' + getString("Usage_disque") + ": " + (collector.getDiskUsage() / 1024 / 1024 + 1) + ' ' + getString("Mo"); final String string; if (Parameters.JAVAMELODY_VERSION != null) { string = tmp + "\n\n" + "JavaMelody " + Parameters.JAVAMELODY_VERSION; } else { string = tmp; } addToDocument(new Phrase(string, cellFont)); }
/** * We create a writer that listens to the document and directs a PDF-stream to out * * @param table * MBasicTable * @param document * Document * @param out * OutputStream * @return DocWriter * @throws DocumentException * e */ protected DocWriter createWriter(final MBasicTable table, final Document document, final OutputStream out) throws DocumentException { final PdfWriter writer = PdfWriter.getInstance(document, out); // writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft); // title if (table.getName() != null) { final HeaderFooter header = new HeaderFooter(new Phrase(table.getName()), false); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); document.addTitle(table.getName()); } // simple page numbers : x // HeaderFooter footer = new HeaderFooter(new Phrase(), true); // footer.setAlignment(Element.ALIGN_RIGHT); // footer.setBorder(Rectangle.TOP); // document.setFooter(footer); // add the event handler for advanced page numbers : x/y writer.setPageEvent(new AdvancedPageNumberEvents()); return writer; }
@Override public void installApiTypeDocs(List<ApiTypeDoc> apiTypeDocs) throws Exception { Paragraph paRefType = new Paragraph(chFont.process("引用类型参考\n")); Chapter chapter = new Chapter(paRefType, categoryChapters.size()+1); for (ApiTypeDoc apiTypeDoc : apiTypeDocs) { Phrase chunk = secFont.process(apiTypeDoc.getName()); ItextUtil.setLocalDestination(chunk, REFTYPE_LINK_PREFIX + apiTypeDoc.getName()); Section section = chapter.addSection(new Paragraph(chunk)); section.setIndentation(10); section.setIndentationLeft(10); section.setBookmarkOpen(false); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); //desc section.add(new Paragraph(textFont.process(apiTypeDoc.getDesc()))); //属性 addTypeAttrs(section, apiTypeDoc.getAttrs()); } document.add(chapter); }
/** * Renders the contents of the report. * * @param response the report data * @param document the current report document * @throws DocumentException for any other errors encountered */ private void renderItems(ChangeHistoryReportResponse response, Document document) throws DocumentException { // generate header table Table table = new Table(3); table.setBorder(Table.TOP | Table.BOTTOM | Table.LEFT | Table.RIGHT); Cell cell = new Cell(); cell.setBorder(Cell.LEFT); table.setDefaultCell(cell); table.setWidth(100); table.setPadding(1); table.addCell(new Phrase("CSD #" + response.getCsd(), ReportHelper.TABLE_HEADER_FONT)); table.addCell(new Phrase(ReportHelper.formatDate(response.getBirthDay()), ReportHelper.TABLE_HEADER_FONT)); table.addCell(new Phrase(response.getClaimName(), ReportHelper.TABLE_HEADER_FONT)); document.add(table); Map<GroupingKey, List<ChangeHistoryReportResponseItem>> groups = groupItems(response); Set<GroupingKey> keySet = groups.keySet(); for (GroupingKey groupingKey : keySet) { renderGroup(document, groupingKey, groups.get(groupingKey)); } if (response.getItems().isEmpty()) { document.add(new Paragraph("There are no changes on record.", ReportHelper.TABLE_DATA_FONT)); } }
/** * Renders all the records that are part of a group. * * @param document the current report * @param groupingKey the grouping key * @param list the items in the group * @throws DocumentException for any errors encountered */ private void renderGroup(Document document, GroupingKey groupingKey, List<ChangeHistoryReportResponseItem> list) throws DocumentException { Table table = new Table(1); table.setBorder(Table.NO_BORDER); Cell cell = new Cell(); cell.setBorder(Cell.NO_BORDER); table.setDefaultCell(cell); table.setWidth(100); table.setPadding(1); // table header and column widths table.setWidths(new float[] {100}); String groupLabel = "{0} {1}"; String groupHeader = MessageFormat.format(groupLabel, groupingKey.date, groupingKey.user); Cell headerCell = new Cell(new Phrase(groupHeader, ReportHelper.TABLE_HEADER_FONT)); headerCell.setBorder(Cell.BOTTOM); table.addCell(headerCell); for (ChangeHistoryReportResponseItem row : list) { table.addCell(new Phrase(row.getDescription(), ReportHelper.TABLE_DATA_FONT)); } document.add(table); document.add(new Phrase(" ")); // spacer }
/** * Renders the summary of adjustments. * * @param document the current document * @param userChangeCount the map representing the number of changes per user * @param userAccounts the map representing the number of accounts per user * @throws DocumentException for any errors encountered */ private void renderSummary(Document document, Map<String, Integer> userChangeCount, Map<String, Set<String>> userAccounts) throws DocumentException { Table table = new Table(1); table.setBorder(Table.TOP | Table.LEFT | Table.BOTTOM); Cell cell = new Cell(); cell.setBorder(Cell.NO_BORDER); table.setDefaultCell(cell); table.setWidth(100); table.setPadding(1); // table header and column widths table.setWidths(new float[] {100}); String groupLabel = "{0} made {1} changes to {2} accounts during this reporting period."; for (Map.Entry<String, Integer> user : userChangeCount.entrySet()) { Set<String> accountsModified = userAccounts.get(user.getKey()); String userSummary = MessageFormat.format(groupLabel, user.getKey(), user.getValue(), accountsModified.size()); table.addCell(new Phrase(userSummary, ReportHelper.TABLE_DATA_FONT)); } document.add(table); }
/** * Renders the grand total. * @param response the response object * @param document the document report * @throws DocumentException may be thrown by the iText library while rendering the elements */ private void renderGrandTotal(PaymentPendingApprovalReportResponse response, Document document) throws DocumentException { Table table = new Table(2); table.setWidths(new float[]{80, 20}); table.setBorder(Table.NO_BORDER); table.setWidth(40); table.setPadding(1); Cell cell = new Cell(new Phrase("Grand Total", ReportHelper.TABLE_HEADER_FONT)); cell.setBorder(Cell.BOTTOM); cell.setBorderWidth(1f); table.addCell(cell); Cell subTotal = new Cell(new Phrase(response.getItems().size() + "", ReportHelper.TABLE_HEADER_FONT)); subTotal.setBorder(Cell.BOTTOM); subTotal.setBorderWidth(1f); table.addCell(subTotal); document.add(table); }
/** * Render grouping. * @param response The response object * @param document The document report * @throws DocumentException may be thrown by the iText library while rendering the elements */ private void renderGrouping(PaymentPendingApprovalReportResponse response, Document document) throws DocumentException { Table table = new Table(2); table.setWidths(new float[]{80, 20}); table.setBorder(Table.NO_BORDER); table.setWidth(40); table.setPadding(1); Cell cell = new Cell(new Phrase("Recievables Technician", ReportHelper.TABLE_HEADER_FONT)); cell.setBorder(Cell.TOP | Cell.BOTTOM); table.addCell(cell); Cell subTotal = new Cell(new Phrase(response.getItems().size() + "", ReportHelper.TABLE_HEADER_FONT)); subTotal.setBorder(Cell.TOP | Cell.BOTTOM); table.addCell(subTotal); document.add(table); }
/** * Creates a common format header for the reports. * * @param document the report document * @param reportGenerationDate the date of printing * @param reportNameText the name of the report * @return the header to include */ public static HeaderFooter generateSimpleHeader(Document document, Date reportGenerationDate, String reportNameText) { Paragraph header = new Paragraph(); if (reportNameText != null) { Paragraph reportName = new Paragraph(reportNameText, ReportHelper.REPORT_HEADER_FONT); header.add(reportName); } if (reportGenerationDate != null) { Paragraph reportDate = new Paragraph( new SimpleDateFormat(HEADER_DATE_FORMAT, Locale.US).format(reportGenerationDate), ReportHelper.HEADER_DATE_FONT); header.add(reportDate); } HeaderFooter head = new HeaderFooter(new Phrase(header), false); head.setAlignment(Element.ALIGN_CENTER); head.setBorder(Rectangle.BOTTOM); return head; }
/** * Using FontSelector. * * @param args * no arguments needed */ public static void main(String[] args) { try { // step 1 Document document = new Document(); // step 2 PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "fontselection.pdf")); // step 3 document.open(); // step 4 String text = "This text is the first verse of \u275dThe Iliad\u275e. It's not polytonic as it should be " + "with \u2798 and \u279a entoation variants but that's all we have for now.\n\n" + "\u2766\u00a0\u00a0\u039c\u03b7\u03bd\u03b9\u03bd \u03b1\u03b5\u03b9\u03b4\u03b5, \u03b8\u03b5\u03b1, \u03a0\u03b7\u03bb\u03b7\u03b9\u03b1\u03b4\u03b5\u03c9 \u0391\u03c7\u03b9\u03bb\u03b7\u03bf\u03c2"; FontSelector sel = new FontSelector(); sel.addFont(new Font(Font.TIMES_ROMAN, 12)); sel.addFont(new Font(Font.ZAPFDINGBATS, 12)); sel.addFont(new Font(Font.SYMBOL, 12)); Phrase ph = sel.process(text); document.add(new Paragraph(ph)); // step 5 document.close(); } catch (Exception de) { de.printStackTrace(); } }
@Override public void onEndPage(PdfWriter writer, Document document) { try { Rectangle page = document.getPageSize(); PdfPTable footer = new PdfPTable(1); footer.setWidthPercentage(100); footer.setSpacingBefore(20); String FootPager = String.valueOf(document.getPageNumber());//current page no PdfPCell footerPageNocell = new PdfPCell(new Phrase(fontFamilySelector.process(FootPager, FontContext.SMALL_BOLD_HELVETICA))); footerPageNocell.setBorder(0); footerPageNocell.setPaddingBottom(5); footerPageNocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); footer.addCell(footerPageNocell); footer.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); footer.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin() - 5, writer.getDirectContent()); } catch (Exception e) { throw new ExceptionConverter(e); } }