Java & J2EE Page 4 - Creating Simple PDF Files With iTextSharp |
In order to recap everything before we move on, let's create a simple application that generates a very basic PDF document. Nothing fancy is needed here. We'll create a few paragraphs of text and style each of them a bit differently. This application will create a PDF in the file 1.pdf: using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; class Example1 { static void Main(string[] args) { // Create and open a document Document doc = new Document(); PdfWriter.GetInstance(doc, new FileStream("1.pdf", FileMode.Create)); doc.Open(); // Create a string to use for paragraphs string text = "This is a paragraph. It is represted" + " 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."; // Add a basic paragraph doc.Add(new Paragraph(text)); // Add a paragraph that's underlined and indented Paragraph p2 = new Paragraph(text); p2.IndentationLeft = 36; p2.Font.SetStyle(Font.UNDERLINE); doc.Add(p2); // Add a paragraph that's underlined and in bold doc.Add(new Paragraph(text, FontFactory.GetFont("Courier", Font.DEFAULTSIZE, Font.UNDERLINE | Font.BOLD)));
// Add a really big paragraph doc.Add(new Paragraph(text, new Font(Font.HELVETICA, 36))); // Add a green, centered paragraph Paragraph p5 = new Paragraph(text, new Font(Font.TIMES_ROMAN, Font.DEFAULTSIZE, Font.NORMAL, Color.GREEN)); p5.Alignment = Element.ALIGN_CENTER; doc.Add(p5); // Add a double-spaced paragraph with // an indented first line Paragraph p6 = new Paragraph(text); p6.FirstLineIndent = 36; p6.MultipliedLeading = 2; doc.Add(p6); // Add a paragraph with multiple styles // Each word gets bigger Paragraph ascending = new Paragraph(); ascending.SpacingBefore = 72; for (int i = 1; i <= 5; i++) { ascending.Add(new Chunk("Hello", new Font(Font.HELVETICA, i * 5))); } doc.Add(ascending); // Close the document doc.Close(); } } The example is pretty straightforward. Everything should be familiar to you, and, moreover, comments explain the different sections of code. When you run the above code, the file 1.pdf will be created. If you open the new PDF file, you should see multiple paragraphs with various styles. You've looked at two basic text objects, fonts, and a document creation in the iTextSharp library, but, of course, the library supports more features. Besides adding text, you can add graphics and metadata to a PDF document. You can even enhance the text parts of a document with features such as columns.
blog comments powered by Disqus |
|
|
|
|
|
|
|