# Md To PDF

> 使用 md-to-pdf（Markdown + Puppeteer + highlight.js）将 Markdown 文件转换为格式美观的 PDF。

- Skill: `loongyowl/md-to-pdf` (Agent Skill, multi-file: 5 files)
- Install (CLI): `npx skillmds@latest add loongyowl/md-to-pdf`
- Raw SKILL.md: https://api.skillmd.com/api/skills/loongyowl/md-to-pdf/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Docs & Writing
- License: MIT
- Author: loongyowl (https://skillmd.com/u/loongyowl)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/loongyowl/md-to-pdf

---


# Markdown to PDF Converter

将 Markdown 文件转换为高质量的 PDF 文档，支持代码语法高亮、自定义样式表以及完整的 Puppeteer PDF 自定义功能——使用独立的 Node.js.js.js 环境，无需系统级安装。

## Core Principles

- **自包含**：集成 Node.js + md-to-pdf；可在任何支持 bash 的机器上运行  
- **优先级解析**：命令行参数 > > > 前置内容 > > 配置文件 > 默认值  
- **跨平台**：Linux/macOS（完全自动），Windows（WSL 或主机上的 Node.js）  
- **支持方式**：单文件、批处理、标准输入管道、监视模式、自定义 CSS、代码高亮

## Quick Start

```bash
# 1. Convert a single file (auto-installs if needed)
bash scripts/md-to-pdf-convert.sh document.md

# 2. Convert with syntax highlighting
bash scripts/md-to-pdf-convert.sh document.md --highlight-style monokai

# 3. Convert with custom page size and margins
bash scripts/md-to-pdf-convert.sh document.md \
  --pdf-options '{"format":"A4","margin":{"top":"1in","bottom":"1in","left":"0.75in","right":"0.75in"}}'

# 4. Batch convert all markdown files in a directory
for f in docs/*.md; do bash scripts/md-to-pdf-convert.sh "$f"; done

# 5. Watch mode (auto-regenerate on save)
bash scripts/md-to-pdf-convert.sh document.md --watch
```

## Workflow

```
User provides .md file(s)
       │
       ▼
┌─────────────────┐
│ Check md-to-pdf  │── not found ──► Run install.sh
│ available?       │
└────────┬────────┘
         │ found
         ▼
┌─────────────────┐
│ Parse options    │   Read args: CSS, highlight, PDF config
│ & input file     │   Read front-matter if present
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Run md-to-pdf    │   md-to-pdf [options] input.md
│ Convert .md → .pdf │   Output: same dir, same name, .pdf extension
└────────┬────────┘
         │
         ▼
   Report output file path
```

## Detailed Instructions

### Step 1: Ensure Environment

The skill ships with two scripts:

| Script | Purpose |
|--------|---------|
| `scripts/install.sh` | Self-contained Node.js + md-to-pdf installation |
| `scripts/md-to-pdf-convert.sh` | Core conversion wrapper |

**On first use**, the convert script auto-detects missing dependencies and offers to install. Accept the installation prompt, or run manually:

```bash
bash scripts/install.sh
```

**Windows note**: On native Windows (no WSL), install Node.js 18+ from https://nodejs.org/ then run:
```bash
npm install md-to-pdf --prefix .hermes/skills/md-to-pdf/.local-md-to-pdf
```

### Step 2: Convert Files

Basic conversion — PDF output in same directory as source:

```bash
bash scripts/md-to-pdf-convert.sh report.md
# Output: report.pdf (same directory)
```

Multiple files (bash):

```bash
for f in chapters/*.md; do
  bash scripts/md-to-pdf-convert.sh "$f"
done
```

Single command for multiple files using shell globbing:

```bash
bash scripts/md-to-pdf-convert.sh docs/guide.md docs/api.md
# Note: each file generates its own PDF in its own directory
```

### Step 3: Apply Styling & Formatting

#### Code Syntax Highlighting

```bash
bash scripts/md-to-pdf-convert.sh document.md --highlight-style monokai
```

Popular themes: `monokai`, `solarized-light`, `github-dark`, `atom-one-dark`, `vs2015`

When using a theme with a background color, enable `printBackground`:

```bash
bash scripts/md-to-pdf-convert.sh document.md \
  --highlight-style monokai \
  --pdf-options '{"printBackground":true}'
```

#### Custom Stylesheet (CSS)

Local CSS file:

```bash
bash scripts/md-to-pdf-convert.sh document.md --stylesheet ./custom-style.css
```

Remote CSS URL:

```bash
bash scripts/md-to-pdf-convert.sh document.md \
  --stylesheet https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/monokai.min.css
```

Multiple stylesheets:

```bash
bash scripts/md-to-pdf-convert.sh document.md \
  --stylesheet ./base.css \
  --stylesheet ./custom.css
```

#### Inline CSS

```bash
bash scripts/md-to-pdf-convert.sh document.md \
  --css 'body { font-family: "Noto Sans SC", sans-serif; font-size: 12pt; }'
```

#### Front-matter Configuration (YAML)

Add to the top of your `.md` file:

```yaml
---
documentTitle: "My Document"
highlightStyle: monokai
pdfOptions:
  format: A4
  margin:
    top: 1in
    bottom: 1in
    left: 0.75in
    right: 0.75in
headerTemplate: '<div style="font-size:10px;text-align:center"><span class="date"></span></div>'
footerTemplate: '<div style="font-size:10px;text-align:center"><span class="pageNumber"></span> / <span class="totalPages"></span></div>'
---
```

### Step 4: Advanced Options

#### PDF Page Configuration

```bash
bash scripts/md-to-pdf-convert.sh doc.md \
  --pdf-options '{"format":"Letter","margin":{"top":"20mm","bottom":"20mm","left":"15mm","right":"15mm"}}'
```

Supported formats: `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid`, or custom `{width, height}` objects.

#### Headers and Footers

```bash
bash scripts/md-to-pdf-convert.sh doc.md \
  --pdf-options '{
    "headerTemplate": "<div style=\"font-size:9px;text-align:right\"><span class=\"date\"></span></div>",
    "footerTemplate": "<div style=\"font-size:9px;text-align:center\">Page <span class=\"pageNumber\"></span> / <span class=\"totalPages\"></span></div>"
  }'
```

#### Page Breaks

Insert a page break in your Markdown:

```html
<div class="page-break"></div>
```

Or in raw Markdown:

```markdown
---

<div class="page-break"></div>

---
```

#### Watch Mode

Auto-regenerate PDF when Markdown changes:

```bash
bash scripts/md-to-pdf-convert.sh doc.md --watch
```

Adjust polling for editors that modify files after save:

```bash
bash scripts/md-to-pdf-convert.sh doc.md \
  --watch --watch-options '{"awaitWriteFinish":{"stabilityThreshold":500,"pollInterval":100}}'
```

#### DevTools (Debug)

```bash
bash scripts/md-to-pdf-convert.sh doc.md --devtools
```

Opens headless Chrome with DevTools to inspect the rendered HTML before PDF generation.

## Environment Variable Overrides

Set these to customize behavior:

| Variable | Purpose | Default |
|----------|---------|---------|
| `MD_TO_PDF_HIGHLIGHT` | Default highlight.js theme | `solarized-light` |
| `MD_TO_PDF_CSS` | Default inline CSS | `""` |
| `MD_TO_PDF_FORMAT` | Default PDF page format | `A4` |
| `MD_TO_PDF_MARKDOWN_DIR` | Default input directory | `.` (current) |

## Batch Processing Example

Convert an entire documentation directory tree:

```bash
#!/bin/bash
# batch-convert.sh — placed in the same directory as SKILL.md
SKILL_DIR="$(cd "$(dirname "$0")" && pwd)"

find . -name "*.md" -not -path "*/.node-dist/*" -not -path "*/node_modules/*" | while read -r mdfile; do
  echo "[$mdfile] ..."
  bash "$SKILL_DIR/scripts/md-to-pdf-convert.sh" "$mdfile" \
    --highlight-style solarized-light \
    --pdf-options '{"format":"A4","margin":{"top":"1in","bottom":"1in","left":"0.75in","right":"0.75in"}}'
done

echo "=== Batch complete ==="
```

## Troubleshooting

| Problem | Solution |
|---------|----------|
| `md-to-pdf` not found | Run `bash scripts/install.sh` or ensure Node.js is installed |
| PDF is blank / blank pages | Puppeteer can't render — check `--devtools` output |
| Code blocks missing syntax highlighting | Use `--highlight-style` with a valid theme name |
| CSS not applied | Verify stylesheet path is relative to CWD, not to md-to-pdf install |
| Images not rendering | Use `--basedir` to set correct base directory for relative image paths |
| Chinese characters not showing | Add `--css 'body { font-family: "Noto Sans SC", sans-serif; }'` |
| Windows path issues | Use WSL, or convert Windows paths: `C:\Users\file.md` → `/c/Users/file.md` |
| Memory errors with large files | Increase Puppeteer memory: `--launch-options '{"args":["--no-sandbox","--disable-setuid-sandbox"]}'` |

## Bundled Resources

| Resource | File | Purpose |
|----------|------|---------|
| Options reference | `references/md-to-pdf-options.md` | Full CLI, Puppeteer, and front-matter option docs |
| CSS template | `references/professional-style.css` | Professional typography template with fonts, code blocks, tables |

## External References

- md-to-pdf GitHub: https://github.com/simonhaenisch/md-to-pdf
- highlight.js themes: https://highlightjs.org/static/demo/
- Puppeteer PDF options: https://pptr.dev/api/puppeteer.puppeteerpdfoptions/

---

*Based on [simonhaenisch/md-to-pdf](https://github.com/simonhaenisch/md-to-pdf). Adapted for cross-agent portability by Hermes Agent skill-maker.*

