Create PDF in C#

Generate PDF
7/4/2014

This simple code sample shows you how to create a PDF using C# and print "Hello World" to it

C# code sample to create PDF

1 // create a new document with a single section 2 Document document = new Document(); 3 Section section = document.Sections.Add(); 4 document.Sections.Add( section ); 5 6 // add a new textparagraph to the section 7 TextParagraph textParagraph = new TextParagraph(); 8 section.Paragraphs.Add( textParagraph ); 9 10 // create a fragment, set some text and add it to the paragraph 11 Fragment fragment = new Fragment(); 12 fragment.Text = "Hello world!"; 13 textParagraph.Fragments.Add( fragment );

Here is the created PDF: Create-pdf-in-c-sharp.png
You might have noticed that you have to add the text into Fragment then add the Fragment into TextParagraph instead of simply add the text into TextParagraph. By doing so, a TextParagraph is allowed to have texts with different fonts and styles. This design increases the flexibility of TextParagraph. Here is the sample of saving document:

1 using( FileStream file = new FileStream( @"..\..\HelloWorld.pdf", FileMode.Create, FileAccess.Write ) ) 2 { 3 document.Write( file ); 4 }