Convert RTF to Markdown

The RTF to Markdown Converter writes the content of RTF documents as Markdown text, with the headings, lists, tables, links, notes and pictures of the document.

The RTF to Markdown Converter is part of the RTF to PDF component of the EvoPdf Next for .NET library. It is available in the applications that reference the NuGet packages of this component, described in the Convert RTF to PDF documentation section.

Convert an RTF Document to Markdown

The EvoPdf.NextRtfToMarkdownConverter class converts an RTF document from a file, from a stream, from a memory buffer or from a string to a Markdown string or to a Markdown file.

Convert an RTF File to Markdown
// Create an RTF to Markdown converter instance
RtfToMarkdownConverter rtfToMarkdownConverter = new RtfToMarkdownConverter();

// Convert the RTF file to a Markdown string
string markdown = rtfToMarkdownConverter.ConvertFileToMarkdown("document.rtf");
Convert an RTF Document from Memory to a Markdown File
RtfToMarkdownConverter rtfToMarkdownConverter = new RtfToMarkdownConverter();

// Convert the RTF document and write the Markdown text to a file encoded as UTF-8
rtfToMarkdownConverter.ConvertToMarkdownFile(rtfBytes, "document.md");
Convert an RTF Stream or an RTF String to Markdown
// Convert the RTF document read from a stream
string markdownFromStream = rtfToMarkdownConverter.ConvertStreamToMarkdown(rtfStream);

// Convert the RTF content given as a string
string markdownFromString = rtfToMarkdownConverter.ConvertStringToMarkdown(rtfContent);

Content Written in Markdown

The Markdown text follows the structure of the RTF document:

  • The headings of the document are written as Markdown headings of the same level

  • The bold, italic and strikethrough text keeps its formatting

  • The numbered and bulleted lists are written as Markdown lists with their nested levels

  • The tables are written as Markdown tables

  • The hyperlinks are written as Markdown links

  • The footnotes are written as Markdown footnotes

Pictures of the Document

The pictures of the document are left out by default. The RtfToMarkdownConverterImageMode property, with a value of the EvoPdf.NextRtfToMarkdownImageMode enumeration, writes the images of the pictures, embedded in the Markdown text or saved as files in a folder.

Embed the Pictures in the Markdown Text
rtfToMarkdownConverter.ImageMode = RtfToMarkdownImageMode.Embed;

When the pictures are saved as files, the RtfToMarkdownConverterImagesFolder property gives the folder and the RtfToMarkdownConverterImageFileName property gives the name of the files, which is followed by a number. The links of the Markdown text use the name of the images folder or the path given by the RtfToMarkdownConverterImagesLinkPath property.

Save the Pictures as Files
rtfToMarkdownConverter.ImageMode = RtfToMarkdownImageMode.File;

// The folder where the image files are saved
rtfToMarkdownConverter.ImagesFolder = "output/document_images";

// Optionally set the path used by the links of the Markdown text and the name of the files
rtfToMarkdownConverter.ImagesLinkPath = "document_images";
rtfToMarkdownConverter.ImageFileName = "picture";

Asynchronous Methods

The conversion methods have asynchronous versions that accept a cancellation token.

Asynchronously Convert an RTF Document to Markdown
string markdown = await rtfToMarkdownConverter.ConvertToMarkdownAsync(rtfBytes, cancellationToken);

Code Sample - Convert RTF to Markdown

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

// Use EVO PDF Namespace
using EvoPdf.Next;

namespace EvoPdf_Next_AspNetDemo.Controllers.RTF_to_PDF
{
    public class RTF_to_MarkdownController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;
        public RTF_to_MarkdownController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

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

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> ConvertRtfToMarkdown(RTF_to_Markdown_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 the RTF to Markdown converter instance with default options
            RtfToMarkdownConverter rtfToMarkdownConverter = new RtfToMarkdownConverter();

            // Leave the pictures out or embed their images in the Markdown text
            rtfToMarkdownConverter.ImageMode = model.ImageMode == "Embed" ? RtfToMarkdownImageMode.Embed : RtfToMarkdownImageMode.None;

            byte[] inputRtfBytes = null;
            string outputFileName = 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);
                }

                outputFileName = Path.GetFileNameWithoutExtension(model.RtfFile.FileName) + ".md";
            }
            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);
                }

                outputFileName = Path.GetFileNameWithoutExtension(model.RtfFileUrl) + ".md";
            }

            // Convert the RTF document to Markdown
            string markdown = rtfToMarkdownConverter.ConvertToMarkdown(inputRtfBytes);

            // Encode the Markdown text as UTF-8 bytes
            byte[] outputMarkdownBytes = Encoding.UTF8.GetBytes(markdown);

            // Return the Markdown text as a downloadable file
            return File(outputMarkdownBytes, "text/markdown; charset=utf-8", outputFileName);
        }

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

            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_Markdown".Length);

            model.RtfFileUrl = rootUrl + "/DemoAppFiles/Input/RTF_Files/RTF_Document.rtf";

            return model;
        }
    }
}

See Also