HiQPdf Next PDF to Markdown Converter for .NET

HiQPdf Next PDF to Markdown Converter for .NET

The PDF to Markdown Converter is a component of the HiQPdf Next Library for .NET that converts PDF documents to Markdown text, keeping the headings, lists, tables, links and images of the document.

You can deploy the library on Windows, Linux and macOS platforms, including Azure App Service and Functions or Docker containers.

Download Now
Online Demo
Documentation

The PDF to Markdown Converter is a component of the HiQPdf Next Library for .NET that converts PDF documents to Markdown text. It finds the headings, lists, tables and links from the layout of the pages and works with any PDF document, tagged or not. You can see the list of all HiQPdf Next components on the library page.
The PDF to Markdown Converter is distributed as part of the HiQPdf Next PDF Processor for .NET, which also includes functionality for converting PDF to text, converting PDF pages to images and extracting images from PDF documents.

Compatibility Platforms

HiQPdf Next for .NET can run on a variety of Windows, Linux and macOS platforms in web, console and desktop applications across all modern .NET platforms. The library components can be used in Azure App Service and Azure Functions environments on both Windows and Linux. Deployment to Docker Windows and Linux containers is also supported.
The .NET library targets .NET Standard 2.0, which makes it compatible with a wide range of .NET Core and .NET Framework applications.

Getting Started

The online documentation contains Getting Started guides for Windows, Linux, macOS, Azure App Service and Azure Functions, with detailed instructions for integrating the library into your application and complete C# examples for each important feature of the library.
You can see the current capabilities of the library by checking the online demo application for this library and the API reference in the online documentation.

Download Demo Application

You can also download a free trial package for .NET, which includes an ASP.NET demo application project with complete C# source code as a starting point for experimenting with your own usage scenarios.
Running the samples in the demo application that involve HTML to PDF conversion features on Linux platforms might require installing some system dependency packages. The documentation includes an entire section dedicated to building, publishing and running the demo application on multiple platforms.

NuGet Packages

For Windows x64 deployments add a reference to the HiQPdf.Next.PdfProcessor.Windows NuGet Package and for Linux x64 deployments add a reference to the HiQPdf.Next.PdfProcessor.Linux NuGet Package. The packages without an architecture suffix target x64.
For Windows ARM64 and Linux ARM64 deployments add a reference to the HiQPdf.Next.PdfProcessor.Windows.Arm64 and HiQPdf.Next.PdfProcessor.Linux.Arm64 NuGet Packages respectively.
For macOS on Apple Silicon (ARM64) deployments add a reference to the HiQPdf.Next.PdfProcessor.MacOS NuGet Package.
The package for Windows is referenced by the HiQPdf.Next.Windows metapackage for all components, the package for Windows ARM64 is referenced by the HiQPdf.Next.Windows.Arm64 metapackage for all components, the package for Linux is referenced by the HiQPdf.Next.Linux metapackage for all components, the package for Linux ARM64 is referenced by the HiQPdf.Next.Linux.Arm64 metapackage for all components and the package for macOS is referenced by the HiQPdf.Next.MacOS metapackage for all components.
There are also multiplatform metapackages that reference both the Windows x64 and Linux x64 PDF Processor packages: HiQPdf.Next.PdfProcessor for the PDF Processor functionality and HiQPdf.Next for the entire HiQPdf Next library.

Installation

The PDF Processor component ships its runtime inside the NuGet package and needs no system packages on Windows, Linux or macOS. On Linux the runtime file must have execute permission, as the Getting Started on Linux guide shows.

HiQPdf.Next Namespace

All components of the HiQPdf Next for .NET library share the same HiQPdf.Next namespace and can be used together in the same application. To use the library in your own code, add the using directive at the top of your C# source file, as shown below.
// Include the HiQPdf.Next namespace at the top of your C# file
using HiQPdf.Next;

Sample Code

After you add the reference to the NuGet package to your project, use the sample code below to convert a PDF document to Markdown with the images embedded in the text.
// Create the PDF to Markdown converter instance with default options
PdfToMarkdownConverter pdfToMarkdownConverter = new PdfToMarkdownConverter();

// Embed the images of the document in the Markdown text
pdfToMarkdownConverter.ImageMode = PdfToMarkdownImageMode.Embed;

// Convert the specified PDF file to Markdown
string markdown = pdfToMarkdownConverter.ConvertToMarkdown(pdfFilePath);

Features List

HiQPdf Next PDF to Markdown Converter for .NET offers options for the content written in Markdown. You can detect tables, keep the links, include the images and leave out the page headers and footers that repeat. You can specify the user and owner passwords to open password-protected PDF documents, as well as the PDF page range to convert.

