.NET (1322)
Children categories
Rich Text Format (RTF) is a proprietary text file format which can serve as an exchange format between word processing programs from different manufacturers on different operating systems. Rich text documents include page formatting options, such as custom page margins, line spacing, and tab widths. With rich text, it's easy to create columns, add tables, and format your documents in a way that makes them easier to read. This article will demonstrate how to convert Word Doc/Docx to RTF files and convert RTF to Word Doc/Docx with the help of Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Convert Word Doc/Docx to RTF
The following steps show you how to convert Word to RTF using Spire.Doc for .NET.
- Create a Document instance.
- Load a Word sample document using Document.LoadFromFile() method.
- Save the document as an RTF file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace ConvertToRtf
{
class Program
{
static void Main(string[] args)
{
//Create a Word document instance
Document document = new Document();
//Load a Word sample document
document.LoadFromFile("sample.docx");
// Save the document to RTF
document.SaveToFile("Result.rtf", FileFormat.Rtf);
}
}
}

Convert RTF to Word Doc/Docx
The steps to convert an RTF document to Word Doc/Docx is very similar with that of the above example:
- Create a Document instance.
- Load an RTF document using Document.LoadFromFile() method.
- Save the RTF document to Doc/Docx format using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using System;
public class RtfToDocDocx
{
public static void Main(String[] args)
{
// Create a Document instance
Document document = new Document();
// Load an RTF document
document.LoadFromFile("input.rtf", FileFormat.Rtf);
// Save the document to Doc
document.SaveToFile("toDoc.doc", FileFormat.Doc);
// Save the document to Docx
document.SaveToFile("toDocx.docx", FileFormat.Docx2013);
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
OpenXML is an XML-based file format for MS Office documents. OpenXML is popular among developers as it allows creating and editing Office documents, such Word documents, with no need for MS Office. But when presented to ordinary users, OpenXML files usually need to be converted to Word documents to facilitate reading and editing. In this article, you can learn how to convert XML files to Word documents or Word documents to XML files with the help of Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Convert an OpenXML File to a Word Document
The detailed steps of the conversion are as follows:
- Create an object of Document class.
- Load an OpenXML file from disk using Document.LoadFromFile() method.
- Convert the OpenXML file to a Word document and save it using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using System;
namespace DocExample
{
internal class Program
{
static void Main(string[] args)
{
//Create a Document class instance
Document document = new Document();
//Load an OpenXML file from disk
document.LoadFromFile(@"C:\Samples\Sample.xml", FileFormat.Xml);
//Convert the OpenXML file to a Word document and save it
document.SaveToFile("OpenXMLToWord.docx", FileFormat.Docx2013);
}
}
}

Convert a Word Document to an OpenXML File
The detailed steps of the conversion are as follows:
- Create an object of Document class.
- Load a Word document from disk using Document.LoadFromFile() method.
- Convert the Word document to an OpenXML file and save it using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using System;
namespace DocExample
{
internal class Program
{
static void Main(string[] args)
{
//Create a Document class instance
Document document = new Document();
//Load a Word document from disk
document.LoadFromFile(@"C:\Samples\Sample.docx");
//Convert the Word document to an OpenXML file and save it
//Change WordXML to WordML to convert to ML file
document.SaveToFile("WordToOpenXMl.xml", FileFormat.WordXml);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Microsoft Word and HTML (Hypertext Markup Language) are two of the most widely used formats worldwide. Microsoft Word is the go-to solution for crafting rich, feature-packed documents such as reports, proposals, and print-ready files, while HTML is the foundational language that powers content on the web. Understanding how to effectively convert between these formats can enhance document usability and accessibility.
In this article, we will provide a detailed step-by-step guide on converting HTML to Word and Word to HTML in .NET using C#. It covers the following topics:
- Why Convert Between Word and HTML
- .NET Word Library Installation
- How to Convert HTML to Word Using C#
- How to Convert Word to HTML Using C#
- Conclusion
- FAQs
Why Convert Between Word and HTML?
Before diving into the technical details, let's understand why you might need to convert between Word and HTML:
- Cross-Platform Accessibility: HTML is the backbone of web pages, while Word documents are industry-standard for creating, sharing and editing content. Converting between them enables content to be accessible and editable across different platforms.
- Rich Formatting: Word documents support complex formatting and elements; converting HTML to Word lets users retain formatting when exporting web content.
- Document Archiving and Data Exchange: Archive HTML content as Word or publish Word-based reports to the web.
.NET Word Library Installation
The .NET framework does not natively support HTML or Word conversions. To bridge this gap, Spire.Doc for .NET provides a powerful, developer-friendly API for document creation, manipulation, and conversion—without requiring Microsoft Office or Interop libraries.
Install Spire.Doc for .NET
Before getting started with the conversion, you need to install Spire.Doc for .NET through one of the following methods:
Method 1: Install via NuGet
Run the following command in the NuGet Package Manager Console:
Install-Package Spire.Doc
Method 2: Manually Add the DLLs
You can also download the Spire.Doc for .NET package, extract the files, and then reference Spire.Doc.dll manually in your Visual Studio project.
How to Convert HTML to Word Using C#
Spire.Doc enables you to load HTML files or HTML strings and save them as Word documents. Let’s see how to implement these conversions.
Convert HTML String to Word
To convert an HTML string to Word format, follow these steps:
- Create a Document Object: Instantiate a new Document object.
- Add a Section and Paragraph: Create a section in the document and add a paragraph.
- Append HTML String: Use the Paragraph.AppendHTML() method to include the HTML content.
- Save the Document: Save the document using Document.SaveToFile() with the desired format (e.g., Docx).
Example code
using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
namespace ConvertHtmlStringToWord
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Add a section to the document
Section section = document.AddSection();
// Set the page margins
section.PageSetup.Margins.All = 2;
// Add a paragraph to the section
Paragraph paragraph = section.AddParagraph();
// Read HTML string from a file
string htmlFilePath = @"C:\Users\Administrator\Desktop\Html.html";
string htmlString = File.ReadAllText(htmlFilePath, System.Text.Encoding.UTF8);
// Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString);
// Save the document to a Word file
document.SaveToFile("AddHtmlStringToWord.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}

Convert HTML File to Word
If you have existing HTML files, converting them to Word is straightforward. Here’s how to do that:
- Create a Document Object: Instantiate a new Document object.
- Load the HTML File: Use Document.LoadFromFile() to load the HTML file.
- Save as Word Format: Save the document using Document.SaveToFile() with the desired format (e.g., Docx).
Example Code
using Spire.Doc;
namespace ConvertHtmlToWord
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Load the HTML file
document.LoadFromFile(@"C:\Users\Administrator\Desktop\MyHtml.html", FileFormat.Html);
// Save the file as a Word document
document.SaveToFile("HtmlToWord.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}
How to Convert Word to HTML Using C#
Spire.Doc also supports exporting Word documents (such as .docx and .doc) to HTML format. You can perform basic conversion with default behavior, or customize the output using advanced settings.
Basic Word to HTML Conversion
To convert a Word document to an HTML file using default settings, follow these steps:
- Create a Document Object: Instantiate a new Document object.
- Load the Word Document: Use Document.LoadFromFile() to load the Word document.
- Save as HTML File: Save the document using Document.SaveToFile() with HTML as the format.
Example Code
using Spire.Doc;
namespace BasicWordToHtmlConversion
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Load the Word document
document.LoadFromFile("input.docx");
// Save the document as an HTML file
document.SaveToFile("BasicWordToHtmlConversion.html", FileFormat.Html);
// Dispose resources
document.Dispose();
}
}
}
Advanced Word to HTML Conversion Settings
To tailor the conversion process, use the HtmlExportOptions class, which allows you to adjust a variety of settings, including:
- Whether to export the document's styles.
- Whether to embed images in the converted HTML.
- Whether to export headers and footers.
- Whether to export form fields as text.
Follow these steps to convert a Word document to HTML with customized options:
- Create a Document Object: Instantiate a new Document object.
- Load the Word Document: Use Document.LoadFromFile() to load the Word document.
- Get HtmlExportOptions: Access the HtmlExportOptions through Document.HtmlExportOptions.
- Customize Conversion Settings: Modify the properties of HtmlExportOptions to customize the conversion.
- Save as HTML File: Save the document using Document.SaveToFile() with HTML as the format.
Example Code
using Spire.Doc;
namespace AdvancedWordToHtmlConversion
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("sample.docx");
HtmlExportOptions htmlExportOptions = doc.HtmlExportOptions;
// Set whether to export the document styles
htmlExportOptions.IsExportDocumentStyles = true;
// Set whether to embed the images in the HTML
htmlExportOptions.ImageEmbedded = true;
// Set the type of the CSS style sheet
htmlExportOptions.CssStyleSheetType = CssStyleSheetType.Internal;
// Set whether to export headers and footers
htmlExportOptions.HasHeadersFooters = true;
// Set whether to export form fields as text
htmlExportOptions.IsTextInputFormFieldAsText = false;
// Save the document as an HTML file
doc.SaveToFile("AdvancedWordToHtmlConversion.html", FileFormat.Html);
doc.Close();
}
}
}
Conclusion
Converting HTML to Word and Word to HTML using C# and the Spire.Doc library is a seamless process that enhances document management and accessibility. By following the detailed steps outlined in this tutorial, developers can easily implement these conversions in their applications, improving workflow and productivity.
FAQs
Q1: Is it possible to batch convert multiple Word files to HTML using C#?
A1: Yes, you can loop through a list of Word files and apply the conversion logic in your C# code.
Q2: What types of HTML elements are supported during conversion to Word?
A2: Spire.Doc supports a wide range of HTML elements, including text, tables, images, lists, and more. However, certain elements not supported by Microsoft Word may also not be rendered correctly in Spire.Doc.
Q3: Can I convert formats other than HTML and Word?
A3: Yes. Spire.Doc supports various file format conversions, such as Word to PDF, Markdown to Word, Word to Markdown, RTF to Word, RTF to PDF.
Q4: Is Spire.Doc free to use?
A4: Spire.Doc offers a free version for lightweight use, but for extensive features and commercial use, a licensed version is recommended.
Get a Free License
To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.
When you'd like to put a Word document on the web, it's recommended that you should convert the document to HTML in order to make it accessible via a web page. This article will demonstrate how to convert Word to HTML programmatically in C# and VB.NET using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Convert Word to HTML
The following steps show you how to convert Word to HTML using Spire.Doc for .NET.
- Create a Document instance.
- Load a Word sample document using Document.LoadFromFile() method.
- Save the document as an HTML file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace WordToHTML
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document mydoc = new Document();
//Load a Word document
mydoc.LoadFromFile("sample.docx");
//Save to HTML
mydoc.SaveToFile("WordToHTML.html", FileFormat.Html);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Text files are simple and versatile, but they don't support formatting options and advanced features like headers, footers, page numbers, and styles, and cannot include multimedia content like images or tables. Additionally, spell-checking and grammar-checking features are also not available in plain text editors.
If you need to add formatting, multimedia content, or advanced features to a text document, you'll need to convert it to a more advanced format like Word. Similarly, if you need to simplify the formatting of a Word document, reduce its file size, or work with its content using basic tools, you might need to convert it to a plain text format. In this article, we will explain how to convert text files to Word format and convert Word files to text format in C# and VB.NET using Spire.Doc for .NET library.
- Convert a Text File to Word Format in C# and VB.NET
- Convert a Word File to Text Format in C# and VB.NET
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Convert a Text File to Word Format in C# and VB.NET
Spire.Doc for .NET offers the Document.LoadText(string fileName) method which enables you to load a text file. After the text file is loaded, you can easily save it in Word format by using the Document.SaveToFile(string fileName, FileFormat fileFormat) method. The detailed steps are as follows:
- Initialize an instance of the Document class.
- Load a text file using the Document.LoadText(string fileName) method.
- Save the text file in Word format using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.
- C#
- VB.NET
using Spire.Doc;
namespace ConvertTextToWord
{
internal class Program
{
static void Main(string[] args)
{
//Initialize an instance of the Document class
Document doc = new Document();
//Load a text file
doc.LoadText("Sample.txt");
//Save the text file in Word format
doc.SaveToFile("TextToWord.docx", FileFormat.Docx2016);
doc.Close();
}
}
}

Convert a Word File to Text Format in C# and VB.NET
To convert a Word file to text format, you just need to load the Word file using the Document.LoadFromFile(string fileName) method, and then call the Document.SaveToFile(string fileName, FileFormat fileFormat) method to save it in text format. The detailed steps are as follows:
- Initialize an instance of the Document class.
- Load a Word file using the Document.LoadFromFile(string fileName) method.
- Save the Word file in text format using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.
- C#
- VB.NET
using Spire.Doc;
namespace ConvertWordToText
{
internal class Program
{
static void Main(string[] args)
{
//Initialize an instance of the Document class
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"Sample.docx");
//Save the Word file in text format
doc.SaveToFile("WordToText.txt", FileFormat.Txt);
doc.Close();
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
The sample demonstrates how to work with MailMerge in Silverlight via Spire.Doc.

Efficient C# Image to PDF Guide: Convert JPG/ PNG to PDF with Code Examples
2022-03-30 06:26:00 Written by KoohjiImages (JPG, PNG, BMP, etc.) are common for data capture, but PDFs provide better security, compression, and cross-platform consistency. In .NET development, developers may often need a reliable C# image to PDF solution to streamline workflows like report generation, document archiving, and digital record management.

This guide demonstrates how to efficiently convert images to PDF in C#/ ASP.NET using Spire.PDF for .NET, a powerful library that simplifies this process with robust features and excellent compatibility.
- Set Up Your Project
- How to Convert Image to PDF in C#
- Image to PDF Customization Options
- FAQs (TIFF to PDF, SVG to PDF)
- Conclusion
Set Up Your Project
Before we start writing code to convert images such as PNG to PDF, we need to set up our C# project and add the Spire.PDF library.
Step 1: Create a New C# Project
Open Visual Studio and create a new C# project. You can choose a Console Application, Windows Forms Application, or any other project type depending on your needs.
Step 2: Install Spire.PDF
There are a few ways to add the PDF converter library to your project. One common method is through NuGet Package Manager.
- In Visual Studio, right-click on your project in the Solution Explorer, select "Manage NuGet Packages".
- In the NuGet Package Manager window, search for "Spire.PDF".
- Then, click "Install" to add the latest version of the library to your project.
Once the installation is complete, you'll be able to reference the necessary namespaces in your C# code.
How to Convert Image to PDF in C#
Spire.PDF does not provide a straightforward method to convert images to PDF. But you could create a new PDF document and draw images at the specified locations of a certain page. The following are two code examples for single/multiple image conversion.
Converting a Single Image to PDF
This example shows how to convert a JPG image to a PDF document, with the PDF page match the exact dimensions of the image.
C# code for JPG to PDF conversion:
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace ConvertImageToPdf
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Set the margins to 0
doc.PageSettings.SetMargins(0);
// Load an image
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\announcement.jpg");
// Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
// Add a page of the same size as the image
PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
// Load a JPG image and draw it at (0, 0) of the page
PdfImage pdfImage = PdfImage.FromImage(image);
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
// Save the PDF file
doc.SaveToFile("ConvertPdfWithSameSize.pdf");
}
}
}
Explanation:
- PdfDocument: Represents the PDF file.
- PdfPageBase: A page in the PDF document.
- PdfImage.FromImage: Converts an Image object to a PDF image.
- DrawImage: Renders the image on the PDF page.
Output:

Converting Multiple Images to a Single PDF
If you have multiple images that you want to combine into a single PDF document, the process is similar to the single-image conversion, but with a loop to handle each image.
C# code to convert JPG, PNG, TIFF, BMP to PDF:
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace ConvertMultipleImagesIntoPdf
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Set the page margins to 0
pdf.PageSettings.SetMargins(0);
// Specify the images to be converted
string[] imagePaths = {"Image-1.png", "Image-2.jpg", "Image-3.bmp", "Image-4.tiff"};
// Iterate through each image
foreach (string path in imagePaths)
{
// Load a particular image
Image image = Image.FromFile(path);
// Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
// Add a page that has the same size as the image
PdfPageBase page = pdf.Pages.Add(new SizeF(width, height));
//Create a PdfImage object based on the image
PdfImage pdfImage = PdfImage.FromImage(image);
// Draw image at (0, 0) of the page
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
}
// Save the PDF file
pdf.SaveToFile("CombinaImagesToPdf.pdf");
pdf.Dispose();
}
}
}
This C# code loops through an array of image files in different formats, loads each image, adds it to a new page in the PDF document, and then saves the final PDF with all the images.
Output:

Image to PDF Customization Options
Adjust Page Settings
While conversion, you can customize PDF page properties such as orientation, margins, and size according to the nature of your images:
// Create a PDF document
PdfDocument pdf = new PdfDocument();
// Set page orientation
pdf.PageSettings.Orientation = PdfPageOrientation.Landscape;
// Set page margins (in points, 1 point = 1/72 inch)
pdf.PageSettings.SetMargins(20);
// Set page size
pdf.PageSettings.Size = PdfPageSize.A4;
Resize Images for Optimal Fit
If you need to maintain a fixed PDF page size, you can scale the image to make it fit to page:
// Set fixed page size (e.g., A4)
PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4);
//Load an image
Image image = Image.FromFile("sample.jpg");
// Get the width and heigh of the page
float pageWidth = page.Canvas.ClientSize.Width;
float pageHeight = page.Canvas.ClientSize.Height;
// Scale the image
float scale = Math.Min(pageWidth / image.Width, pageHeight / image.Height);
float scaledWidth = image.Width * scale;
float scaledHeight = image.Height * scale;
// Draw the scaled image on the page
page.Canvas.DrawImage(PdfImage.FromImage(image), 0, 0, scaledWidth, scaledHeight);
FAQs (TIFF to PDF, SVG to PDF)
Q1: What image formats does Spire.PDF support?
A: Spire.PDF seamlessly supports all major image formats:
- JPG/ JPEG
- PNG
- BMP
- TIFF
- GIF
- EMF
- WMF
Ensure your input image is in a supported format for seamless conversion.
Q2: Can I convert a multi-page TIFF image to PDF?
A: Yes! Iterate through TIFF frames to convert. The full code example can be found at: Convert a Multi-Page TIFF Image to a PDF File in C#
Q3: Can I convert SVG image to PDF?
A: Yes! You can load an SVG file with LoadFromSvg() and then save it as a PDF through the SaveToFile(String, FileFormat.PDF) method.
using Spire.Pdf;
namespace SVGtoPDF
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Load a sample SVG file
doc.LoadFromSvg("Sample.svg");
// Save SVG to PDF document
doc.SaveToFile("SVGtoPDF.pdf", FileFormat.PDF);
doc.Dispose();
}
}
}
Q4: Where can I find the VB.NET demos for image to PDF conversion?
A: Spire.PDF fully supports VB.NET. You can convert the C# code samples provided above to VB.NET via code converter tools (e.g. Telerik Code Converter).
Conclusion
With Spire.PDF for .NET, converting images to PDF in C# becomes simple and flexible. This guide shows you how to:
- Convert a single or multiple images into a PDF document.
- Customize page size, margins, and layout for your PDF output.
By following the examples in this guide, you can seamlessly integrate image-to-PDF conversion into your .NET applications.
For advanced features (encryption, annotation), explore Spire.PDF’s online documentation.
Get a Free License
Need to remove watermarks on output files and get rid of restrictions? You can request a 30-day full-featured trial license. A tutorial on how to use the license file is available here.
An Extensible Markup Language (XML) file is a standard text file that utilizes customized tags to describe the structure and other features of a document. By converting XML to PDF, you make it easier to share with others since PDF is a more common and ease-to-access file format. This article will demonstrate how to convert XML to PDF in C# and VB.NET using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Convert XML to PDF
The following are steps to convert XML to PDF using Spire.Doc for .NET.
- Create a Document instance.
- Load an XML sample document using Document.LoadFromFile() method.
- Save the document as a PDF file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace XMLToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document mydoc = new Document();
//Load an XML sample document
mydoc.LoadFromFile(@"XML Sample.xml", FileFormat.Xml);
//Save it to PDF
mydoc.SaveToFile("XMLToPDF.pdf", FileFormat.PDF);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
A text file is a type of computer file that contains plain text. It can be viewed on almost any computer but has very basic and limited functionalities. If you would like to perform more manipulations on text files, such as inserting annotations or form fields, you can convert them to PDF. In this article, we will demonstrate how to convert text files to PDF in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Convert Text Files to PDF in C# and VB.NET
The following are the main steps to convert a text file to PDF using Spire.PDF for .NET:
- Read the text in the text file into a string object using File.ReadAllText() method.
- Create a PdfDocument instance and add a page to the PDF file using PdfDocument.Pages.Add() method.
- Create a PdfTextWidget instance from the text.
- Draw the text onto the PDF page using PdfTextWidget.Draw() method.
- Save the result file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.IO;
namespace ConvertTextToPdf
{
class Program
{
static void Main(string[] args)
{
//Read the text from the text file
string text = File.ReadAllText(@"Input.txt");
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Add a page
PdfPageBase page = pdf.Pages.Add();
//Create a PdfFont instance
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);
//Create a PdfTextLayout instance
PdfTextLayout textLayout = new PdfTextLayout();
textLayout.Break = PdfLayoutBreakType.FitPage;
textLayout.Layout = PdfLayoutType.Paginate;
//Create a PdfStringFormat instance
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Justify;
format.LineSpacing = 20f;
//Create a PdfTextWidget instance from the text
PdfTextWidget textWidget = new PdfTextWidget(text, font, PdfBrushes.Black);
//Set string format
textWidget.StringFormat = format;
//Draw the text at the specified location of the page
RectangleF bounds = new RectangleF(new PointF(10, 25), page.Canvas.ClientSize);
textWidget.Draw(page, bounds, textLayout);
//Save the result file
pdf.SaveToFile("TextToPdf.pdf", FileFormat.PDF);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.