Convert RTF to PDF

The RTF to PDF Converter component allows you to convert RTF documents to PDF.

This component is bundled and distributed as separate NuGet packages for Windows, Linux and macOS, each including the same .NET Standard 2.0 library and different native runtimes. Targeting .NET Standard 2.0 makes the packages compatible with a wide range of .NET Core and .NET Framework versions.

You can reference the Winnovative.Pdf.Next.RtfToPdf.Windows NuGet package in applications running on Windows or the Winnovative.Pdf.Next.RtfToPdf.Linux NuGet package in applications running on Linux to enable RTF to PDF conversion in your application. The package for Windows is referenced by the Winnovative.Pdf.Next.Windows metapackage for all components and the package for Linux is referenced by the Winnovative.Pdf.Next.Linux metapackage for all components.

There are also multiplatform metapackages that reference both the Windows x64 and Linux x64 RTF to PDF packages: Winnovative.Pdf.Next.RtfToPdf for the RTF to PDF functionality and Winnovative.Pdf.Next for the entire Winnovative PDF Next library.

For macOS on Apple Silicon (ARM64), the Winnovative.Pdf.Next.RtfToPdf.MacOS package can be referenced.

For Windows ARM64 and Linux ARM64, the Winnovative.Pdf.Next.RtfToPdf.Windows.Arm64 and Winnovative.Pdf.Next.RtfToPdf.Linux.Arm64 packages can be referenced.

Overview

The Winnovative.Pdf.NextRtfToPdfConverter class allows you to load a RTF file and generate a PDF document, with optional control over page formatting, layout and visual elements such as headers and footers and table of contents creation.

The converter renders the header and footer of the RTF document on the PDF pages and an RTF document can also be rendered in the pages of a PDF document created from code, between the other elements of the document.

Create the RTF to PDF Converter

The Winnovative.Pdf.NextRtfToPdfConverter class is used to convert RTF documents to PDF. You can create an instance using the default constructor, which initializes the converter with standard settings. These settings can later be customized through the RtfToPdfConverterPdfDocumentOptions property which exposes an object of RtfToPdfDocumentOptions type controlling various aspects of the generated PDF document.

Create a RTF to PDF Converter Instance
// Create a new RTF to PDF converter instance
RtfToPdfConverter rtfToPdfConverter = new RtfToPdfConverter();

Note that RtfToPdfConverter instances are not reusable. You must create a new instance for each conversion. Reusing an instance after a completed conversion will result in an exception.

Configure the PDF Page Settings

The format of the generated PDF document pages is controlled by the PDF page settings defined through the RtfToPdfConverterPdfDocumentOptions property. An object of type RtfToPdfDocumentOptions is exposed through the RtfToPdfConverterPdfDocumentOptions property.

The following example shows how to configure page size, orientation and margins.

Use Custom PDF Page Settings
rtfToPdfConverter.PdfDocumentOptions.UsePageSettingsFromRtf = false;
rtfToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
rtfToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape;
rtfToPdfConverter.PdfDocumentOptions.LeftMargin = 20;
rtfToPdfConverter.PdfDocumentOptions.RightMargin = 20;
rtfToPdfConverter.PdfDocumentOptions.TopMargin = 30;
rtfToPdfConverter.PdfDocumentOptions.BottomMargin = 30;

Add HTML Headers and Footers

You can add a header or footer from a URL or from an HTML string. The header and footer can include variables such as {page_number} or {total_pages} and support automatic resizing.

The creation of the HTML header and footer is controlled by the RtfToPdfDocumentOptionsPdfHtmlHeader and RtfToPdfDocumentOptionsPdfHtmlFooter properties. These properties expose objects of type PdfHtmlHeaderFooter, which derives from PdfHtmlTemplate.

The RtfToPdfDocumentOptions object is exposed through the RtfToPdfConverterPdfDocumentOptions property.

The header and footer options are similar to those available in the HTML to PDF Converter and are described in detail in the HTML Header and Footer with Page Numbers documentation section.

Table of Contents

