MarkdownToPdf.NET 1.4.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package MarkdownToPdf.NET --version 1.4.0
                    
NuGet\Install-Package MarkdownToPdf.NET -Version 1.4.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MarkdownToPdf.NET" Version="1.4.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MarkdownToPdf.NET" Version="1.4.0" />
                    
Directory.Packages.props
<PackageReference Include="MarkdownToPdf.NET" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MarkdownToPdf.NET --version 1.4.0
                    
#r "nuget: MarkdownToPdf.NET, 1.4.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MarkdownToPdf.NET@1.4.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MarkdownToPdf.NET&version=1.4.0
                    
Install as a Cake Addin
#tool nuget:?package=MarkdownToPdf.NET&version=1.4.0
                    
Install as a Cake Tool

MarkdownToPdf.NET

A comprehensive .NET library for generating PDF files from Markdown and plain text with customizable styling and metadata support.

Features

  • ✅ Convert Markdown to PDF with full formatting support
  • ✅ Convert plain text to PDF with proper paragraph formatting
  • ✅ Direct HTML to PDF conversion
  • Portable and self-contained - no external dependencies required
  • Cross-platform support - Windows, Linux, macOS
  • ✅ Customizable PDF metadata (title, author, subject)
  • ✅ Configurable page settings (size, orientation, margins)
  • ✅ Modern, readable default styling
  • ✅ Custom CSS override support
  • ✅ Dependency injection support for ASP.NET applications
  • ✅ Comprehensive error handling
  • ✅ Logging integration
  • ✅ Both file output and byte array output options

Supported Markdown Features

  • Headers (H1-H6) with styled borders
  • Bold and italic text formatting
  • Unordered and ordered lists
  • Links
  • Inline code and code blocks
  • Blockquotes with styling

  • Tables with borders
  • Horizontal rules
  • Emoji support 😊
  • Task lists
  • And more via Markdig extensions

Installation

Install the package via NuGet Package Manager:

dotnet add package MarkdownToPdf.NET

Or via Package Manager Console:

Install-Package MarkdownToPdf.NET

✅ No additional setup required! The package includes all necessary native dependencies for Windows, Linux, and macOS.

Note: While the package name is MarkdownToPdf.NET, the namespace remains PdfTools.* for consistency and ease of use.

Dependencies

The library automatically handles the following dependencies:

<PackageReference Include="MarkdownToPdf.NET" Version="1.3.2" />
<PackageReference Include="Markdig" Version="0.37.0" />
<PackageReference Include="DinkToPdf" Version="1.0.8" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />

Portable Native Libraries

This package includes version-compatible native libraries for cross-platform support:

  • Windows: libwkhtmltox.dll (v0.12.4 - compatible with DinkToPdf 1.0.8)
  • Linux: libwkhtmltox.so (v0.12.4 - compatible with DinkToPdf 1.0.8)
  • macOS: libwkhtmltox.dylib (when available)

✅ Version Compatibility Guaranteed: The library includes automatic version verification to ensure compatibility between wkhtmltopdf and DinkToPdf, preventing runtime crashes.

No separate installation of wkhtmltopdf is required!

Quick Start

Basic Usage

using PdfTools.Services;
using PdfTools.Models;

// Create generator instance
var generator = new PdfGenerator();

// Generate PDF from markdown
string markdown = @"
# My Document

This is a **sample** document with *formatting*.

## Features
- Beautiful styling
- Easy to use
- Professional output
";

generator.GenerateFromMarkdown(markdown, "output.pdf");

// Generate PDF from plain text
string text = "This is plain text that will be converted to a nicely formatted PDF.";
generator.GenerateFromText(text, "text-output.pdf");

With Custom Options

