This short article explains the step-by-step procedure to convert Text to PDF in C#. We will use one of the popular document conversion APIs for performing the document transformation and develop the working example for C# Text to PDF functionality. Below you can find the stepwise instructions as well as sample code for converting Text to PDF using C#.
Steps to Convert Text to PDF in C#
- Install GroupDocs.Conversion for .NET package from the NuGet in the .NET application to convert Text to PDF
- Add a reference to the GroupDocs.Conversion namespace for developing the Text to PDF functionality
- Instantiate Converter class and pass the input Text file to its constructor
- Create an object of the PdfConvertOptions class and define properties for customizing the PDF document
- Call the Convert method of the Converter class to save Text as a PDF document
The convert TXT to PDF C# functionality can be implemented by following the above points. The document conversion can be done by writing a few lines of code that consists of API calls of the document conversion library. These steps do not require installing any third-party software and can be used on any operating system like MS Windows, Linux, and Mac OS that support a .NET environment.
Code to Convert Text to PDF in C#
using System; | |
using GroupDocs.Conversion.Options.Convert; | |
namespace ConvertTextToPdfInCSharp | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) // Main function to convert Text to PDF using C# | |
{ | |
// Remove the watermark in output PDF document by adding license | |
string licensePath = "GroupDocs.Conversion.lic"; | |
GroupDocs.Conversion.License lic = new GroupDocs.Conversion.License(); | |
lic.SetLicense(licensePath); | |
// Load the source Text file for conversion to PDF | |
var converterObj = new GroupDocs.Conversion.Converter("sample.txt"); | |
// Set the conversion options for PDF document to customize the output file | |
PdfConvertOptions options = new PdfConvertOptions(); | |
// Convert and save the TXT in PDF format | |
converterObj.Convert("converted.pdf", options); | |
Console.WriteLine("Done"); | |
} | |
} | |
} |
In the above code snippet, we have created the C# convert TXT to PDF capability for demonstration. You can see in the example, that the Converter class is used for loading the input text file for conversion after adding the essential namespace. Then, instantiate PdfConvertOptions class for defining the parameters for customizing the output PDF document. Finally, the Convert method enables storing the resulting file to the disc.
We have discussed the document transformation process to create the Text to PDF C# functionality. Recently, we published an article to change SVG to PDF using C#, have a look at how to convert SVG to PDF in C# guide for more information.