If RtfToPdfDocumentOptionsGenerateTableOfContents is set to true, the converter will automatically create a table of contents based on the titles and subtitles defined in the RTF document using heading styles. The creation and appearance of the table of contents are controlled by the properties of a TableOfContentsOptions object exposed through the RtfToPdfDocumentOptionsTableOfContents property.

The RtfToPdfDocumentOptions object is exposed through the RtfToPdfConverterPdfDocumentOptions property.

The following example shows how enable the automatic generation of a table of contents.

Generate Table of Contents
rtfToPdfConverter.PdfDocumentOptions.GenerateTableOfContents = true;

Content Wider than the Page

The content is laid out at the width of the page, between the margins, and keeps the size it has in the document. Images wider than the page are reduced to the page width and long words are wrapped, so most documents need nothing more. An element that cannot be reduced on its own, such as a table whose columns hold codes or addresses that cannot be broken between letters, extends beyond the right margin and its right part is cut off.

When RtfToPdfDocumentOptionsFitWideContentToPage is set to true, the whole content is scaled down as much as needed to show such an element entirely, which also makes the rest of the content smaller. The default value is false; the option matters only for documents with content wider than the page.

Fit Wide Content to Page
rtfToPdfConverter.PdfDocumentOptions.FitWideContentToPage = true;

Convert RTF to PDF

To convert an RTF document from a memory buffer to a PDF document in a memory buffer use the RtfToPdfConverterConvertToPdf(Byte) method. The parameter is the RTF document read into a memory buffer.

Convert RTF from Memory to PDF in Memory
byte[] outPdfBuffer = rtfToPdfConverter.ConvertToPdf(rtfBytes);

To convert an RTF document from a stream to a PDF document in a memory buffer use the RtfToPdfConverterConvertStreamToPdf(Stream) method. The parameter is the stream providing the RTF content bytes.

Convert RTF Stream to PDF in Memory
byte[] outPdfBuffer = rtfToPdfConverter.ConvertStreamToPdf(rtfStream);

You can convert an RTF string to a PDF document in a memory buffer using the RtfToPdfConverterConvertStringToPdf(String) method. The parameter is the RTF content as a string.

Convert RTF String to PDF in Memory
byte[] outPdfBuffer = rtfToPdfConverter.ConvertStringToPdf(rtfString);

To convert an RTF file to a PDF document in a memory buffer use the RtfToPdfConverterConvertFileToPdf(String) method. The parameter is the full path of the RTF file to be converted.

Convert RTF File to PDF in Memory
byte[] outPdfBuffer = rtfToPdfConverter.ConvertFileToPdf(rtfFilePath);

After conversion the resulting PDF document is returned as a byte array for in-memory processing such as streaming to a web client or saving to a database or a file.

For example you can write the byte array to disk to store the PDF as a file.

Write PDF Data to File
File.WriteAllBytes("output.pdf", outPdfBuffer);

There are also methods to convert an RTF document to a PDF file directly.

To convert an RTF document from a memory buffer to a PDF file use the RtfToPdfConverterConvertToPdfFile(Byte, String) method. The first parameter is the RTF document read into a memory buffer and the second parameter is the full path of the output PDF file.

Convert RTF from Memory to PDF File
rtfToPdfConverter.ConvertToPdfFile(rtfBytes, outputPdfFilePath);

To convert an RTF document from a stream to a PDF file use the RtfToPdfConverterConvertStreamToPdfFile(Stream, String) method. The first parameter is the stream providing the RTF content bytes and the second parameter is the full path of the output PDF file.

Convert RTF from Stream to PDF File
rtfToPdfConverter.ConvertStreamToPdfFile(rtfStream, outputPdfFilePath);

To convert an RTF string to a PDF file use the RtfToPdfConverterConvertStringToPdfFile(String, String) method. The first parameter is the RTF content as a string and the second parameter is the full path of the output PDF file.

Convert RTF String to PDF File
rtfToPdfConverter.ConvertStringToPdfFile(rtfString, outputPdfFilePath);

