Products Technologies Demo Docs Blog Support Company

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.

Convert Markdown to PDF in a Console Application on Linux and Windows

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.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Download ZIP

Open on GitHub

Open in Visual Studio

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.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETASP.NET CoreDOCX

DOCX Meets Markdown: Preparing Enterprise Documents for AI

Discover why Markdown is a game-changer for document creation in the age of AI. Explore how this lightweight markup language can enhance collaboration, version control, and integration with AI…


ASP.NETASP.NET CoreDOCX

Converting MS Word (*.docx) to Markdown (*.md) in .NET C#

Learn how to convert MS Word documents (*.docx) to Markdown files (*.md) in .NET C# using the TX Text Control .NET Server for ASP.NET. This tutorial provides a step-by-step guide to implement the…


ASP.NETASP.NET CoreMarkdown

Introducing TXTextControl.Markdown.Core: Import and Export Markdown in TX…

We are happy to announce the release of TXTextControl.Markdown.Core, a powerful new component that enables seamless import and export of Markdown files in TX Text Control. This addition enhances…


ASP.NETASP.NET CoreExtraction

Mining PDFs with Regex in C#: Practical Patterns, Tips, and Ideas

Mining PDFs with Regex in C# can be a powerful technique for extracting information from documents. This article explores practical patterns, tips, and ideas for effectively using regular…


ASP.NETASP.NET CoreForms

Streamline Data Collection with Embedded Forms in C# .NET

Discover how to enhance your C# .NET applications by embedding forms for data collection. This article explores the benefits of using Text Control's ASP.NET and ASP.NET Core components to create…