com.lowagie.text.Paragraph Java Examples

The following examples show how to use com.lowagie.text.Paragraph. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FactoryProperties.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private static void setParagraphLeading(Paragraph p, String leading) {
	if (leading == null) {
		p.setLeading(0, 1.5f);
		return;
	}
	try {
		StringTokenizer tk = new StringTokenizer(leading, " ,");
		String v = tk.nextToken();
		float v1 = Float.parseFloat(v);
		if (!tk.hasMoreTokens()) {
			p.setLeading(v1, 0);
			return;
		}
		v = tk.nextToken();
		float v2 = Float.parseFloat(v);
		p.setLeading(v1, v2);
	} catch (Exception e) {
		p.setLeading(0, 1.5f);
	}
}
 
Example #2
Source File: WritePdfTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void writeFile() throws IOException, DocumentException {
	File file = File.createTempFile("testfile", ".pdf");
	File fileWithPageNumbers = File.createTempFile("testfilewithpagenumbers", ".pdf");
	Document document = new Document();
	PdfWriter.getInstance(document, new FileOutputStream(file));
	document.open();
	for(int i = 0; i < 100; i++) {
	document.add(new Paragraph("Test"));
	}
	document.close();
	addPageNumbers(file, fileWithPageNumbers.getAbsolutePath());
	Assert.assertTrue(file.length() > 0);
	Assert.assertTrue(fileWithPageNumbers.length() > 0);
	file.delete();
	fileWithPageNumbers.delete();
}
 
Example #3
Source File: PurchaseOrderQuotePdf.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * A helper method to create a PdfPCell. We can specify the content, font, horizontal alignment, border (borderless, no
 * bottom border, no right border, no top border, etc.
 *
 * @param content              The text content to be displayed in the cell.
 * @param borderless           boolean true if the cell should be borderless.
 * @param noBottom             boolean true if the cell should have borderWidthBottom = 0.
 * @param noRight              boolean true if the cell should have borderWidthRight = 0.
 * @param noTop                boolean true if the cell should have borderWidthTop = 0.
 * @param horizontalAlignment  The desired horizontal alignment for the cell.
 * @param font                 The font type to be used in the cell.
 * @return                     An instance of PdfPCell which content and attributes were set by the input parameters.
 */
private PdfPCell createCell(String content, boolean borderless, boolean noBottom, boolean noRight, boolean noTop, int horizontalAlignment, Font font) {
    PdfPCell tableCell = new PdfPCell(new Paragraph(content, font));
    if (borderless) {
        tableCell.setBorder(0);
    }
    if (noBottom) {
        tableCell.setBorderWidthBottom(0);
    }
    if (noTop) {
        tableCell.setBorderWidthTop(0);
    }
    if (noRight) {
        tableCell.setBorderWidthRight(0);
    }
    tableCell.setHorizontalAlignment(horizontalAlignment);
    return tableCell;
}
 
Example #4
Source File: ExtendedFontTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Extended font example.
 * 
 * 
 */
@Test
public void main() throws Exception {
	Document document = new Document();
	RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("ExtendedFont.rtf"));
	document.open();

	// Create a RtfFont with the desired font name.
	RtfFont msComicSans = new RtfFont("Comic Sans MS");

	// Use the RtfFont like any other Font.
	document.add(new Paragraph("This paragraph uses the" + " Comic Sans MS font.", msComicSans));

	// Font size, font style and font colour can also be specified.
	RtfFont bigBoldGreenArial = new RtfFont("Arial", 36, Font.BOLD, Color.GREEN);

	document.add(new Paragraph("This is a really big bold green Arial text", bigBoldGreenArial));
	document.close();
}
 
Example #5
Source File: PdfMBeansReport.java    From javamelody with Apache License 2.0 6 votes vote down vote up
private void writeAttributes(MBeanNode mbean) throws DocumentException {
	final String description = mbean.getDescription();
	final List<MBeanAttribute> attributes = mbean.getAttributes();
	if (description != null || !attributes.isEmpty()) {
		currentTable = createAttributesTable();
		if (description != null) {
			currentTable.getDefaultCell().setColspan(3);
			addCell('(' + description + ')');
			currentTable.getDefaultCell().setColspan(1);
		}
		for (final MBeanAttribute attribute : attributes) {
			writeAttribute(attribute);
		}
		final Paragraph paragraph = new Paragraph();
		paragraph.setIndentationLeft(margin);
		paragraph.add(currentTable);
		addToDocument(paragraph);
		addText("\n");
	}
}
 
