Java & J2EE Page 2 - Adding Columns With iTextSharp |
So, here's a short example of a program that creates a single column two inches wide, on the left side of a letter-sized page, with one inch to the left, top and bottom of the column: using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; class Columns { public static void Main() { string text = "This is a paragraph. It is represented" + " by a Paragraph object in the iTextSharp " + "library. Here, we're creating paragraphs with " + "various styles in order to test out iTextSharp." + " This paragraph will take up multiple lines " + "and allow for a more complete example."; Document doc = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("1.pdf",FileMode.Create)); doc.Open(); PdfContentByte cb = writer.DirectContent; ColumnText column1 = new ColumnText(cb); column1.SetSimpleColumn(72, 72, 72*3, 72*10); column1.AddElement(new Paragraph(text)); column1.Go(); doc.Close(); } } The above example creates a PDF file called 1.pdf. If you open it, you'll notice that the text doesn't occupy the whole column (it falls far short, actually). So, how would it look if more text were to be added? Place the two lines that add text in a loop with five iterations: for (int i = 0; i < 5; i++) { column1.AddElement(new Paragraph(text)); column1.Go(); } If you run the example now and look at the result, you'll see that the column is indeed filled up with text, but not all of the text actually made it to the column. Once the column filled with text, the rest of the text got cut off. So, we've added more text than allowed for by the bounds of the column. It's actually possible to check if all of the text has been successfully written. The Go method returns an Integer value that indicates whether the write ended with no text left (success) or no space in the column left (failure). You can check this value with the bit flags ColumnText.NO_MORE_TEXT and ColumnText.NO_MORE_COLUMN: int result = column1.Go(); if ((result & ColumnText.NO_MORE_TEXT) != 0) { // All the text has been written } if ((result & ColumnText.NO_MORE_COLUMN) != 0) { // The column is full } Of course, this raises the following question: what do we do if we run out of space within a column? Right now, the extra text is essentially discarded, but this is unacceptable. Common sense tells us that we need yet another column to contain the overflow text.
blog comments powered by Disqus |
|
|
|
|
|
|
|