iTextSharp is an advanced .NET library that allows us to create pdf documents from our .NET applications. It provides functionalities to create documents and reports based on data from databases or XML files and merge or split pages from existing PDF files. In this post, we will explore a step by step tutorial to configure and use iTextSharp in a .NET Core console application, you can follow the same steps if you want to use iTextSharp in an ASP.NET web application.
Step 1: Installing iTextSharp for .NET Core
iTextSharp can be downloaded from NuGet. The package name is "iTextSharp.LGPLv2.Core"
You can use the GUI or the following command in the Package Manager Console:
PM> Install-Package iTextSharp.LGPLv2.Core -Version 1.7.5
That's it, you can now compile and run your application and you will be able to use iTextSharp.
Step 2: Use iTextSharp to Create a Simple PDF File
In this step, we initialized a simple string that contains the text we want to add to the pdf. Then we initialized the Document, and we used the A4 as page size.
The following .NET code is used to create a simple PDF file with one paragraph:
using iTextSharp.text;
using iTextSharp.text.pdf;
string text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.";
Document pdfDoc = new Document(PageSize.A4, 7f, 5f, 5f, 0f);
try
{
Font mainFont = FontFactory.GetFont("Verdana", 11, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000")));
string newFilePath = "D:\\temp\\iTextSharp\\" + "HelloWord.pdf";
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(newFilePath, FileMode.Create));
pdfDoc.Open();
text = text.Replace(Environment.NewLine, String.Empty).Replace(" ", String.Empty);
Chunk beginning = new Chunk(text, mainFont);
Phrase p1 = new Phrase(beginning);
Paragraph p = new Paragraph();
p.Add(p1);
pdfDoc.Add(p);
}
catch (DocumentException ex)
{
throw (ex);
}
catch (IOException ex)
{
throw (ex);
}
finally
{
pdfDoc.Close();
}
Console.WriteLine("The file is created.");
Console.ReadLine();
As you can see, we are able to set the font family and the font size and where to save the created pdf. It is important to close the current document and releases any system resources associated with it. Following a call to Close, any operations on the iTextSharp Document might raise exceptions.