Example #6
Source File: OpenTypeFontTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Using oth
 */
@Test
public void main() throws Exception {
	// step 1
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step 2
	PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("opentypefont.pdf"));
	// step 3
	document.open();
	// step 4
	BaseFont bf = BaseFont.createFont(PdfTestBase.RESOURCES_DIR
			+ "liz.otf", BaseFont.CP1252, true);
	String text = "Some text with the otf font LIZ.";
	document.add(new Paragraph(text, new Font(bf, 14)));
	// step 5
	document.close();
}
 
Example #7
Source File: PdfWebTable.java    From unitime with Apache License 2.0 6 votes vote down vote up
private float addImage(PdfPCell cell, String name) {
	try {
		java.awt.Image awtImage = (java.awt.Image)iImages.get(name);
		if (awtImage==null) return 0;
		Image img = Image.getInstance(awtImage, Color.WHITE);
		Chunk ck = new Chunk(img, 0, 0);
		if (cell.getPhrase()==null) {
			cell.setPhrase(new Paragraph(ck));
			cell.setVerticalAlignment(Element.ALIGN_TOP);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		} else {
			cell.getPhrase().add(ck);
		}
		return awtImage.getWidth(null);
	} catch (Exception e) {
		return 0;
	}
}
 
Example #8
Source File: EventsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * We only alter the handling of some endtags.
 * 
 * @param uri
 *            the uri of the namespace
 * @param lname
 *            the local name of the tag
 * @param name
 *            the name of the tag
 */
public void endElement(String uri, String lname, String name) {
	if (myTags.containsKey(name)) {
		XmlPeer peer = (XmlPeer) myTags.get(name);
		// we don't want the document to be close
		// because we are going to add a page after the xml is parsed
		if (isDocumentRoot(peer.getTag())) {
			return;
		}
		handleEndingTags(peer.getTag());
		// we want to add a paragraph after the speaker chunk
		if ("SPEAKER".equals(name)) {
			try {
				TextElementArray previous = (TextElementArray) stack
						.pop();
				previous.add(new Paragraph(16));
				stack.push(previous);
			} catch (EmptyStackException ese) {
			}
		}
	} else {
		handleEndingTags(name);
	}
}
 
Example #9
Source File: EndPageTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Demonstrates the use of PageEvents.
 */
@Test
public void main() throws Exception {
	Document document = new Document(PageSize.A4, 50, 50, 70, 70);

	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("endpage.pdf"));
	writer.setPageEvent(new EndPageTest());
	document.open();
	String text = "Lots of text. ";
	for (int k = 0; k < 10; ++k)
		text += text;
	document.add(new Paragraph(text));
	document.close();

}
 
Example #10
Source File: ContractsGrantsInvoiceReportServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Generates a PDF paragraph for a given Address
 * @param name the name that this envelope is being sent to
 * @param line1Address the first line of the address
 * @param line2Address the second line of the address
 * @param cityName the name of the city to send this to
 * @param stateCode the code of the state or presumably province to send this to
 * @param postalCode the postal code/zip code to send the enveleope to
 * @param font the font to write in
 * @return a PDF Paragraph for the address
 */
protected Paragraph generateAddressParagraph(String name, String line1Address, String line2Address, String cityName, String stateCode, String postalCode, Font font) {
    Paragraph addressParagraph = new Paragraph();
    addressParagraph.add(new Paragraph(name, font));
    if (!StringUtils.isBlank(line1Address)) {
        addressParagraph.add(new Paragraph(line1Address, font));
    }
    if (!StringUtils.isBlank(line2Address)) {
        addressParagraph.add(new Paragraph(line2Address, font));
    }
    String string = "";
    if (!StringUtils.isBlank(cityName)) {
        string += cityName;
    }
    if (!StringUtils.isBlank(stateCode)) {
        string += ", " + stateCode;
    }
    if (!StringUtils.isBlank(postalCode)) {
        string += "-" + postalCode;
    }
    if (!StringUtils.isBlank(string)) {
        addressParagraph.add(new Paragraph(string, font));
    }
    return addressParagraph;
}
 