To convert an RTF file to a PDF file use the RtfToPdfConverterConvertFileToPdfFile(String, String) method. The first parameter is the full path of the RTF file to be converted and the second parameter is the full path of the output PDF file.

Convert RTF File to PDF File
rtfToPdfConverter.ConvertFileToPdfFile(rtfFilePath, outputPdfFilePath);

Asynchronous RTF to PDF Methods

There are also asynchronous variants of these methods that follow the Task-based Asynchronous Pattern (TAP) in .NET, allowing RTF to PDF conversion to run in parallel using async and await. These methods share the same names as their synchronous counterparts and include the "Async" suffix. They also accept an optional System.ThreadingCancellationToken parameter that can be used to cancel the conversion operation where applicable.

To convert an RTF document from a memory buffer to a PDF document in a memory buffer, use the RtfToPdfConverterConvertToPdfAsync(Byte, CancellationToken) method. The parameter is the RTF document read into a memory buffer.

Convert RTF from Memory to PDF in Memory
byte[] outPdfBuffer = await rtfToPdfConverter.ConvertToPdfAsync(rtfBytes);

To convert an RTF document from a stream to a PDF document in a memory buffer, use the RtfToPdfConverterConvertStreamToPdfAsync(Stream, CancellationToken) method. The parameter is the stream providing the RTF content bytes.

Convert RTF Stream to PDF in Memory
byte[] outPdfBuffer = await rtfToPdfConverter.ConvertStreamToPdfAsync(rtfStream);

You can convert an RTF string to a PDF document in a memory buffer using the RtfToPdfConverterConvertStringToPdfAsync(String, CancellationToken) method. The parameter is the RTF content as a string.

Convert RTF String to PDF in Memory
byte[] outPdfBuffer = await rtfToPdfConverter.ConvertStringToPdfAsync(rtfString);

To convert an RTF file to a PDF document in a memory buffer, use the RtfToPdfConverterConvertFileToPdfAsync(String, CancellationToken) method. The parameter is the full path of the RTF file to be converted.

Convert RTF File to PDF in Memory
byte[] outPdfBuffer = await rtfToPdfConverter.ConvertFileToPdfAsync(rtfFilePath);

There are also methods to convert an RTF document to a PDF file directly.

To convert an RTF document from a memory buffer to a PDF file, use the RtfToPdfConverterConvertToPdfFileAsync(Byte, String, CancellationToken) method. The first parameter is the RTF document read into a memory buffer and the second parameter is the full path of the output PDF file.

Convert RTF from Memory to PDF File
await rtfToPdfConverter.ConvertToPdfFileAsync(rtfBytes, outputPdfFilePath);

To convert an RTF document from a stream to a PDF file, use the RtfToPdfConverterConvertStreamToPdfFileAsync(Stream, String, CancellationToken) method. The first parameter is the stream providing the RTF content bytes and the second parameter is the full path of the output PDF file.

Convert RTF from Stream to PDF File
await rtfToPdfConverter.ConvertStreamToPdfFileAsync(rtfStream, outputPdfFilePath);

To convert an RTF string to a PDF file, use the RtfToPdfConverterConvertStringToPdfFileAsync(String, String, CancellationToken) method. The first parameter is the RTF content as a string and the second parameter is the full path of the output PDF file.

Convert RTF String to PDF File
await rtfToPdfConverter.ConvertStringToPdfFileAsync(rtfString, outputPdfFilePath);

To convert an RTF file to a PDF file, use the RtfToPdfConverterConvertFileToPdfFileAsync(String, String, CancellationToken) method. The first parameter is the full path of the RTF file to be converted and the second parameter is the full path of the output PDF file.

Convert RTF File to PDF File
await rtfToPdfConverter.ConvertFileToPdfFileAsync(rtfFilePath, outputPdfFilePath);

Page Settings from the RTF Document

The page size, orientation and margins of the RTF document are used for the PDF pages when UsePageSettingsFromRtf is true, the default; the page size, orientation, margins and zoom set in the document options apply when it is false.

Use Custom Page Settings
rtfToPdfConverter.PdfDocumentOptions.UsePageSettingsFromRtf = false;
rtfToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
rtfToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape;

