Convert Tagged PDF to Markdown

The Tagged PDF to Markdown Converter writes the content of tagged PDF documents as Markdown text. A tagged PDF document, like a PDF/UA document, marks its headings, paragraphs, lists, tables and links, and the converter uses these marks to write the Markdown structure exactly as the author of the document defined it.

A PDF document without tags is converted from the text of its pages. For documents that are not tagged the PDF to Markdown Converter component finds the structure from the layout of the pages.

The Tagged PDF to Markdown Converter is part of the Core component of the EvoPdf Next for .NET library.

Convert a Tagged PDF to Markdown

The EvoPdf.NextTaggedPdfToMarkdownConverter class converts a PDF document from a file, from a stream or from a memory buffer to a Markdown string.

Convert a Tagged PDF File to Markdown
// Create a tagged PDF to Markdown converter instance
TaggedPdfToMarkdownConverter taggedPdfToMarkdownConverter = new TaggedPdfToMarkdownConverter();

// Convert the PDF file to a Markdown string
string markdown = taggedPdfToMarkdownConverter.ConvertToMarkdown("document.pdf");
Convert a Tagged PDF from Memory to a Markdown File
TaggedPdfToMarkdownConverter taggedPdfToMarkdownConverter = new TaggedPdfToMarkdownConverter();

string markdown = taggedPdfToMarkdownConverter.ConvertToMarkdown(pdfBytes);

// Write the Markdown text to a file encoded as UTF-8
File.WriteAllText("document.md", markdown);

Pages to Convert

By default all the pages are converted. The conversion methods also accept the number of the first page to convert and the number of the last page to convert. When the end page number is 0 or is not given, the conversion goes on to the end of the document.

Convert a Range of Pages
// Convert the pages from 2 to 5
string markdown = taggedPdfToMarkdownConverter.ConvertToMarkdown("document.pdf", 2, 5);

// Convert from the page 3 to the end of the document
string markdownFromPage = taggedPdfToMarkdownConverter.ConvertToMarkdown("document.pdf", 3);

The TaggedPdfToMarkdownConverterMaxPageCount property limits the number of PDF pages converted. The default value is 0, which means there is no limit.

Limit the Number of Pages Converted
taggedPdfToMarkdownConverter.MaxPageCount = 10;

Open Password Protected PDFs

To convert a password protected PDF document set the TaggedPdfToMarkdownConverterUserPassword or the TaggedPdfToMarkdownConverterOwnerPassword property before the conversion.

Set the Passwords of a Protected PDF
taggedPdfToMarkdownConverter.UserPassword = "user-password";
taggedPdfToMarkdownConverter.OwnerPassword = "owner-password";

Images of the Figures

A figure of the document is written by default with its alternative text. The TaggedPdfToMarkdownConverterImageMode property, with a value of the EvoPdf.NextTaggedPdfToMarkdownImageMode enumeration, also writes the image of the figure, embedded in the Markdown text or saved as a file in a folder, in which case the Markdown text links to the file.

Embed the Images of the Figures in the Markdown Text
taggedPdfToMarkdownConverter.ImageMode = TaggedPdfToMarkdownImageMode.Embed;

When the images are saved as files, the TaggedPdfToMarkdownConverterImagesFolder property gives the folder and the TaggedPdfToMarkdownConverterImageFileName property gives the name of the files, which is followed by a number. The images are saved as PNG or JPEG files. The links use the name of the folder as path, or the path set by the TaggedPdfToMarkdownConverterImagesLinkPath property.

Save the Images of the Figures as Files
taggedPdfToMarkdownConverter.ImageMode = TaggedPdfToMarkdownImageMode.File;

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

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

Check if the Tags Were Used

After a conversion the TaggedPdfToMarkdownConverterDocumentStructureUsed property indicates if the Markdown was produced from the tags of the document.

Check if the Document Was Tagged
string markdown = taggedPdfToMarkdownConverter.ConvertToMarkdown(pdfBytes);

bool documentWasTagged = taggedPdfToMarkdownConverter.DocumentStructureUsed;

Asynchronous Methods

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

Asynchronously Convert a Tagged PDF to Markdown
string markdown = await taggedPdfToMarkdownConverter.ConvertToMarkdownAsync(pdfBytes, cancellationToken);

Code Sample - Convert Tagged PDF to Markdown

Convert Tagged PDF 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.PDF_to_Markdown;

// Use EVO PDF Namespace
using EvoPdf.Next;

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

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

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> ConvertTaggedPdfToMarkdown(Tagged_PDF_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 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 Tagged_PDF_to_Markdown_ViewModel SetViewModel()
        {
            var model = new Tagged_PDF_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 - "Tagged_PDF_to_Markdown".Length);

            model.PdfFileUrl = rootUrl + "/DemoAppFiles/Input/PDF_Files/Personal_Data_Document.pdf";

            return model;
        }
    }
}

See Also