Example #11
Source File: CustomerLoadServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void writeFileNameSectionTitle(Document pdfDoc, String filenameLine) {
    Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.BOLD);

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_LEFT);
    Chunk chunk = new Chunk(filenameLine, font);
    chunk.setBackground(Color.LIGHT_GRAY, 5, 5, 5, 5);
    paragraph.add(chunk);

    //  blank line
    paragraph.add(new Chunk("", font));

    try {
        pdfDoc.add(paragraph);
    }
    catch (DocumentException e) {
        LOG.error("iText DocumentException thrown when trying to write content.", e);
        throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
    }
}
 
Example #12
Source File: PdfCacheInformationsReport.java    From javamelody with Apache License 2.0 6 votes vote down vote up
@Override
void toPdf() throws DocumentException {
	writeHeader();

	for (final CacheInformations cacheInformations : cacheInformationsList) {
		nextRow();
		writeCacheInformations(cacheInformations);
	}
	addTableToDocument();
	if (!hitsRatioEnabled) {
		final Paragraph statisticsEnabledParagraph = new Paragraph(
				getString("caches_statistics_enable"), cellFont);
		statisticsEnabledParagraph.setAlignment(Element.ALIGN_RIGHT);
		addToDocument(statisticsEnabledParagraph);
	}
	addConfigurationReference();
}
 
Example #13
Source File: LockboxServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void writeDetailLine(com.lowagie.text.Document pdfDoc, String detailLineText) {
    if (ObjectUtils.isNotNull(detailLineText)) {
        Font font = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL);

        Paragraph paragraph = new Paragraph();
        paragraph.setAlignment(com.lowagie.text.Element.ALIGN_LEFT);
        paragraph.add(new Chunk(detailLineText, font));

        try {
            pdfDoc.add(paragraph);
        }
        catch (DocumentException e) {
            LOG.error("iText DocumentException thrown when trying to write content.", e);
            throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
        }
    }
}
 
Example #14
Source File: CustomerInvoiceWriteoffBatchServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void writeInvoiceSectionTitle(com.lowagie.text.Document pdfDoc, String customerNameLine) {
    Font font = FontFactory.getFont(FontFactory.COURIER, 8, Font.BOLD + Font.UNDERLINE);

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(com.lowagie.text.Element.ALIGN_LEFT);
    paragraph.add(new Chunk(customerNameLine, font));

    //  blank line
    paragraph.add(new Chunk("", font));

    try {
        pdfDoc.add(paragraph);
    }
    catch (DocumentException e) {
        LOG.error("iText DocumentException thrown when trying to write content.", e);
        throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
    }
}
 
Example #15
Source File: DocumentSettingsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Document settings example.
 * 
 * 
 */
@Test
public void main() throws Exception {
	Document document = new Document();

	// Keep a reference to the RtfWriter2 instance.
	RtfWriter2 writer2 = RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("DocumentSettings.rtf"));

	// Specify that the document caching is to be done on disk.
	writer2.getDocumentSettings().setDataCacheStyle(RtfDataCache.CACHE_DISK);

	// Specify that all \n are translated into soft linebreaks.
	writer2.getDocumentSettings().setAlwaysGenerateSoftLinebreaks(true);

	document.open();
	document.add(new Paragraph("This example has been cached on disk\nand all "
			+ "\\n have been translated into soft linebreaks."));
	document.close();
}
 