Conversion Information

After a conversion completes, ConversionInfo is a RtfToPdfConversionInfo object with the number of pages generated from the RTF document, the pages of the table of contents and of the external PDF documents inserted before and after it and the total number of pages of the generated document, like the HTML to PDF converter described in the Retrieve HTML to PDF Conversion Information topic.

Read the Conversion Information
byte[] outPdfBuffer = rtfToPdfConverter.ConvertToPdf(inputBytes);

Console.WriteLine("Pages from the document: {0}", rtfToPdfConverter.ConversionInfo.PagesFromDocument);
Console.WriteLine("Total pages: {0}", rtfToPdfConverter.ConversionInfo.TotalPages);

Code Sample - Convert RTF to PDF

Convert RTF to PDF in ASP.NET Core
using System;
using System.IO;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Winnovative_Next_AspNetDemo.Models;
using Winnovative_Next_AspNetDemo.Models.RTF_to_PDF;

// Use Winnovative Namespace
using Winnovative.Pdf.Next;

namespace Winnovative_Next_AspNetDemo.Controllers.RTF_to_PDF
{
    public class RTF_to_PDFController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;

        public RTF_to_PDFController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            var model = SetViewModel();

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> ConvertRtfToPdf(RTF_to_PDF_ViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
                throw new ValidationException(errorMessage);
            }

            // Set the license key received after purchase to use the library in licensed mode; leave it commented for demo mode
            // Licensing.LicenseKey = "your-license-key";

            // Create an RTF to PDF converter object with default settings
            RtfToPdfConverter rtfToPdfConverter = new RtfToPdfConverter();

            // Set whether a table of contents is automatically generated from headings
            rtfToPdfConverter.PdfDocumentOptions.GenerateTableOfContents = model.GenerateToc;

            // Set whether the whole content is scaled down to show entirely an element wider than the page that cannot be
            // reduced on its own, such as a table whose columns cannot be wrapped; by default the content is not scaled down
            rtfToPdfConverter.PdfDocumentOptions.FitWideContentToPage = model.FitWideContentToPage;

            // Set whether to use the page settings (size, orientation, margins) of the RTF document or the custom settings
            rtfToPdfConverter.PdfDocumentOptions.UsePageSettingsFromRtf = model.PdfPageSettingsMode == "FromRtfDocument";

            if (!rtfToPdfConverter.PdfDocumentOptions.UsePageSettingsFromRtf)
            {
                // Set PDF page size which can be a predefined size like A4 or a custom size in points 
                // Leave it not set to have a default A4 PDF page
                rtfToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize(model.PdfPageSize);

                // Set PDF page orientation to Portrait or Landscape
                // Leave it not set to have a default Portrait orientation for PDF page
                rtfToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation(model.PdfPageOrientation);

                // Set PDF page margins in points or leave them not set to have a PDF page without margins
                rtfToPdfConverter.PdfDocumentOptions.LeftMargin = model.LeftMargin;
                rtfToPdfConverter.PdfDocumentOptions.RightMargin = model.RightMargin;
                rtfToPdfConverter.PdfDocumentOptions.TopMargin = model.TopMargin;
                rtfToPdfConverter.PdfDocumentOptions.BottomMargin = model.BottomMargin;

                // Set the RTF viewer zoom percentage
                rtfToPdfConverter.PdfDocumentOptions.Zoom = model.RtfViewerZoom;
            }

            // Set PDF header and footer
            SetHeader(rtfToPdfConverter, model);
            SetFooter(rtfToPdfConverter, model);

            byte[] inputRtfBytes = null;

