How to Convert RTF to PDF in C#

RTF is abbreviated from Rich Text Format and it is widely used by developers to exchange text files between different word processors in different operating systems. Sometimes you may need to convert RTF file into PDF to be displayed to others and not to be changed easily. Spire.PDF, as a powerful .NET PDF component, enables developers to convert files from RTF to PDF easily. This article will show you how to convert RTF into PDF in C#.

Firstly, please check the original RTF file:

How to Convert RTF to PDF in C#

Step 1: Create a PDF document.

PdfDocument pdf = new PdfDocument();

Step 2: Set the margin for the PDF.

PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;

Step 3: Create one page.

PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, margin);

Step 4: Load the RTF document.

String rtf = System.IO.File.ReadAllText("sample.rtf");
page.LoadFromRTF(rtf, page.Canvas.ClientSize.Width, true)

Step 5: Save to document into PDF.

pdf.SaveToFile("FromRTF.pdf");

Effective screenshot of the result PDF file:

How to Convert RTF to PDF in C#

Full codes:

static void Main(string[] args)
{
    PdfDocument pdf = new PdfDocument();

    PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
    PdfMargins margin = new PdfMargins();
    margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
    margin.Bottom = margin.Top;
    margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;

    PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, margin);

    String rtf = System.IO.File.ReadAllText("sample.rtf");
    page.LoadFromRTF(rtf, page.Canvas.ClientSize.Width, true);

    pdf.SaveToFile("FromRTF.pdf");

}