Example #16
Source File: LockboxServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void writeBatchGroupSectionTitle(com.lowagie.text.Document pdfDoc, String batchSeqNbr, java.sql.Date procInvDt, String cashControlDocNumber) {
    Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.BOLD);

    String lineText = "CASHCTL " + rightPad(cashControlDocNumber, 12) + " " +
    "BATCH GROUP: " + rightPad(batchSeqNbr, 5) + " " +
    rightPad((procInvDt == null ? "NONE" : procInvDt.toString()), 35);

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(com.lowagie.text.Element.ALIGN_LEFT);
    Chunk chunk = new Chunk(lineText, font);
    chunk.setBackground(Color.LIGHT_GRAY, 5, 5, 5, 5);
    paragraph.add(chunk);

    //  blank line
    paragraph.add(new Chunk("", font));

    try {
        pdfDoc.add(paragraph);
    }
    catch (DocumentException e) {
        LOG.error("iText DocumentException thrown when trying to write content.", e);
        throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
    }
}
 
Example #17
Source File: PdfDocumentFactory.java    From javamelody with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #18
Source File: CustomerInvoiceWriteoffBatchServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void writeInvoiceSectionMessage(com.lowagie.text.Document pdfDoc, String resultLine) {
    Font font = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL);

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(com.lowagie.text.Element.ALIGN_LEFT);
    paragraph.add(new Chunk(resultLine, font));

    //  blank line
    paragraph.add(new Chunk("", font));

    try {
        pdfDoc.add(paragraph);
    }
    catch (DocumentException e) {
        LOG.error("iText DocumentException thrown when trying to write content.", e);
        throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
    }
}
 
Example #19
Source File: BasicTabsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Tab stops in paragraphs.
 * 
 * 
 */
@Test
public void main() throws Exception {
	Document document = new Document();
	RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("BasicTabs.rtf"));

	document.open();

	// Define the Paragraph to add tab stops to
	Paragraph par = new Paragraph();

	// Add the tab stops to the paragraph
	par.add(new RtfTab(70, RtfTab.TAB_LEFT_ALIGN));
	par.add(new RtfTab(400, RtfTab.TAB_RIGHT_ALIGN));

	// Add the text to the paragraph, placing the tab stops with \t
	par.add("\tFirst the text on the left-hand side\tThis text is right aligned.");

	document.add(par);

	document.close();
}
 
Example #20
Source File: HelloHtmlTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates an HTML page with the text 'Hello World'
 * 
 */
@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
	// and directs a HTML-stream to a file
	HtmlWriter.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.html"));

	// step 3: we open the document
	document.open();
	// step 4: we add a paragraph to the document
	document.add(new Paragraph("Hello World"));

	// step 5: we close the document
	document.close();
}
 
Example #21
Source File: BookmarksTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a document with outlines.
 * 
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document(PageSize.A6);

	// step 2:
	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("bookmarks.pdf"));
	// step 3:
	writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
	document.open();
	// step 4: we grab the ContentByte and do some stuff with it
	writer.setPageEvent(new BookmarksTest());

	document.add(new Paragraph(
			"GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur.  Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt.  Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt.",
			new Font(Font.HELVETICA, 12)));
	document.add(new Paragraph(
			"[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]",
			new Font(Font.HELVETICA, 12)));
	document.add(new Paragraph(
			"Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix.  Is M. Messala, [et P.] M.  Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent:  perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri.  Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur:  una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit.  His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur.  Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.",
			new Font(Font.HELVETICA, 12)));
	document.add(new Paragraph(
			"His rebus adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare.  Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant.  Ad eas res conficiendas Orgetorix deligitur.  Is sibi legationem ad civitates suscipit.  In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat.  Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset:  non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat.  Hac oratione adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant.",
			new Font(Font.HELVETICA, 12)));
	document.add(new Paragraph(
			"Ea res est Helvetiis per indicium enuntiata.  Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur.  Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit.  Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit.",
			new Font(Font.HELVETICA, 12)));

	// step 5: we close the document
	document.close();
}
 