            // If an uploaded file exists, use it with priority
            if (model.RtfFile != null && model.RtfFile.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream();
                    await model.RtfFile.CopyToAsync(ms);
                    inputRtfBytes = ms.ToArray();
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to read the uploaded RTF file", ex);
                }
            }
            else
            {
                // Otherwise, fall back to the URL
                string rtfUrl = model.RtfFileUrl?.Trim();
                if (string.IsNullOrWhiteSpace(rtfUrl))
                    throw new Exception("No RTF file provided: upload a file or specify a URL");

                try
                {
                    if (rtfUrl.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
                    {
                        string localPath = new Uri(rtfUrl).LocalPath;
                        inputRtfBytes = await System.IO.File.ReadAllBytesAsync(localPath);
                    }
                    else
                    {
                        using var httpClient = new System.Net.Http.HttpClient();
                        inputRtfBytes = await httpClient.GetByteArrayAsync(rtfUrl);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Could not download the RTF file from URL", ex);
                }
            }

            // The buffer to receive the generated PDF document
            byte[] outPdfBuffer = rtfToPdfConverter.ConvertToPdf(inputRtfBytes);

            if (model.AddConversionInfoPage)
            {
                // The information about the conversion is available after it completes: the pages generated from the
                // document, the pages of the table of contents and of the external PDF documents inserted before and
                // after it and the total number of pages. It is written in a page added at the end of the document
                var conversionInfo = rtfToPdfConverter.ConversionInfo;
                string infoText = "Pages generated from the RTF document: " + conversionInfo.PagesFromDocument + "\n" +
                    "Pages of the table of contents inserted before the content: " + conversionInfo.TocPagesInsertedBefore + "\n" +
                    "Pages of external PDF documents inserted before the content: " + conversionInfo.ExternalPagesInsertedBefore + "\n" +
                    "Total pages inserted before the content: " + conversionInfo.TotalPagesInsertedBefore + "\n" +
                    "Pages inserted after the content: " + conversionInfo.ExternalPagesInsertedAfter + "\n" +
                    "Total pages of the generated document: " + conversionInfo.TotalPages;

                using PdfEditor pdfEditor = new PdfEditor(outPdfBuffer, null);
                int infoPageNumber = pdfEditor.AddPage(PdfPageSize.A4, PdfPageOrientation.Portrait);
                string fontFilePath = System.IO.Path.Combine(m_hostingEnvironment.ContentRootPath, "wwwroot", "DemoAppFiles", "Input", "Font_Files", "DejaVuSerif.ttf");
                PdfFont infoFont = PdfFontManager.CreateFont(fontFilePath, 10f, PdfFontStyle.Normal, PdfColor.Black);
                pdfEditor.AddText(infoPageNumber, new PdfTextElement("Conversion Information", PdfFontManager.CreateFont(fontFilePath, 14f, PdfFontStyle.Bold, PdfColor.DarkBlue)) { X = 40, Y = 40 });
                pdfEditor.AddText(infoPageNumber, new PdfTextElement(infoText, infoFont) { X = 40, Y = 70, Width = 515 });
                outPdfBuffer = pdfEditor.Save();
            }

            // Send the PDF file to browser
            FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
            // send as attachment
            fileResult.FileDownloadName = "RTF_to_Pdf.pdf";

            return fileResult;
        }

        private void SetHeader(RtfToPdfConverter rtfToPdfConverter, RTF_to_PDF_ViewModel model)
        {
            bool headerEnabled = model.HeaderEnabled;
            if (!headerEnabled)
                return;

            // Set the header HTML from a URL or from an HTML string
            bool headerHtmlFromUrl = model.HeaderHtmlSource == "Url";
            if (headerHtmlFromUrl)
            {
                string headerUrl = model.HeaderUrlTextBox;

                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.HtmlSourceUrl = headerUrl;
            }
            else
            {
                string headerHtml = model.HeaderHtmlTextBox;
                string headerHtmlBaseUrl = model.HeaderHtmlBaseUrlTextBox;

                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.Html = headerHtml;
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.HtmlBaseUrl = headerHtmlBaseUrl;
            }

            // Enable automatic height adjustment based on header HTML content
            bool autoSizeHeaderContentHeight = model.AutoSizeHeaderContentHeight;
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.AutoSizeContentHeight = autoSizeHeaderContentHeight;

            // Set the minimum and maximum content height used when AutoSizeContentHeight is enabled
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.MinContentHeight = model.HeaderMinContentHeight;
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.MaxContentHeight = model.HeaderMaxContentHeight;

            // Set a fixed height for the header if AutoResizeHeight is disabled
            if (model.HeaderHeight.HasValue)
            {
                int headerHeight = model.HeaderHeight.Value;
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.Height = headerHeight;
            }

            // If AutoResizeHeight is enabled and both Height and FitHeight are set,
            // the content may be scaled down to fit the specified height
            bool fitHeaderHeight = model.FitHeaderHeight;
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.FitHeight = fitHeaderHeight;

            // Enable automatic top margin adjustment in the PDF based on the header
            bool autoResizeTopMargin = model.AutoResizeTopMargin;
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.AutoResizePdfMargins = autoResizeTopMargin;

            // Set header visibility on specific PDF pages: first page, odd-numbered pages and even-numbered pages
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ShowInFirstPage = model.ShowHeaderInFirstPage;
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ShowInOddPages = model.ShowHeaderInOddPages;
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ShowInEvenPages = model.ShowHeaderInEvenPages;

            // Reserve space for the header on all pages, regardless of visibility
            // If false, the document will be rendered using print styles instead of screen styles
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ReserveSpaceAlways = model.ReserveHeaderSpace;

            // Optimize the header rendering time by providing a hint if the HTML template contains variables such as { page_number} or { total_pages}
            rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.SkipVariablesParsing = model.SkipHeaderVariablesParsing;

            // Optionally set additional time to wait for the asynchronous header HTML content before rendering
            if (model.HeaderConversionDelay.HasValue)
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ConversionDelay = model.HeaderConversionDelay.Value;
        }

        private void SetFooter(RtfToPdfConverter rtfToPdfConverter, RTF_to_PDF_ViewModel model)
        {
            bool footerEnabled = model.FooterEnabled;
            if (footerEnabled)
            {
                // Set the footer HTML from a URL or from an HTML string
                bool footerHtmlFromUrl = model.FooterHtmlSource == "Url";
                if (footerHtmlFromUrl)
                {
                    string footerUrl = model.FooterUrlTextBox;

                    rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.HtmlSourceUrl = footerUrl;
                }
                else
                {
                    string footerHtml = model.FooterHtmlTextBox;
                    string footerHtmlBaseUrl = model.FooterHtmlBaseUrlTextBox;

                    rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.Html = footerHtml;
                    rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.HtmlBaseUrl = footerHtmlBaseUrl;
                }

                // Enable automatic height adjustment based on footer HTML content
                bool autoSizeFooterContentHeight = model.AutoSizeFooterContentHeight;
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.AutoSizeContentHeight = autoSizeFooterContentHeight;

                // Set the minimum and maximum content height used when AutoSizeContentHeight is enabled
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.MinContentHeight = model.FooterMinContentHeight;
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.MaxContentHeight = model.FooterMaxContentHeight;

                // Set a fixed height for the footer if AutoResizeHeight is disabled
                if (model.FooterHeight.HasValue)
                {
                    int footerHeight = model.FooterHeight.Value;
                    rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.Height = footerHeight;
                }

                // If AutoResizeHeight is enabled and both Height and FitHeight are set,
                // the content may be scaled down to fit the specified height
                bool fitFooterHeight = model.FitFooterHeight;
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.FitHeight = fitFooterHeight;

                // Enable automatic bottom margin adjustment in the PDF based on the footer
                bool autoResizeBottomMargin = model.AutoResizeBottomMargin;
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.AutoResizePdfMargins = autoResizeBottomMargin;

                // Set footer visibility on specific PDF pages: first page, odd-numbered pages and even-numbered pages
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ShowInFirstPage = model.ShowFooterInFirstPage;
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ShowInOddPages = model.ShowFooterInOddPages;
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ShowInEvenPages = model.ShowFooterInEvenPages;

                // Reserve space for the footer on all pages, regardless of visibility
                // If false, the document will be rendered using print styles instead of screen styles
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ReserveSpaceAlways = model.ReserveFooterSpace;

                // Optimize the footer rendering time by providing a hint if the HTML template contains variables such as { page_number} or { total_pages}
                rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.SkipVariablesParsing = model.SkipFooterVariablesParsing;

                // Optionally set additional time to wait for the asynchronous footer HTML content before rendering
                if (model.FooterConversionDelay.HasValue)
                    rtfToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ConversionDelay = model.FooterConversionDelay.Value;
            }
        }

        private PdfPageSize SelectedPdfPageSize(string selectedValue)
        {
            switch (selectedValue)
            {
                case "A0":
                    return PdfPageSize.A0;
                case "A1":
                    return PdfPageSize.A1;
                case "A10":
                    return PdfPageSize.A10;
                case "A2":
                    return PdfPageSize.A2;
                case "A3":
                    return PdfPageSize.A3;
                case "A4":
                    return PdfPageSize.A4;
                case "A5":
                    return PdfPageSize.A5;
                case "A6":
                    return PdfPageSize.A6;
                case "A7":
                    return PdfPageSize.A7;
                case "A8":
                    return PdfPageSize.A8;
                case "A9":
                    return PdfPageSize.A9;
                case "ArchA":
                    return PdfPageSize.ArchA;
                case "ArchB":
                    return PdfPageSize.ArchB;
                case "ArchC":
                    return PdfPageSize.ArchC;
                case "ArchD":
                    return PdfPageSize.ArchD;
                case "ArchE":
                    return PdfPageSize.ArchE;
                case "B0":
                    return PdfPageSize.B0;
                case "B1":
                    return PdfPageSize.B1;
                case "B2":
                    return PdfPageSize.B2;
                case "B3":
                    return PdfPageSize.B3;
                case "B4":
                    return PdfPageSize.B4;
                case "B5":
                    return PdfPageSize.B5;
                case "Flsa":
                    return PdfPageSize.Flsa;
                case "HalfLetter":
                    return PdfPageSize.HalfLetter;
                case "Ledger":
                    return PdfPageSize.Ledger;
                case "Legal":
                    return PdfPageSize.Legal;
                case "Letter":
                    return PdfPageSize.Letter;
                case "Letter11x17":
                    return PdfPageSize.Letter11x17;
                case "Note":
                    return PdfPageSize.Note;
                default:
                    return PdfPageSize.A4;
            }
        }

        private PdfPageOrientation SelectedPdfPageOrientation(string selectedValue)
        {
            return selectedValue == "Portrait" ? PdfPageOrientation.Portrait : PdfPageOrientation.Landscape;
        }

        private RTF_to_PDF_ViewModel SetViewModel()
        {
            var model = new RTF_to_PDF_ViewModel();

            var contentRootPath = System.IO.Path.Combine(m_hostingEnvironment.ContentRootPath, "wwwroot");

            HttpRequest request = ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = request.Scheme;
            uriBuilder.Host = request.Host.Host;
            if (request.Host.Port != null)
                uriBuilder.Port = (int)request.Host.Port;
            uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
            uriBuilder.Query = request.QueryString.ToString();

            string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
            string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "RTF_To_PDF".Length);

            model.RtfFileUrl = rootUrl + "/DemoAppFiles/Input/RTF_Files/RTF_Document.rtf";
            model.HeaderHtmlTextBox = System.IO.File.ReadAllText(System.IO.Path.Combine(contentRootPath, "DemoAppFiles/Input/HTML_Files/Header_HTML.html"));
            model.FooterHtmlTextBox = System.IO.File.ReadAllText(System.IO.Path.Combine(contentRootPath, "DemoAppFiles/Input/HTML_Files/Footer_HTML.html"));
            model.HeaderHtmlBaseUrlTextBox = rootUrl + "DemoAppFiles/Input/HTML_Files/";
            model.HeaderUrlTextBox = rootUrl + "DemoAppFiles/Input/HTML_Files/Header_HTML.html";
            model.FooterHtmlBaseUrlTextBox = rootUrl + "DemoAppFiles/Input/HTML_Files/";
            model.FooterUrlTextBox = rootUrl + "DemoAppFiles/Input/HTML_Files/Footer_HTML.html";

            return model;
        }
    }
}

See Also