Convert Markdown to PDF in a Console Application on Linux and Windows
Learn how to convert Markdown files to PDF in a console application on Linux and Windows using TX Text Control .NET Server for ASP.NET. This tutorial provides step-by-step instructions and code examples to help you get started quickly.

Do you need a quick and easy way to convert Markdown files to PDFs? This article describes a small console application that converts Markdown strings or files into PDFs. It's ideal for continuous integration (CI) pipelines, server jobs, and developer tooling.
The conversion is handled under the hood by TX Text Control and the new TXTextControl.Markdown.Core package. This package brings first-class Markdown import and export to TX Text Control.
Md2pdf is a small command-line program that converts Markdown files into finished PDFs. You can give it a file path or pipe text into the tool to feed it Markdown. Md2pdf parses the Markdown using TX Text Control and TXTextControl.Markdown.Core, builds a proper document, and renders a high-quality PDF.
By default, it prints a Base64 representation of the PDF to the standard output, allowing it to safely flow through pipes and other tools. If you provide an output path ending in .pdf (or set the output format to PDF), it writes a real binary PDF file instead. You can specify the input text encoding if necessary, and the tool reports errors via standard error and exits with a non-zero code, allowing it to fit cleanly into scripts and CI pipelines.
How the Conversion Works
At the heart of the tool is a simple method that passes your Markdown to TX Text Control and requests a PDF. The TXTextControl.Markdown.Core package integrates the LoadMarkdown extension, enabling you to input Markdown directly into a ServerTextControl instance, bypassing intermediate HTML or DOCX.
using System;
using System.IO;
using TXTextControl.Markdown;
namespace TXTextControl.Md2Pdf
{
public static class MarkdownToPdf
{
public static byte[] Convert(string markdown)
{
if (markdown is null) throw new ArgumentNullException(nameof(markdown));
using var tx = new TXTextControl.ServerTextControl();
tx.Create();
try
{
tx.LoadMarkdown(markdown);
tx.Save(out byte[] ms, TXTextControl.BinaryStreamType.AdobePDF);
return ms;
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to load Markdown into TX Text Control.", ex);
}
}
}
}
Calling it from Linux (bash)
To convert a Markdown file to PDF, you can call the tool like this:
# 1) From a file → PDF
md2pdf --file report.md --out report.pdf
# 2) From STDIN → PDF
cat report.md | md2pdf --out report.pdf
# 3) From STDIN → Base64, then decode in the shell
cat report.md | md2pdf | base64 -d > report.pdf
Calling it from Windows (PowerShell)
Using Windows PowerShell, you can convert a Markdown file to PDF like this:
# 1) From a file → PDF
.\md2pdf.exe --file .\report.md --out .\report.pdf
# 2) From STDIN → PDF
Get-Content -Raw -Encoding UTF8 .\report.md | .\md2pdf.exe --out .\report.pdf
# 3) Capture Base64 from STDOUT and write PDF
$b64 = .\md2pdf.exe --file .\report.md
[IO.File]::WriteAllBytes(".\report.pdf", [Convert]::FromBase64String($b64))
Calling it from .NET
You can launch the CLI and capture STDOUT (Base64), then write the bytes to a .pdf.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
public static class Md2PdfCaller
{
public static async Task<string> ConvertFileToBase64Async(string exePath, string mdPath)
{
var psi = new ProcessStartInfo
{
FileName = exePath,
Arguments = $"--file \"{mdPath}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8,
CreateNoWindow = true
};
using var proc = Process.Start(psi)!;
string stdout = await proc.StandardOutput.ReadToEndAsync();
string stderr = await proc.StandardError.ReadToEndAsync();
await proc.WaitForExitAsync();
if (proc.ExitCode != 0)
throw new InvalidOperationException($"md2pdf failed: {stderr}");
return stdout.Trim();
}
public static async Task WritePdfAsync(string exePath, string mdPath, string pdfPath)
{
// Let the CLI write a real PDF directly
var psi = new ProcessStartInfo
{
FileName = exePath,
Arguments = $"--file \"{mdPath}\" --out \"{pdfPath}\"",
UseShellExecute = false,
RedirectStandardError = true,
CreateNoWindow = true
};
using var proc = Process.Start(psi)!;
string stderr = await proc.StandardError.ReadToEndAsync();
await proc.WaitForExitAsync();
if (proc.ExitCode != 0)
throw new InvalidOperationException($"md2pdf failed: {stderr}");
}
}
Calling it from Python
Using Python, you can a subprocess to call the CLI tool:
import subprocess, base64, sys
exe = r"./md2pdf.exe" # or "md2pdf" on Linux if on PATH
md_path = "report.md"
pdf_path = "report.pdf"
# Option A: let the tool write a PDF directly
subprocess.run([exe, "--file", md_path, "--out", pdf_path], check=True)
# Option B: capture Base64 and decode in Python
result = subprocess.run([exe, "--file", md_path], capture_output=True, text=True, check=True)
b64 = result.stdout.strip()
with open(pdf_path, "wb") as f:
f.write(base64.b64decode(b64))
Calling from PHP
Using PHP, you can call the CLI tool using shell_exec:
<?php
$exe = PHP_OS_FAMILY === 'Windows' ? '.\\md2pdf.exe' : './md2pdf';
$md = 'report.md';
$pdf = 'report.pdf';
// Option A: write PDF directly
$cmd = escapeshellcmd($exe) . ' --file ' . escapeshellarg($md) . ' --out ' . escapeshellarg($pdf);
exec($cmd, $output, $code);
if ($code !== 0) {
throw new RuntimeException("md2pdf failed with code $code");
}
// Option B: capture Base64 and decode in PHP
$cmd = escapeshellcmd($exe) . ' --file ' . escapeshellarg($md);
$b64 = shell_exec($cmd);
if ($b64 === null) {
throw new RuntimeException("md2pdf failed");
}
file_put_contents($pdf, base64_decode(trim($b64)));
When to use Base64 vs Direct PDF Output
Use Base64 encoding when the PDF will travel through environments that expect text. This includes piping results between commands, passing data across operating systems, embedding the output in JSON, posting it to an HTTP API, dropping it onto a message queue, or returning it from a serverless job. In these scenarios, a binary stream can be corrupted by encodings, shells, or middleware. Base64 keeps the payload ASCII-safe and predictable so that any language can decode it back into bytes on the receiving end.
Choose direct PDF output when you simply want a file on disk. If your goal is "convert this Markdown and save the PDF here", letting the tool write the binary .pdf to the path you specify is faster and avoids the Base64 round-trip entirely.
Conclusion
Md2pdf is a simple yet powerful tool that uses TX Text Control to convert Markdown to PDF. Whether you're automating documentation generation, integrating it into CI/CD pipelines, or simply need a quick file conversion solution, Md2pdf makes it easy. With support for Base64 and direct PDF output, Md2pdf fits seamlessly into various workflows and environments.
![]()
Download and Fork This Sample on GitHub
We proudly host our sample code on github.com/TextControl.
Please fork and contribute.
Requirements for this sample
- TX Text Control .NET Server for ASP.NET 33.0
ASP.NET
Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.
- Angular
- Blazor
- React
- JavaScript
- ASP.NET MVC, ASP.NET Core, and WebForms
Related Posts
ASP.NETASP.NET CoreDigital Signatures
Why Digitally Signing your PDFs is the Only Reliable Way to Prevent Tampering
PDF documents are widely used for sharing information because of their fixed layout and cross-platform compatibility. However, it is crucial to ensure the integrity and authenticity of these…
Bringing MailMerge Power to Markdown: Fluid Placeholders in TX Text Control…
The latest beta version of the TX Text Control Markdown NuGet package introduces support for fluid placeholders, also known as Mustache or Handlebars syntax. This powerful feature enables…
Automating PDF/UA Accessibility with AI: Describing DOCX Documents Using TX…
This article shows how to use TX Text Control together with the OpenAI API to automatically add descriptive texts (alt text and labels) to images, links, and tables in a DOCX. The resulting…
Converting Office Open XML (DOCX) to PDF in Java
Learn how to convert Office Open XML (DOCX) documents to PDF in Java using the powerful ServerTextControl library. This guide provides step-by-step instructions and code examples to help you…
Extending DS Server with Custom Digital Signature APIs
In this article, we will explore how to extend the functionality of DS Server by integrating custom digital signature APIs. We will cover the necessary steps to create a plugin that allows DS…
