Introduction
In this article, we will see how we can convert a string of data to PDF and then send an email with an attached copy of the generated PDF.
Firstly, we can convert the string of data to PDF by using Popular Library for rendering PDF is ItextSharp. Secondly, we can attach the converted PDF file to an email and send it to the recipient by using the built-in C# Mail messages Class.
So, let's start to build our first step.
Step 1. Convert HTML String to PDF
In this step, we will first create a button that will do the rest of the work on the Click event.
Let's create the button to perform the required operation.
The UI view looks like the following.

So our front end is all set, and we need to apply the CS logic to perform the operation.
Let's start building an HTML string.
I am using the StringBuilder class for generating HTML string and passing it to the parser for generating PDF. Before proceeding further, add the following references.
Now let's write the code for generating in-memory PDF from HTML string.
Now let's understand the Line of code. After building the string, we can read from the string as we have passed the generated string.
We are building the PDF document with a default page size of A4 Page size.
Parse the HTML string using the HTMLWorker of Itextsharp library.
Use the memory stream to keep the file in memory.
Now we get the PDF and memory stream to create the instance and write the document. Then first open the document, parse by the html worker, and then after completing the work, close the document (dispose of the resources), managing the resource properly.
Now we add the created document to the memory stream and use the bytes of it as an in-memory reference to later attach to the email.
This is all about the first step, which will generate the PDF file, and we will later use this as an attachment.
First Output
![]()
Now let's proceed to the second step.
Step 2. Email the Generated PDF File as an attachment.
We will now use the Mail Message class to send emails with in-memory generated PDF files.
You can use any email you receive from ID by just authorizing the account i.e, providing the network credentials. I have also used some application settings from the web. config file and use it here to get from there.
Final Output
![invoicepdf]()
Read more articles on C#.