Convert PDF Documents From Memory, Stream or File

You can convert PDF documents from a memory buffer, a stream or a file. The conversion produces a .NET string that contains the Markdown text.

Headings, Lists and Code Blocks

The headings are written with their levels, the bulleted and numbered lists as Markdown lists and the text in a fixed-width font as code blocks. When the document has bookmarks, the heading levels follow them.

Tables Written as Markdown Tables

The tables are found from their ruling lines and from the alignment of the text. A table that continues on the next pages is written as a single table.

Links of the PDF Document

The links of the PDF document are written as Markdown links. You can turn this option off to get only the text of the links.

Images Embedded or Saved as Files

The images of the document can be embedded in the Markdown text or saved as PNG files in a folder and linked from the Markdown text. By default the images are not included.

Repeated Page Headers and Footers

The text and the images that repeat at the top or at the bottom of the pages, such as page headers and footers, can be left out of the Markdown text.

Convert Password-Protected PDF Documents

If the PDF document is password-protected, you specify the user or owner password used to open the document before the conversion.

Convert the Entire Document or a Range of PDF Pages

The convert methods allow you to specify the range of PDF pages to convert, by the start page number and optionally the end page number.

Convert Tagged PDF Documents Using Their Structure

For tagged PDF documents, such as PDF/UA documents, the TaggedPdfToMarkdownConverter class writes the Markdown text from the structure marked by the tags of the document. The class is included in the HiQPdf Next Core PDF API for .NET component.

Asynchronous Convert Methods

There are asynchronous variants of the convert methods with the Async suffix that can be used with async and await.

Available on Windows, Linux and macOS Platforms

HiQPdf Next for .NET can run on Windows (x64 and ARM64), Linux (x64 and ARM64) and macOS (Apple Silicon / ARM64). There are different NuGet packages for Windows, Linux and macOS, including the same .NET library but with different native runtimes. For Windows, the minimum required version is Windows 10 or Windows Server 2016.

Built for .NET Standard 2.0 for Maximum Compatibility

The .NET library targets .NET Standard 2.0, making it compatible with a wide range of .NET Core and .NET Framework applications. It is compatible with .NET 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, .NET Standard 2.0 and .NET Framework 4.6.2 to 4.8.1.

Fully Compatible with Azure App Service and Azure Functions on Both Windows and Linux

The converter can run without restrictions in your Azure App Service and Azure Functions .NET Core applications targeting both Windows and Linux platforms. Web fonts and other features are fully supported by HiQPdf Next for .NET. Online documentation offers detailed usage instructions for Azure applications targeting both Windows and Linux.

NuGet Packages for Windows, Linux and macOS

HiQPdf Next for .NET is delivered as NuGet packages for Windows, Linux and macOS. The packages include the .NET Standard 2.0 library, the same for both platforms, and the specific native runtime for each platform.
ASP.NET Core Demo Application with C# Code for All Features
The zip package that can be downloaded from the website contains the project for the ASP.NET Core demo application with C# sample code for all major library features.

Simple and Flexible Licensing with a Single License for All Libraries

The license for HiQPdf Next for .NET works with both the classic HiQPdf Library for .NET and the multi-platform client-server solution. There are no additional runtime or deployment costs charged for using our software component in your applications.

HiQPdf Next for .NET - PDF to Markdown C# Code Sample for 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 HiQPdf_Next_AspNetDemo.Models;

using HiQPdf.Next;

namespace HiQPdf_Next_AspNetDemo.Controllers
{
    public class PdfToMarkdownController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;
        public PdfToMarkdownController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

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