Example #22
Source File: PdfThreadInformationsReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private void writeThreadInformations(ThreadInformations threadInformations)
		throws DocumentException, IOException {
	final PdfPCell defaultCell = getDefaultCell();
	defaultCell.setHorizontalAlignment(Element.ALIGN_LEFT);
	addCell(threadInformations.getName());
	defaultCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	if (threadInformations.isDaemon()) {
		addCell(getString("oui"));
	} else {
		addCell(getString("non"));
	}
	defaultCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
	addCell(integerFormat.format(threadInformations.getPriority()));
	defaultCell.setHorizontalAlignment(Element.ALIGN_LEFT);
	final PdfPCell cell = new PdfPCell();
	final Paragraph paragraph = new Paragraph(
			getDefaultCell().getLeading() + cellFont.getSize());
	paragraph.add(new Chunk(
			getImage(
					"bullets/" + HtmlThreadInformationsReport.getStateIcon(threadInformations)),
			0, -1));
	paragraph.add(new Phrase(String.valueOf(threadInformations.getState()), cellFont));
	cell.addElement(paragraph);
	addCell(cell);
	if (stackTraceEnabled) {
		addCell(threadInformations.getExecutedMethod());
	}
	if (cpuTimeEnabled) {
		defaultCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		addCell(integerFormat.format(threadInformations.getCpuTimeMillis()));
		addCell(integerFormat.format(threadInformations.getUserTimeMillis()));
	}
}
 
Example #23
Source File: MetaDataTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testProducer() throws Exception {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	Document document = new Document();

	PdfWriter.getInstance(document, baos);
	document.open();
	document.add(new Paragraph("Hello World"));
	document.close();

	PdfReader r = new PdfReader(baos.toByteArray());

	// with this special version, metadata is not generated by default
	Assert.assertNull(r.getInfo().get("Producer"));
}
 
Example #24
Source File: WidthTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates how to measure and scale the width of a Chunk.
 * 
 */
@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("Width.pdf"));

	// step 3: we open the document
	document.open();
	// step 4:
	Chunk c = new Chunk("quick brown fox jumps over the lazy dog");
	float w = c.getWidthPoint();
	Paragraph p = new Paragraph("The width of the chunk: '");
	p.add(c);
	p.add("' is ");
	p.add(String.valueOf(w));
	p.add(" points or ");
	p.add(String.valueOf(w / 72f));
	p.add(" inches.");
	document.add(p);
	document.add(c);
	document.add(Chunk.NEWLINE);
	c.setHorizontalScaling(0.5f);
	document.add(c);
	document.add(c);

	// step 5: we close the document
	document.close();
}
 
Example #25
Source File: PdfOutline.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Constructs a <CODE>PdfOutline</CODE>.
 * <P>
 * This is the constructor for an <CODE>outline entry</CODE>.
 *
 * @param parent the parent of this outline item
 * @param destination the destination for this outline item
 * @param title the title of this outline item
 * @param open <CODE>true</CODE> if the children are visible
 */
public PdfOutline(PdfOutline parent, PdfDestination destination, Paragraph title, boolean open) {
    super();
    StringBuffer buf = new StringBuffer();
    for (Iterator i = title.getChunks().iterator(); i.hasNext(); ) {
        Chunk chunk = (Chunk) i.next();
        buf.append(chunk.content());
    }
    this.destination = destination;
    initOutline(parent, buf.toString(), open);
}
 
Example #26
Source File: BudgetConstructionReportsServiceHelperImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.kuali.kfs.module.bc.document.service.BudgetConstructionReportsServiceHelper#generatePdf(java.util.List,
 *      java.io.ByteArrayOutputStream)
 */
@NonTransactional
public void generatePdf(List<String> errorMessages, ByteArrayOutputStream baos) throws DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();

    for (String error : errorMessages) {
        document.add(new Paragraph(error));
    }

    document.close();
}
 
Example #27
Source File: ChangingStylesheetsTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
    * Changing paragraph stylesheets properties.
    * 
    * 
    */
@Test
   public void main() throws Exception {
           Document document = new Document();
           RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("ChangingStylesheets.rtf"));

           // Set the default style font name. This is inherited
           // by all other styles.
           RtfParagraphStyle.STYLE_NORMAL.setFontName("Times New Roman");
           // Set the colour of the level 1 heading to blue.
           RtfParagraphStyle.STYLE_HEADING_1.setColor(Color.BLUE);
           // Set the font name of the heading back to Arial again.
           RtfParagraphStyle.STYLE_HEADING_2.setFontName("Arial");
           // Change the font size
           RtfParagraphStyle.STYLE_HEADING_2.setSize(12);

           // Change the style properties to the desired values
           // before document.open()

           document.open();
           
           // Simply set the stylesheet you wish to use as the Font
           // of the Paragraph
           document.add(new Paragraph("This is a heading level 1",
                   RtfParagraphStyle.STYLE_HEADING_1));
           document.add(new Paragraph("This is a heading level 2",
                   RtfParagraphStyle.STYLE_HEADING_2));
           document.add(new Paragraph("Just some text that is formatted " +
                   "in the default style.", RtfParagraphStyle.STYLE_NORMAL));

           document.close();

   }
 