var options = new PdfOptions
{
    Title = "My Custom Document",
    Author = "John Doe",
    Subject = "Sample PDF Generation",
    PageSize = "A4",
    Orientation = "Portrait",
    Margins = new PdfMargins
    {
        Top = 25,
        Bottom = 25,
        Left = 20,
        Right = 20
    },
    CustomCss = @"
        body { font-family: 'Times New Roman'; }
        h1 { color: #ff6b6b; }
    "
};

generator.GenerateFromMarkdown(markdown, "custom-output.pdf", options);

With Enhanced Styling

// Method 1: Using enhanced CSS with modern typography and better visual design
generator.GenerateFromMarkdownWithEnhancedStyling(markdown, "enhanced-output.pdf", "My Enhanced Document");

// Method 2: Create enhanced options using factory wrapper
var enhancedOptions = PdfOptionsFactory.CreateDefaultWithEnhancements("Professional Report");
generator.GenerateFromMarkdown(markdown, "professional-output.pdf", enhancedOptions);

// Method 3: Create enhanced options directly from provider
var directOptions = EnhancedCssProvider.CreateDefaultOptionsWithEnhancements();
directOptions.Title = "My Custom Title";
generator.GenerateFromMarkdown(markdown, "direct-output.pdf", directOptions);

// Method 4: Create enhanced options with custom CSS
var customOptions = PdfOptionsFactory.CreateEnhanced("Custom Report", @"
    .custom-highlight { 
        background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
        padding: 1rem;
        border-radius: 8px;
    }
");
generator.GenerateFromMarkdown(markdown, "custom-output.pdf", customOptions);

Professional Document Styling

// Create options optimized for professional documents
var professionalOptions = PdfOptionsFactory.CreateProfessional(
    title: "Annual Report 2024",
    author: "Company Name",
    subject: "Financial Analysis"
);

generator.GenerateFromMarkdown(markdown, "annual-report.pdf", professionalOptions);

// For technical documentation
var technicalOptions = PdfOptionsFactory.CreateTechnical("API Documentation");
generator.GenerateFromMarkdown(markdown, "api-docs.pdf", technicalOptions);

Generate to Byte Array

// Get PDF as byte array (useful for web applications)
byte[] pdfBytes = generator.GenerateFromMarkdownToBytes(markdown, options);

// In ASP.NET Controller
return File(pdfBytes, "application/pdf", "document.pdf");

ASP.NET Integration

Startup Configuration

using PdfTools.Extensions;

// In Program.cs or Startup.cs
builder.Services.AddPdfTools();

// Or with custom converter
builder.Services.AddPdfTools(provider => 
{
    // Custom converter configuration
    return new SynchronizedConverter(new PdfTools());
});

Controller Usage

[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
    private readonly IPdfGenerator _pdfGenerator;
    
    public PdfController(IPdfGenerator pdfGenerator)
    {
        _pdfGenerator = pdfGenerator;
    }
    
    [HttpPost("from-markdown")]
    public IActionResult GenerateFromMarkdown([FromBody] MarkdownRequest request)
    {
        try
        {
            var options = new PdfOptions
            {
                Title = request.Title,
                Author = request.Author
            };
            
            var pdfBytes = _pdfGenerator.GenerateFromMarkdownToBytes(
                request.Markdown, options);
            
            return File(pdfBytes, "application/pdf", "document.pdf");
        }
        catch (Exception ex)
        {
            return BadRequest($"PDF generation failed: {ex.Message}");
        }
    }
}

API Reference

IPdfGenerator Interface

// Generate PDF from markdown to file
void GenerateFromMarkdown(string markdown, string outputPath, PdfOptions? options = null);

// Generate PDF from text to file
void GenerateFromText(string text, string outputPath, PdfOptions? options = null);

// Generate PDF from HTML to file
void GenerateFromHtml(string html, string outputPath, PdfOptions? options = null);

// Generate PDF from markdown to byte array
byte[] GenerateFromMarkdownToBytes(string markdown, PdfOptions? options = null);

// Generate PDF from text to byte array
byte[] GenerateFromTextToBytes(string text, PdfOptions? options = null);

PdfOptions Configuration

public class PdfOptions
{
    public string? Title { get; set; }           // PDF metadata title
    public string? Author { get; set; }          // PDF metadata author
    public string? Subject { get; set; }         // PDF metadata subject
    public string Orientation { get; set; }     // "Portrait" or "Landscape"
    public string PageSize { get; set; }        // "A4", "Letter", "Legal", etc.
    public string? CustomCss { get; set; }      // Custom CSS overrides
    public PdfMargins Margins { get; set; }     // Page margins
}

public class PdfMargins
{
    public int Top { get; set; }                // Top margin in mm
    public int Bottom { get; set; }             // Bottom margin in mm
    public int Left { get; set; }               // Left margin in mm
    public int Right { get; set; }              // Right margin in mm
}

Error Handling

The library provides specific exception types for different error scenarios:

try
{
    generator.GenerateFromMarkdown(markdown, outputPath);
}
catch (InvalidInputException ex)
{
    // Handle invalid input (null/empty content, invalid paths)
    Console.WriteLine($"Invalid input: {ex.Message}");
}
catch (PdfGenerationException ex)
{
    // Handle PDF generation errors
    Console.WriteLine($"PDF generation failed: {ex.Message}");
}
catch (FileOperationException ex)
{
    // Handle file I/O errors
    Console.WriteLine($"File operation failed: {ex.Message}");
}

Styling

The library includes beautiful default CSS styling that provides:

  • Modern, readable fonts (Segoe UI family)
  • Proper heading hierarchy with colored borders
  • Styled lists and blockquotes
  • Syntax-highlighted code blocks
  • Professional table formatting
  • Print-optimized layout

Enhanced CSS Features

The library now includes enhanced CSS options with advanced typography and modern design:

// Use enhanced CSS for better visual appearance
var enhancedOptions = PdfOptionsFactory.CreateEnhanced("Document Title");

// Enhanced CSS includes:
// - CSS Variables for consistent theming
// - Google Fonts integration (Inter, JetBrains Mono)
// - Advanced typography with font features
// - Professional gradients and shadows
// - Responsive image containers
// - Smart page break controls
// - Enhanced status indicators and alerts

CSS Styling Options

Default CSS: Clean, professional styling

var options = PdfOptionsFactory.CreateDefault("Document Title");

Enhanced CSS: Modern typography with advanced features

// Method 1: Factory wrapper (recommended)
var options = PdfOptionsFactory.CreateDefaultWithEnhancements("Enhanced Document");

// Method 2: Direct provider access
var options = EnhancedCssProvider.CreateDefaultOptionsWithEnhancements();

// Method 3: Convenience method
generator.GenerateFromMarkdownWithEnhancedStyling(markdown, "output.pdf", "Title");

// Method 4: Enhanced with custom CSS
var options = PdfOptionsFactory.CreateEnhanced("Document", "custom css here");

Professional CSS: Optimized for business documents

var options = PdfOptionsFactory.CreateProfessional("Annual Report", "Author", "Subject");

Technical CSS: Specialized for technical documentation

var options = PdfOptionsFactory.CreateTechnical("API Documentation");

Custom CSS Classes

The enhanced CSS includes utility classes for better content styling:


<div class="alert alert-info">Information message</div>
<div class="alert alert-warning">Warning message</div>
<div class="alert alert-success">Success message</div>
<div class="alert alert-danger">Error message</div>


<div class="highlight">Important highlighted content</div>


<div class="card">Card content with shadow and border</div>


<div class="grid">
  <div class="metric-card">Metric 1</div>
  <div class="metric-card">Metric 2</div>
</div>


<div class="page-break-before">Content starts on new page</div>
<div class="no-break">Keep this content together</div>

You can override any styles using the CustomCss property in PdfOptions.

Building and Deployment Guide

This section provides step-by-step instructions for building, testing, and deploying the MarkdownToPdf.NET package.

Prerequisites

  • .NET 6.0 SDK or later
  • Git for version control
  • NuGet CLI (optional, for advanced scenarios)
  • NuGet.org API key (for deployment)

Building the Package

1. Clone and Navigate
git clone https://github.com/eochieng_microsoft/PdfTools.git
cd PdfTools
2. Clean Previous Builds
dotnet clean PdfTools.sln
3. Restore Dependencies
dotnet restore PdfTools/PdfTools.csproj
4. Build the Library
# Debug build
dotnet build PdfTools/PdfTools.csproj

# Release build (recommended for packaging)
dotnet build PdfTools/PdfTools.csproj --configuration Release

Creating the NuGet Package

1. Generate Package
# Creates package in bin/Release directory
dotnet pack PdfTools/PdfTools.csproj --configuration Release
2. Verify Package Contents
# List generated packages
ls PdfTools/bin/Release/*.nupkg

# Expected output: MarkdownToPdf.NET.{version}.nupkg

Deployment to NuGet.org

1. Obtain API Key
  • Reach out to eochieng to get the API Key
2. Deploy Package
# Replace YOUR_API_KEY with your actual API key
dotnet nuget push "PdfTools/bin/Release/MarkdownToPdf.NET.{version}.nupkg" \
  --api-key YOUR_API_KEY \
  --source https://api.nuget.org/v3/index.json
3. Verify Deployment

Version Management Workflow

For Bug Fixes (Patch Version)
# Example: 1.2.1 → 1.2.2
# Update version in PdfTools.csproj
# Test, build, and deploy
For New Features (Minor Version)
# Example: 1.2.1 → 1.3.0
# Update version in PdfTools.csproj
# Update README with new features
# Test extensively, build, and deploy
For Breaking Changes (Major Version)
# Example: 1.2.1 → 2.0.0
# Update version in PdfTools.csproj
# Update documentation
# Consider migration guide
# Test thoroughly, build, and deploy

Changelog

Version 1.3.2 (Latest)

  • 🐛 CRITICAL FIX: Resolved version compatibility issue between wkhtmltopdf and DinkToPdf
  • Stability: Fixed crashes when running without debugger attached
  • 🔧 Enhancement: Added automatic version verification for native libraries
  • 📦 Dependencies: Updated to use wkhtmltopdf 0.12.4 (compatible with DinkToPdf 1.0.8)
  • 🛡️ Reliability: Added proactive compatibility checking to prevent runtime failures

Version 1.3.1

  • 📦 Updated Markdig to version 0.37.0
  • 🔧 Minor improvements and bug fixes

Version 1.3.0

  • ✨ Enhanced CSS styling support
  • 🎨 New default styling options
  • 📐 Improved page layout and typography

License

This library uses the following open-source packages:

Make sure to comply with their respective licenses in your applications.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.1.0 103 8/17/2025
2.0.1 130 8/14/2025
2.0.0 125 8/13/2025
1.4.0 180 8/8/2025
1.3.2 211 8/6/2025
1.3.1 92 8/1/2025
1.3.0 114 7/31/2025
1.2.1 119 7/30/2025
1.2.0 97 7/29/2025
1.1.0 98 7/28/2025
1.0.1 96 7/18/2025