The PDF to Markdown Converter component writes the content of PDF documents as Markdown text. The headings, lists, tables, code and links are found from the text of the pages and from the lines drawn on them, so the PDF document does not have to be tagged.
This component is distributed as part of the EvoPdf.Next.PdfProcessor.Windows NuGet package when targeting Windows x64 and as part of the EvoPdf.Next.PdfProcessor.Linux package when targeting Linux x64. The Windows x64 package is referenced by the EvoPdf.Next.Windows metapackage and the Linux x64 package is referenced by the EvoPdf.Next.Linux metapackage.
For macOS on Apple Silicon (ARM64), this component is distributed as part of the EvoPdf.Next.PdfProcessor.MacOS NuGet package.
For Windows ARM64 and Linux ARM64, this component is distributed as part of the EvoPdf.Next.PdfProcessor.Windows.Arm64 and EvoPdf.Next.PdfProcessor.Linux.Arm64 NuGet packages respectively.
You can choose if the tables, the links and the images of the document are written, leave out the page headers and footers and set the range of pages to convert. Password protected PDF documents are also supported.
The EvoPdf.NextPdfToMarkdownConverter class converts PDF documents to Markdown. You can create an instance using the default constructor and then set its options through properties.
// Create a new PDF to Markdown converter instance
PdfToMarkdownConverter pdfToMarkdownConverter = new PdfToMarkdownConverter();Note that PdfToMarkdownConverter instances are not reusable. You must create a new instance for each conversion.
The text arranged in rows and columns is written as Markdown tables when the PdfToMarkdownConverterDetectTables property is true. The links of the document are written as Markdown links when the PdfToMarkdownConverterIncludeLinks property is true. The text that repeats at the top and at the bottom of the pages, like the page headers, the page footers and the page numbers, is left out when the PdfToMarkdownConverterRemoveHeadersAndFooters property is true. All these properties are true by default.
// Write the tables as plain text
pdfToMarkdownConverter.DetectTables = false;
// Write the text of the links without their addresses
pdfToMarkdownConverter.IncludeLinks = false;
// Keep the page headers and footers in the Markdown text
pdfToMarkdownConverter.RemoveHeadersAndFooters = false;The images of the PDF document are left out by default. The PdfToMarkdownConverterImageMode property, with a value of the EvoPdf.NextPdfToMarkdownImageMode enumeration, lets you embed the images in the Markdown text or save them as PNG files in a folder, in which case the Markdown text links to the files. The images are placed in the text where they are on the pages.
pdfToMarkdownConverter.ImageMode = PdfToMarkdownImageMode.Embed;When the images are saved as files, the PdfToMarkdownConverterImagesFolder property gives the folder and the PdfToMarkdownConverterImageFileName property gives the name of the files, which is followed by a number. The links use the name of the folder as path, or the path set by the PdfToMarkdownConverterImagesLinkPath property.
pdfToMarkdownConverter.ImageMode = PdfToMarkdownImageMode.File;
// The folder where the PNG files are saved
pdfToMarkdownConverter.ImagesFolder = "output/report_images";
// Optionally set the path used by the links of the Markdown text and the name of the files
pdfToMarkdownConverter.ImagesLinkPath = "report_images";
pdfToMarkdownConverter.ImageFileName = "figure";To convert a password protected PDF document set the PdfToMarkdownConverterUserPassword or the PdfToMarkdownConverterOwnerPassword property before the conversion.
pdfToMarkdownConverter.UserPassword = "user-password";
pdfToMarkdownConverter.OwnerPassword = "owner-password";The PdfToMarkdownConverterMaxPageCount property limits the number of PDF pages converted. The default value is 0, which means there is no limit.
pdfToMarkdownConverter.MaxPageCount = 10;The ConvertToMarkdown methods accept a PDF document from a memory buffer, from a stream or from a file and return the Markdown text. You can convert all the pages, the pages starting from a given page number or a range of pages. The page numbers start from 1.
string markdown = pdfToMarkdownConverter.ConvertToMarkdown(pdfBytes);// Convert the pages 2 to 5
string markdown = pdfToMarkdownConverter.ConvertToMarkdown("document.pdf", 2, 5);All the conversion methods have asynchronous versions that accept a cancellation token.
PdfToMarkdownConverter pdfToMarkdownConverter = new PdfToMarkdownConverter();
string markdown = await pdfToMarkdownConverter.ConvertToMarkdownAsync(pdfBytes, cancellationToken);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 PDF_to_MarkdownController : Controller
{
private readonly IWebHostEnvironment m_hostingEnvironment;
public PDF_to_MarkdownController(IWebHostEnvironment hostingEnvironment)
{
m_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
var model = SetViewModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> ConvertPdfToMarkdown(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 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 PDF_to_Markdown_ViewModel SetViewModel()
{
var model = new 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 - "PDF_to_Markdown".Length);
model.PdfFileUrl = rootUrl + "/DemoAppFiles/Input/PDF_Files/Personal_Data_Document.pdf";
return model;
}
}
}