            return View(model);
        }

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

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

            // Create the PDF to Markdown converter instance with default options
            PdfToMarkdownConverter pdfToMarkdownConverter = new PdfToMarkdownConverter();

            // Optionally set the user password to open a password-protected PDF
            if (!string.IsNullOrEmpty(model.UserPassword))
                pdfToMarkdownConverter.UserPassword = model.UserPassword;

            // Optionally set the owner password to open a password-protected PDF
            if (!string.IsNullOrEmpty(model.OwnerPassword))
                pdfToMarkdownConverter.OwnerPassword = model.OwnerPassword;

            // Write the text arranged in rows and columns as Markdown tables
            pdfToMarkdownConverter.DetectTables = model.DetectTables;

            // Write the links of the PDF document as Markdown links
            pdfToMarkdownConverter.IncludeLinks = model.IncludeLinks;

            // Leave out the text repeated at the top and at the bottom of the pages
            pdfToMarkdownConverter.RemoveHeadersAndFooters = model.RemoveHeadersAndFooters;

            // Leave the images out or embed them in the Markdown text
            pdfToMarkdownConverter.ImageMode = model.ImageMode == "Embed" ? PdfToMarkdownImageMode.Embed : PdfToMarkdownImageMode.None;

            // PDF page number to start the conversion from
            int startPageNumber = model.StartPageNumber;

            // PDF page number to end the conversion at
            // If 0, the conversion continues to the end of the document
            int endPageNumber = 0;
            if (model.EndPageNumber.HasValue)
                endPageNumber = model.EndPageNumber.Value;

            byte[] inputPdfBytes = null;
            string outputFileName = null;

            // If an uploaded file exists, use it with priority
            if (model.PdfFile != null && model.PdfFile.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream();
                    await model.PdfFile.CopyToAsync(ms);
                    inputPdfBytes = ms.ToArray();
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to read the uploaded PDF file", ex);
                }

                outputFileName = Path.GetFileNameWithoutExtension(model.PdfFile.FileName) + ".md";
            }
            else
            {
                // Otherwise, fall back to the URL
                string pdfUrl = model.PdfFileUrl?.Trim();
                if (string.IsNullOrWhiteSpace(pdfUrl))
                    throw new Exception("No PDF file provided: upload a file or specify a URL");

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

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

            // Convert the specified PDF page range to Markdown
            string markdown = pdfToMarkdownConverter.ConvertToMarkdown(inputPdfBytes, startPageNumber, endPageNumber);

            // 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 PdfToMarkdownViewModel SetViewModel()
        {
            var model = new PdfToMarkdownViewModel();

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

            model.PdfFileUrl = rootUrl + "/DemoFiles/Pdf/Personal_Data_Document.pdf";

            return model;
        }
    }
}

HiQPdf Next for .NET - Tagged PDF to Markdown C# Code Sample for 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 HiQPdf_Next_AspNetDemo.Models;

using HiQPdf.Next;

namespace HiQPdf_Next_AspNetDemo.Controllers
{
    public class TaggedPdfToMarkdownController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;
        public TaggedPdfToMarkdownController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

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

            return View(model);
        }

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

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

            // Create the tagged PDF to Markdown converter instance with default options
            TaggedPdfToMarkdownConverter taggedPdfToMarkdownConverter = new TaggedPdfToMarkdownConverter();

            // Optionally set the user password to open a password-protected PDF
            if (!string.IsNullOrEmpty(model.UserPassword))
                taggedPdfToMarkdownConverter.UserPassword = model.UserPassword;

            // Optionally set the owner password to open a password-protected PDF
            if (!string.IsNullOrEmpty(model.OwnerPassword))
                taggedPdfToMarkdownConverter.OwnerPassword = model.OwnerPassword;

            // Leave the images of the figures out or embed them in the Markdown text
            taggedPdfToMarkdownConverter.ImageMode = model.ImageMode == "Embed" ? TaggedPdfToMarkdownImageMode.Embed : TaggedPdfToMarkdownImageMode.None;

            // PDF page number to start the conversion from
            int startPageNumber = model.StartPageNumber;

            // PDF page number to end the conversion at
            // If 0, the conversion continues to the end of the document
            int endPageNumber = 0;
            if (model.EndPageNumber.HasValue)
                endPageNumber = model.EndPageNumber.Value;

            byte[] inputPdfBytes = null;
            string outputFileName = null;

            // If an uploaded file exists, use it with priority
            if (model.PdfFile != null && model.PdfFile.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream();
                    await model.PdfFile.CopyToAsync(ms);
                    inputPdfBytes = ms.ToArray();
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to read the uploaded PDF file", ex);
                }

                outputFileName = Path.GetFileNameWithoutExtension(model.PdfFile.FileName) + ".md";
            }
            else
            {
                // Otherwise, fall back to the URL
                string pdfUrl = model.PdfFileUrl?.Trim();
                if (string.IsNullOrWhiteSpace(pdfUrl))
                    throw new Exception("No PDF file provided: upload a file or specify a URL");

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

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

            // Convert the PDF document to Markdown using the tags of the document
            string markdown = taggedPdfToMarkdownConverter.ConvertToMarkdown(inputPdfBytes, startPageNumber, endPageNumber);

            // 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 TaggedPdfToMarkdownViewModel SetViewModel()
        {
            var model = new TaggedPdfToMarkdownViewModel();

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

            model.PdfFileUrl = rootUrl + "/DemoFiles/Pdf/Personal_Data_Document.pdf";

            return model;
        }
    }
}