The easiest way to create PDF documents in C#

Mo_Developer

Member
Joined
Jul 29, 2021
Messages
5
Programming Experience
3-5
In this tutorial, we would like to share some of our experience in generating PDF documents in C# using the PDFFlow library.

Getting started​

First, we need to create a new console application project “MyPDFDoc” in Visual Studio and choose Language “C#”.
Then we need to add the Gehtsoft.PDFFlowlib library to our project. You can download it as a NuGet package from NuGet Gallery | Gehtsoft.PDFFlowLib.
You can also install it from the Visual Studio NuGet Package Manager:
  1. In Solution Explorer, right-click either References or a project and select Manage NuGet Packages.
  2. Go to the Browse tab and search for the Gehtsoft.PDFFlowLib package using the search box on the upper left.
  3. Select the package from the list and click Install.

Hello World!​

Now the PDFFlow library is installed, we are ready to create our first “Hello world” PDF document.
Add sections to the document.
A section is a part of a document holding content and layout. A document may contain one or more sections.
You can add various content to a section, including paragraphs, images, tables, lines, and repeating areas.
In your Main class start typing this code to create a simple paragraph:
static void Main(string[] args)
{
DocumentBuilder.New().AddSection()
.AddParagraph(“Hello World!”).ToDocument()
.Build(“Result.pdf”);
}
The result will be like this:
1.png

Set font color and size​

