Wednesday, January 21, 2009

C#: Create PDF Document

Following Steps are involved to create a PDF document using C#

1) Create an instance of document object
Document myDoc = new Document(PageSize.A4.Rotate());

2) Create a writer that listens to this doucment and writes the document to desired Stream
PdfWriter.GetInstance(myDoc, new FileStream("Mathews.pdf", FileMode.Create));

3) Open the document
myDoc.Open();

4) Add Content to it
myDoc.add( new Paragraph ( "I am adding some content"));

5) Close the document
myDoc.close();

To use this sample source code for creating a PDF document, you must add a reference to the assembly iTextSharp.sourceforge.net. This can be downloaded from http://www.lowagie.com/iText/. DOwnload the assembly from the website http://www.lowagie.com/iText/ and add a reference to that from your project.


public static void Main()
{
Console.WriteLine("iText Demo");
// create a document-object Document myDoc = new Document(PageSize.A4.Rotate());
try
{
// create a writer
PdfWriter.GetInstance(myDoc, new FileStream("Mathews.pdf", FileMode.Create));

// Open
myDoc.Open();
// add contents
myDoc.Add(new Paragraph("Hello all"));
}
catch(DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch(IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
// close the documnet
myDoc.Close();
}

No comments:

Post a Comment