Example #28
Source File: PdfInstructionalOfferingTableBuilder.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void addText(PdfPCell cell, String text, boolean bold, boolean italic,  int orientation, Color color, boolean newLine) {
	if (text==null) return;
	if (cell.getPhrase()==null) {
		Chunk ch = new Chunk(text, PdfFont.getFont(bold, italic, color));
		cell.setPhrase(new Paragraph(ch));
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		cell.setHorizontalAlignment(orientation);
	} else {
		cell.getPhrase().add(new Chunk((newLine?"\n":"")+text, PdfFont.getFont(bold, italic, color)));
	}
}
 
Example #29
Source File: AccountSummaryController.java    From primefaces-blueprints with The Unlicense 5 votes vote down vote up
public void postProcessPDF(Object document) throws IOException, BadElementException, DocumentException {  
	 Document pdf = (Document) document; 
	 pdf.add( Chunk.NEWLINE );
	 Font fontbold = FontFactory.getFont("Times-Roman", 14, Font.BOLD);
	 pdf.add(new Paragraph("Disclaimer",fontbold));
	 pdf.add( Chunk.NEWLINE );
	 pdf.add(new Paragraph("The information contained in this website is for information purposes only, and does not constitute, nor is it intended to constitute, the provision of financial product advice."));
	 pdf.add(new Paragraph("This website is intended to track the investor account summary information,investments and transaction in a partcular period of time. "));
}
 
Example #30
Source File: FontFactoryType1FontsTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates a PDF file with the 14 standard Type 1 Fonts (using
 * FontFactory)
 * 
 */
@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("FontFactoryType1Fonts.pdf"));

	// step 3: we open the document
	document.open();
	// step 4:

	// the 14 standard fonts in PDF
	Font[] fonts = new Font[14];
	fonts[0] = FontFactory.getFont(FontFactory.COURIER, Font.DEFAULTSIZE, Font.NORMAL);
	fonts[1] = FontFactory.getFont(FontFactory.COURIER, Font.DEFAULTSIZE, Font.ITALIC);
	fonts[2] = FontFactory.getFont(FontFactory.COURIER, Font.DEFAULTSIZE, Font.BOLD);
	fonts[3] = FontFactory.getFont(FontFactory.COURIER, Font.DEFAULTSIZE, Font.BOLD | Font.ITALIC);
	fonts[4] = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.NORMAL);
	fonts[5] = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.ITALIC);
	fonts[6] = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD);
	fonts[7] = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLDITALIC);
	fonts[8] = FontFactory.getFont(FontFactory.TIMES_ROMAN, Font.DEFAULTSIZE, Font.NORMAL);
	fonts[9] = FontFactory.getFont(FontFactory.TIMES_ROMAN, Font.DEFAULTSIZE, Font.ITALIC);
	fonts[10] = FontFactory.getFont(FontFactory.TIMES_ROMAN, Font.DEFAULTSIZE, Font.BOLD);
	fonts[11] = FontFactory.getFont(FontFactory.TIMES_ROMAN, Font.DEFAULTSIZE, Font.BOLDITALIC);
	fonts[12] = FontFactory.getFont(FontFactory.SYMBOL, Font.DEFAULTSIZE, Font.NORMAL);
	fonts[13] = FontFactory.getFont(FontFactory.ZAPFDINGBATS, Font.DEFAULTSIZE, Font.NORMAL);
	// add the content
	for (int i = 0; i < 14; i++) {
		document.add(new Paragraph("quick brown fox jumps over the lazy dog", fonts[i]));
	}

	// step 5: we close the document
	document.close();
}