use the method SetFontColor() to set text color and the method SetFontSize() to set the text size.
DocumentBuilder builder = DocumentBuilder.New();
var section = builder.AddSection();
section.AddParagraph(“Hello World!”).ToDocument();
section.AddParagraph(“Bigger text goes here!”).SetFontColor(Color.FromHtml(“#FC6A03”))
.SetFontSize(20).ToDocument();
builder.Build(“Result.pdf”);
The result will be like this:
2.png

Adding image to document​

Suppose we need to add a Logo to our PDF document, all we need to do is use the method AddImage() and pass the image path to it, set its size and alignment.
DocumentBuilder builder = DocumentBuilder.New();
var section = builder.AddSection();
section.AddParagraph(“Hello World!”).ToDocument();
//Add an image and set its size, alignment and margins
section.AddImage(“MyImage.png”).SetWidth(150).SetAlignment(HorizontalAlignment.Right).SetMargins(10, 10, 10, 10);
section.AddParagraph(“Bigger text goes here!”).SetFontColor(Color.FromHtml(“#FC6A03”))
.SetFontSize(20).ToDocument();
builder.Build(“Result.pdf”);
The result will be like this:
3.png

Layout using tables​

Now let’s add a table and use it to layout our document.
We will create a table with two columns, then insert the text in the first column and the image (logo) in the second column, then set the table borders to zero to make it invisible.
First to create a table with 2 columns and one row use this code:
section.AddTable()
// add 2 columns to the table
.AddColumnToTable().AddColumnToTable()
// add the first row
.AddRow()
// add two cells to the row
.AddCellToRow().AddCellToRow()
.ToDocument();
the result will be like this:
4.png

Then to add the text and the image to the cells use the methods AddParagraph() and AddImage()
DocumentBuilder builder = DocumentBuilder.New();
var section = builder.AddSection();
section.AddParagraph(“Hello World!”).ToDocument();
section.AddTable()
// add 2 columns to the table
.AddColumnToTable().AddColumnToTable()
// add the first row
.AddRow()
.AddCell().AddParagraph(“Bigger text goes here!”).SetFontColor(Color.FromHtml(“#FC6A03”)).SetFontSize(20).ToRow()
.AddCell().AddImage(“MyImage.png”).SetWidth(150).SetAlignment(HorizontalAlignment.Right).SetMargins(10, 10, 10, 10).ToRow()
.ToDocument();
builder.Build(“Result.pdf”);
The result will be like this:
5.png

To remove the table borders set the border width to 0
section.AddTable().SetBorderWidth(0)

Add text after the paragraph​

If you need to add more than one block of text in the same cell, just use the method AddText() and set its font properties.
Also, add \n at the beginning of the paragraph to have a new line.
The following code will add some dummy text to the main text in orange:
DocumentBuilder builder = DocumentBuilder.New();
var section = builder.AddSection();
section.AddParagraph(“Hello World!”).ToDocument();
section.AddTable().SetBorderWidth(0)
// add 2 columns to the table
.AddColumnToTable().AddColumnToTable()
// add the first row
.AddRow()
.AddCell().AddParagraph(“Lorem ipsum dolor sit amet”).SetFontColor(Color.FromHtml(“#FC6A03”)).SetFontSize(20)
.AddText(“\nVestibulum eget lorem ultricies, convallis sapien eu, tristique dui. Donec tincidunt efficitur interdum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Praesent lacus ex, iaculis at aliquam vel, mattis eget lacus. Aenean eget velit purus. Integer euismod pretium est, a efficitur nunc dapibus at. Nam malesuada at nisl a tempor.“).SetFontSize(12).SetFontColor(Color.FromHtml(“#000000”)).ToRow()
.AddCell().AddImage(“MyImage.png”).SetWidth(150).SetAlignment(HorizontalAlignment.Right).SetMargins(10, 10, 10, 10).ToRow().ToDocument();
builder.Build(“Result.pdf”);
The result will be like this:
6.png

Add a horizontal line​

Now let’s separate the page into two sections using a horizontal line.
Use this code to add a horizontal line and set its length, color, and alignment to center:
section.AddLine().SetLength(500).SetColor(Color.Gray).SetAlignment(HorizontalAlignment.Center).ToDocument();
The result will be like this:
7.png

Drawing a table with colspan and rowspan​

Now we will draw a table with 4 columns and 6 rows, change the text style, change the back color of some cells, and span some rows and columns.
DocumentBuilder builder = DocumentBuilder.New();
var section = builder.AddSection();
section.AddParagraph(“Hello World!”).ToDocument();
section.AddTable().SetBorderWidth(0)
// add 2 columns to the table
.AddColumnToTable()
.AddColumnToTable()
// add the first row
.AddRow()
.AddCell().AddParagraph(“Lorem ipsum dolor sit amet”).SetFontColor(Color.FromHtml(“#FC6A03”)).SetFontSize(20)
.AddText(“\nVestibulum eget lorem ultricies, convallis sapien eu, tristique dui. Donec tincidunt efficitur interdum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Praesent lacus ex, iaculis at aliquam vel, mattis eget lacus. Aenean eget velit purus. Integer euismod pretium est, a efficitur nunc dapibus at. Nam malesuada at nisl a tempor. “).SetFontSize(12).SetFontColor(Color.FromHtml(“#000000”)).ToRow()
.AddCell().AddImage(“MyImage.png”).SetWidth(150).SetAlignment(HorizontalAlignment.Right).SetMargins(10, 10, 10, 10).ToRow().ToDocument();
//// horizontal line
section.AddLine().SetLength(500).SetColor(Color.Gray).SetAlignment(HorizontalAlignment.Center).ToDocument();
//// table with colspan and rowspan
section.AddParagraph(“Table with colspan and rowspan:”)
.SetBold().SetMarginBottom(5).SetMarginTop(20).ToSection()
// create table
.AddTable().SetWidth(300)
// create 4 coumns
.AddColumnToTable().AddColumnToTable()
.AddColumnToTable().AddColumnToTable()
// add the first row
.AddRow()
// change the back color of the row
.SetBackColor(Color.FromRgba(0, 0.69, 0.94, 1)).SetBold()
.AddCell(“Product”)
// span this cell in 2 rows
.SetRowSpan(2)
.SetVerticalAlignment(VerticalAlignment.Center)
.ToRow()
.AddCell(“Month”)
// span this cell in 3 columns
.SetColSpan(3)
.SetHorizontalAlignment(HorizontalAlignment.Center).ToTable()
// add the second row
.AddRow().SetHorizontalAlignment(HorizontalAlignment.Center)
.AddCellToRow().AddCellToRow(“January”).AddCellToRow(“February”).AddCellToRow(“March”)
.SetBackColor(Color.FromRgba(0, 0.69, 0.94, 1)).SetBold()
.SetHorizontalAlignment(HorizontalAlignment.Center).ToTable()
// add the third row
.AddRow()
.SetHorizontalAlignment(HorizontalAlignment.Center)
.AddCell().AddParagraphToCell(“Product 1”)
.SetHorizontalAlignment(HorizontalAlignment.Left).ToRow()
.AddCellToRow(“1,000”)
.AddCellToRow(“1,015”)
.AddCellToRow(“1,030”).ToTable()
// add the fourth row
.AddRow()
.SetHorizontalAlignment(HorizontalAlignment.Center).AddCell()
.AddParagraphToCell(“Product 2”)
.SetHorizontalAlignment(HorizontalAlignment.Left).ToRow()
.AddCellToRow(“2,000”)
.AddCellToRow(“2,040”)
.AddCellToRow(“2,075”).ToTable()
// add the fifth row
.AddRow().SetHorizontalAlignment(HorizontalAlignment.Center).AddCell().AddParagraphToCell(“Product 3”)
.SetHorizontalAlignment(HorizontalAlignment.Left)
.ToRow()
.AddCellToRow(“3,000”)
.AddCellToRow(“3,060”)
.AddCellToRow(“3,100”).ToTable()
// add the sixth row
.AddRow()
.SetBackColor(Color.FromRgba(0, 0.69, 0.94, 1)).SetBold()
.AddCellToRow(“Total for Q1”)
.AddCell(“18,320”)
.SetHorizontalAlignment(HorizontalAlignment.Left)
.SetColSpan(3).ToDocument();
builder.Build(“Result.pdf”);
The result will be like this:
8.png

Create Repeating Areas (headers and footers)​

Almost in all business documents, it is necessary to set dynamic page counters, headers, and footers. Let’s see how to do this.
To create a header you the method AddHeaderToBothPages(height) and set its height, and for creating a footer use the method AddFooterToBothPages(height) and set its height too.
To create an automatic page number(page counter) in the footer use the method AddPageNumberToParagraph(“page #”).
The following code will generate a header with image and text, a footer with text, and an automatic page counter.
// repeating areas
// set text style for repeating area
var styleMain = StyleBuilder.New().SetFontSize(11);
section.ApplyStyle(styleMain)
// create header and se its height
.AddHeaderToBothPages(30)
.AddParagraph().SetFont(Fonts.Courier(11))
.SetAlignment(HorizontalAlignment.Center)
// create header image
.AddInlineImage(“MyImage.png”, 24, 24)
.SetMarginRight(5).SetMarginTop(5).ToParagraph()
// create header text
.AddText(“PDFFlow Library”).ToSection()
// this code will create a new PDF page
.InsertPageBreak()
.AddParagraphToSection(“This document is an example of a PDF document:” +“ a header with an image, “ +“a footer with a line and a page number, an empty page at the end.”)
// create footer and set its height
.AddFooterToBothPages(20).AddLineToRepeatingArea()
// add text to footer
.AddParagraph(“A footer with custom text, “)
// generate an outomatic page number
.AddPageNumberToParagraph(“page #”)
.SetAlignment(HorizontalAlignment.Center).ToDocument();
The result will be like this:
9.png

Creating Multilevel List​

To create a Multilevel list you can use the method SetListNumbered() for numerical/Latin/Roman listed items, and the method SetListBulleted() for bulleted/dashed listed items.
For example, if you need to create a bulleted first-level list item add the following code to the
.AddParagraph(“Europe”).SetListBulleted(ListBullet.Bullet, 0)
For creating a numbered second-level list item add the following code
.AddParagraph(“Australia”).SetListNumbered(NumerationStyle.Arabic, 1)
Use the following code to generate a three-leveled list with bulleted, dashed, and numbered items:
////Multilevel List
section.AddParagraph(“Asia”).SetMarginTop(50).SetFontColor(Color.Red)
.SetListBulleted().ToSection()
.AddParagraph(“China”)
.SetListNumbered(NumerationStyle.Arabic,1).SetFontColor(Color.Red).ToSection()
.AddParagraph(“Russia”)
.SetListNumbered(NumerationStyle.Arabic,1).SetFontColor(Color.Red).ToSection()
.AddParagraph(“Moscow”).SetListBulleted(ListBullet.Dash,2).SetFontColor(Color.Red).ToSection()
.AddParagraph(“Omsk”).SetListBulleted(ListBullet.Dash,2).SetFontColor(Color.Red).ToSection()
.AddParagraph(“Africa”).SetFontColor(Color.Green)
.SetListBulleted().ToSection()
.AddParagraph(“Nigeria”)
.SetListNumbered(NumerationStyle.LowerLatin,1).SetFontColor(Color.Green).ToSection()
.AddParagraph(“Kenya”)
.SetListNumbered(NumerationStyle.LowerLatin,1).SetFontColor(Color.Green).ToSection()
.AddParagraph(“North America”).SetFontColor(Color.Blue)
.SetListBulleted().ToSection()
.AddParagraph(“Canada”)
.SetListNumbered(NumerationStyle.LowerRoman,1).SetFontColor(Color.Blue).ToSection()
.AddParagraph(“USA”)
.SetListNumbered(NumerationStyle.LowerRoman,1).SetFontColor(Color.Blue).ToSection()
.ToDocument();
The result will be like this:
10.png

In this tutorial, we considered how to create a simple PDF document from scratch and learned how to generate the most important and common PDF items using PDFFlow.

You can find more useful examples on generating PDF docs on GitHub here

For more information about the PDFFlow library, check out the GS PDFFlow website

 
Back
Top Bottom