
Markdown To Pdf
- 618 installs
- 7 repo stars
- Updated June 18, 2026
- duc01226/easyplatform
markdown-to-pdf is a Claude Code skill that converts markdown files into clean, professional PDF documents for developers who need printable or distributable documentation, proposals, and user guides.
About
markdown-to-pdf is a documentation skill from duc01226/easyplatform with 524 installs on skills.sh that turns markdown sources into polished PDF output for technical writing workflows. Developers reach for markdown-to-pdf when README drafts, API guides, proposals, or user manuals must leave the repo as formatted PDFs instead of raw .md files. The skill focuses on fast conversion with professional layout rather than complex desktop publishing setups. It suits teams shipping internal docs, client proposals, or exported help content without maintaining separate design tooling.
- Converts any markdown file or folder to PDF with one command
- Preserves formatting, headings, tables, and code blocks
- Supports custom CSS styling and header/footer options
- Works with GitHub-flavored markdown and frontmatter
- Outputs production-ready PDFs ready for sharing or printing
Markdown To Pdf by the numbers
- 618 all-time installs (skills.sh)
- Ranked #356 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/duc01226/easyplatform --skill markdown-to-pdfAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 618 |
|---|---|
| repo stars | ★ 7 |
| Last updated | June 18, 2026 |
| Repository | duc01226/easyplatform ↗ |
How do you convert markdown files to PDF?
Instantly turn markdown files into clean, professional PDFs for documentation, proposals, or user guides.
Who is it for?
Developers exporting READMEs, API docs, proposals, or user guides from markdown to shareable PDF format.
Skip if: Teams needing interactive HTML docs, complex InDesign layouts, or non-markdown source formats like LaTeX or Word.
When should I use this skill?
The user asks to convert markdown to PDF, export docs as PDF, or generate printable documentation from .md files.
What you get
A formatted PDF file generated from the source markdown with professional document layout.
- Professional PDF document
By the numbers
- 524 installs on skills.sh
- skills.sh rank 9223 for duc01226/easyplatform/markdown-to-pdf
Files
Codex compatibility note:
>
- Invoke repository skills with$skill-namein Codex; this mirrored copy rewrites legacy Claude/skill-namereferences.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required spawn_agent subagent(s) for that task.- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs. When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json(project-specific paths, commands, modules, and workflow/test settings)docs/project-reference/docs-index-reference.md(routes to the fulldocs/project-reference/*catalog)docs/project-reference/lessons.md(always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md,domain-entities-reference.md,project-structure-reference.md - Frontend/UI/styling/design-system:
frontend-patterns-reference.md,scss-styling-guide.md,design-system/README.md - Spec authoring,
docs/specs/pathing, or TC format:feature-spec-reference.md,spec-system-reference.md,spec-principles.md - Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.mdplus the spec docs above - Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.mdand source Feature Specs underdocs/specs/ - Integration test implementation/review:
integration-test-reference.md - E2E test implementation/review:
e2e-test-reference.md - Code review/audit work:
code-review-rules.mdplus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
Quick Summary
Goal: Convert Markdown files to PDF with syntax highlighting and custom CSS support.
Workflow:
1. Install -- Ensure required tools (pandoc + wkhtmltopdf or weasyprint) are available 2. Convert -- Run conversion with syntax highlighting and optional CSS 3. Verify -- Check PDF output for formatting and completeness
Key Rules:
- Requires pandoc + a PDF engine (wkhtmltopdf or weasyprint)
- Supports syntax highlighting for code blocks
- Custom CSS can be applied for styling
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
markdown-to-pdf
Convert markdown files to high-quality PDF documents with code syntax highlighting and custom CSS support.
Installation Required
This skill requires npm dependencies. Run one of the following:
# Option 1: Install via ClaudeKit CLI (recommended)
ck init # Runs install.sh which handles all skills
# Option 2: Manual installation
cd .claude/skills/markdown-to-pdf
npm installDependencies: md-to-pdf, gray-matter
Note: First run may download Chromium (~150MB) unless system Chrome is detected.
Quick Start
# Basic conversion
node .claude/skills/markdown-to-pdf/scripts/convert.cjs --input ./README.md
# Specify output path
node .claude/skills/markdown-to-pdf/scripts/convert.cjs --input ./doc.md --output ./output.pdf
# With custom CSS
node .claude/skills/markdown-to-pdf/scripts/convert.cjs --input ./doc.md --css ./my-style.cssCLI Options
| Option | Short | Description | Default |
|---|---|---|---|
--input | -i | Input markdown file path | (required) |
--output | -o | Output PDF file path | {input}.pdf |
--css | -c | Custom CSS file path | built-in |
--no-highlight | Disable syntax highlighting | false | |
--help | -h | Show help message |
Features
- Syntax Highlighting: Code blocks rendered with highlight.js
- Custom CSS: Override default styles with your own CSS
- Cross-OS: Works on Windows, macOS, Linux
- System Chrome: Uses installed Chrome/Chromium when available
- Frontmatter Support: YAML frontmatter extracted for title/metadata
Default Styling
The default PDF style includes:
- Serif font (Georgia) for body text
- Monospace font (Consolas/Monaco) for code
- Proper page margins (2cm)
- Code block background highlighting
- Table borders and alternating row colors
Output
Returns JSON on success:
{
"success": true,
"input": "/path/to/input.md",
"output": "/path/to/output.pdf",
"pages": 3
}Troubleshooting
Chrome not found: The skill will automatically download Chromium. Set PUPPETEER_SKIP_DOWNLOAD=1 to prevent this.
Memory issues: Large documents may require more memory. Consider splitting into multiple files.
Font issues: Embed fonts via CSS @font-face with base64-encoded fonts for consistent rendering.
---
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
<!-- SYNC:ai-mistake-prevention -->
AI Mistake Prevention — Failure modes to avoid on every task:
>
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect.
Assume existing values are intentional — ask WHY before changing. Before changing a constant, limit, flag, wording, or pattern, read nearby context and history.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
<!-- /SYNC:ai-mistake-prevention -->
<!-- SYNC:critical-thinking-mindset -->
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
Anti-hallucination: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
<!-- /SYNC:critical-thinking-mindset -->
<!-- SYNC:critical-thinking-mindset:reminder -->
MUST ATTENTION apply critical + sequential thinking — every claim needs appropriate traced evidence (file:line for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
<!-- /SYNC:critical-thinking-mindset:reminder -->
<!-- SYNC:ai-mistake-prevention:reminder -->
MUST ATTENTION apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
<!-- /SYNC:ai-mistake-prevention:reminder -->
Closing Reminders
IMPORTANT MUST ATTENTION — Protocols in force (concise digest of the SYNC/shared blocks this skill carries):
- Critical Thinking: Traced
file:lineproof per claim; confidence >80% to act; NEVER present guess as fact. - AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
IMPORTANT MUST ATTENTION break work into small todo tasks using task tracking BEFORE starting IMPORTANT MUST ATTENTION search codebase for 3+ similar patterns before creating new code IMPORTANT MUST ATTENTION cite file:line evidence for every claim (confidence >80% to act) IMPORTANT MUST ATTENTION add a final review todo task to verify work quality
[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
Hookless Prompt Protocol Mirror (Auto-Synced)
Source: .claude/.ck.json + .claude/skills/shared/sync-inline-versions.md (:full blocks) + .claude/scripts/lib/hookless-prompt-protocol.cjs
[WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
Generic portability boundary: Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from shared/sdd-artifact-contract.md. Read docs/project-config.json and docs/project-reference/docs-index-reference.md, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or docs/specs/ work, route through the local spec docs named by the docs index: feature-spec-reference.md, spec-system-reference.md, spec-principles.md, and workflow-spec-test-code-cycle-reference.md when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run $project-init (or the narrow lower-level route such as $project-config, $docs-init, $scan-all, or $scan --target=<key>) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
1. DETECT: If the prompt starts with an explicit slash skill/workflow command, execute it directly. Otherwise match the prompt against the workflow catalog and skill list. 2. ANALYZE: Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination. 3. AUTO-SELECT: Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow. 4. ACTIVATE: For a selected workflow, call $start-workflow <workflowId>; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task. 5. CREATE TASKS: task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps. 6. EXECUTE: Advance per the Workflow Step Advancement & Parallel Phases rule in your context instructions — model-driven; a sub-agent completion advances a step identically to an inline call; a parallel-phase group is an all-return barrier (advance only after ALL members return, never serialize it)
Shared AI-SDD Protocol Markers
Source: .claude/skills/shared/sync-inline-versions.md
SYNC:ai-sdd-artifact-contract
AI-SDD Artifact Contract — Shared spec-driven development rules stay portable and source-owned.
>
1. Keep reusable AI-SDD principles in .claude; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.2. Preserve cycle: spec -> plan -> tasks -> implement -> verify -> update spec/docs.3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
6. Update.claudesource first, then sync generated mirrors; do not manually edit.agents,.codex, orAGENTS.md. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
7. Ifdocs/project-config.json, root instruction files, or a required project-reference doc is missing or stale, auto-run$project-initor the narrow lower-level route before ordinary project-specific work.
>
Active reference: shared/sdd-artifact-contract.md in the active skills root.---
SYNC:ai-sdd-artifact-contract:reminder
- MANDATORY Apply
shared/sdd-artifact-contract.md; keep reusable AI-SDD in.claudeand local rules in project docs. - MANDATORY Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
- MANDATORY Update
.claudesource before syncing generated mirrors; do not manually edit.agents,.codex, orAGENTS.md. - MANDATORY Missing or stale project config, root instruction files, or required reference docs route project-specific work through
$project-initor the narrow setup route automatically.
[TASK-PLANNING] [MANDATORY] BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.
[LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
Extract lessons — ROOT CAUSE ONLY, not symptom fixes:
1. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value". 2. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up. 3. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase. 4. Consolidate: multiple mistakes sharing one failure mode → ONE lesson. 5. Recurrence gate: "Would this recur in future session WITHOUT this reminder?" — No → skip $learn. 6. Auto-fix gate: "Could $code-review/$code-simplifier/$security-review/$lint catch this?" — Yes → improve review skill instead. 7. BOTH gates pass → ask user to run $learn. [CRITICAL-THINKING-MINDSET] Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act. Anti-hallucination principle: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination. AI Attention principle (Primacy-Recency): Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows. Goal-driven execution: Define success criteria first, loop until verified, and stop only when observable checks pass. Tests verify intent: Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
Common AI Mistake Prevention (System Lessons)
- Re-read files after context compaction. Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
- Grep for old terms after bulk replacements. AI over-trusts find/replace completeness. Grep full repo after bulk edits for missed refs in docs/configs/catalogs.
- Check downstream references before deleting. Deletions cascade doc/code staleness. Map referencing files before removal.
- After memory loss, check existing state before creating new. Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
- Verify AI-generated content against actual code. AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
- Trace full dependency chain after edits. Changing a definition misses downstream consumers. Trace the full chain.
- When renaming, grep ALL consumer file types. Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
- Trace ALL code paths when verifying correctness. Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
- Update docs that embed canonical data when source changes. Docs inlining derived data (workflows, schemas, configs) go stale silently. Update all embedding docs alongside source.
- Verify sub-agent results after context recovery. Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
- Cross-check full target list against sub-agent assignments. Parallel sub-agents by category miss boundary items. Reconcile union of assignments against target list before proceeding.
- Sub-agents inherit knowledge only from their agent .md definition — use custom agent types, not built-in Explore. Tool adoption = permission + knowledge + enforcement (numbered workflow step).
- Persist sub-agent findings incrementally, not as a final batch. Long sub-agents hit cutoffs before final write — findings lost. Instruct append-per-section to report file.
- When debugging, ask "whose responsibility?" before fixing. Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
- Grep ALL removed names after extraction/refactoring. Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
- Assume existing values are intentional — ask WHY before changing. Pattern-matching as "wrong" skips context. Before changing any constant/limit/flag: read comments, git blame, surrounding code.
- Verify ALL affected outputs, not just the first. One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
- Evaluate fit before copying a nearby pattern. Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
- Holistic-first debugging — resist nearest-attention trap. Don't dive into first plausible cause. List EVERY precondition (config, env vars, paths, DB, endpoints, creds, versions, DI, data). Verify each against evidence (grep/query — not reasoning). Ask "what would falsify this?" — if nothing, it's not a hypothesis. Most expensive failure: going deeper in "obvious" layer while bug sits in layer never questioned.
- Surgical changes — apply the diff test (context-aware). Two modes: (1) Bug fix → every line traces to the bug; no restyling; orphan cleanup only for imports YOUR changes made unused. (2) Review/enhancement → implement improvements AND announce as "Enhancement beyond main request: [what]". Never silently scope-creep. Diff test: "Would this line exist if I wasn't asked to do X?" — if no, delete or announce.
- Surface ambiguity before coding — don't pick silently. Multiple valid interpretations → present each with effort: "[Request] could mean (1) [N h], (2) [N h]. Which matters?" List scope/format/volume/constraints assumptions first. If simpler path exists, say so. Never silently pick.
- [MANDATORY FIRST ACTION] ALWAYS activate a suitable skill or workflow BEFORE responding. Match task against workflow catalog + skill list; invoke via skill invocation or
$start-workflow <workflowId>. NEVER answer or write code before checking. Skip = protocol violation. - Why-Review adversarial mindset — apply when reviewing any plan, decision, or design. Default SKEPTIC not VALIDATOR: steel-man a rejected alternative, invert each stated reason ("what does it sacrifice?"), stress-test top 2-3 assumptions, run pre-mortem ("ships, fails in 3 months — what breaks?"), surface 1-2 alternatives author missed. Section presence ≠ quality; quality = causal reasoning + concrete mitigations + evidence, not "it's better" or "monitor closely".
- Front-load report-write in sub-agent prompts for large reviews. Many-file sub-agents hit budget before final write — findings lost. Design prompts so: (1) report-write is first explicit deliverable, (2) append per-file/section (not batched), (3) scope bounded so reads don't exhaust budget. Truncated mid-sentence with no report file → spawn narrower scope, don't retry same prompt.
- After context compaction, re-verify all prior phase outcomes before continuing. Summaries describe intent, not environment state (git index, filesystem, processes). On resume, FIRST audit: git status, re-read modified files, verify filesystem. Every "completed" claim is an untested hypothesis until evidence confirms.
- OOM/memory: check row count before row size. Triage: (1) Unbounded query — no DB filter for trigger? Push filter to DB; eliminates OOM. (2) Large rows? Projection reduces proportionally. Row reduction > projection in ROI.
- Keep domain concepts out of generic/shared/infrastructure layers. Reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. Leak compiles + runs → passes review silently while coupling the "reusable" layer to one consumer. Keep shared type domain-free; push domain fields/logic down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable.
<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->
/* Default PDF styling for markdown-to-pdf skill */
/* Page setup */
@page {
size: A4;
margin: 2cm;
}
/* Body */
body {
font-family: Georgia, 'Times New Roman', serif;
font-size: 12pt;
line-height: 1.6;
color: #333;
max-width: none;
}
/* Headings */
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
margin-top: 1.5em;
margin-bottom: 0.5em;
page-break-after: avoid;
}
h1 {
font-size: 24pt;
border-bottom: 2px solid #333;
padding-bottom: 0.3em;
}
h2 {
font-size: 18pt;
border-bottom: 1px solid #ccc;
padding-bottom: 0.2em;
}
h3 {
font-size: 14pt;
}
h4 {
font-size: 12pt;
}
/* Paragraphs */
p {
margin: 0.8em 0;
text-align: justify;
}
/* Code blocks */
pre {
background-color: #f6f8fa;
border: 1px solid #e1e4e8;
border-radius: 4px;
padding: 1em;
overflow-x: auto;
font-size: 10pt;
line-height: 1.4;
page-break-inside: avoid;
}
code {
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}
/* Inline code */
p code,
li code {
background-color: #f6f8fa;
padding: 0.2em 0.4em;
border-radius: 3px;
font-size: 0.9em;
}
/* Tables */
table {
border-collapse: collapse;
width: 100%;
margin: 1em 0;
page-break-inside: avoid;
}
th,
td {
border: 1px solid #ddd;
padding: 8px 12px;
text-align: left;
}
th {
background-color: #f6f8fa;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #fafafa;
}
/* Lists */
ul,
ol {
margin: 0.8em 0;
padding-left: 2em;
}
li {
margin: 0.3em 0;
}
/* Blockquotes */
blockquote {
border-left: 4px solid #ddd;
margin: 1em 0;
padding: 0.5em 1em;
color: #666;
background-color: #fafafa;
}
/* Links */
a {
color: #0366d6;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* Images */
img {
max-width: 100%;
height: auto;
display: block;
margin: 1em auto;
}
/* Horizontal rule */
hr {
border: none;
border-top: 1px solid #ddd;
margin: 2em 0;
}
/* Page breaks */
.page-break {
page-break-after: always;
}
/* Print-specific */
@media print {
body {
font-size: 11pt;
}
pre {
white-space: pre-wrap;
word-wrap: break-word;
}
a {
color: #333;
}
a[href^='http']::after {
content: ' (' attr(href) ')';
font-size: 0.8em;
color: #666;
}
}
{
"name": "markdown-to-pdf",
"version": "1.0.0",
"description": "Convert markdown files to PDF with syntax highlighting and custom CSS",
"main": "scripts/convert.cjs",
"scripts": {
"start": "node scripts/convert.cjs",
"test": "node tests/run-tests.cjs"
},
"dependencies": {
"gray-matter": "^4.0.3",
"md-to-pdf": "^5.2.4"
},
"engines": {
"node": ">=18.0.0"
}
}
#!/usr/bin/env node
/**
* Markdown to PDF Converter CLI
* Converts markdown files to PDF with syntax highlighting and custom CSS
*
* Usage:
* node convert.cjs --input ./doc.md [--output ./out.pdf] [--css ./style.css]
*
* Options:
* --input, -i Input markdown file (required)
* --output, -o Output PDF path (default: input.pdf)
* --css, -c Custom CSS file path
* --no-highlight Disable syntax highlighting
* --help, -h Show help message
*/
const path = require('path');
/**
* Parse command line arguments
* @param {string[]} argv - Process arguments
* @returns {{input: string|null, output: string|null, css: string|null, noHighlight: boolean, help: boolean}}
*/
function parseArgs(argv) {
const args = {
input: null,
output: null,
css: null,
noHighlight: false,
help: false
};
for (let i = 2; i < argv.length; i++) {
const arg = argv[i];
const nextArg = argv[i + 1];
switch (arg) {
case '--input':
case '-i':
args.input = nextArg;
i++;
break;
case '--output':
case '-o':
args.output = nextArg;
i++;
break;
case '--css':
case '-c':
args.css = nextArg;
i++;
break;
case '--no-highlight':
args.noHighlight = true;
break;
case '--help':
case '-h':
args.help = true;
break;
default:
// Handle positional argument (assume input file)
if (!arg.startsWith('-') && !args.input) {
args.input = arg;
}
}
}
return args;
}
/**
* Print help message
* @returns {void}
*/
function printHelp() {
console.log(`
markdown-to-pdf - Convert markdown files to PDF
USAGE:
node convert.cjs --input <file.md> [options]
node convert.cjs <file.md> [options]
OPTIONS:
--input, -i <path> Input markdown file (required)
--output, -o <path> Output PDF path (default: same as input with .pdf)
--css, -c <path> Custom CSS stylesheet
--no-highlight Disable code syntax highlighting
--help, -h Show this help message
EXAMPLES:
# Basic conversion
node convert.cjs --input ./README.md
# With custom output path
node convert.cjs -i ./docs/guide.md -o ./output/guide.pdf
# With custom CSS
node convert.cjs -i ./report.md -c ./custom-style.css
OUTPUT:
Returns JSON on success:
{
"success": true,
"input": "/path/to/input.md",
"output": "/path/to/output.pdf",
"pages": 5
}
Returns JSON on error:
{
"success": false,
"error": "Error description"
}
EXIT CODES:
0 Success
1 Error (missing input, conversion failed, etc.)
`);
}
/**
* Print result as JSON
* @param {object} result - Result object
* @returns {void}
*/
function printResult(result) {
console.log(JSON.stringify(result, null, 2));
}
/**
* Validate arguments
* @param {{input: string|null}} args - Parsed arguments
* @returns {{valid: boolean, error?: string}}
*/
function validateArgs(args) {
if (!args.input) {
return {
valid: false,
error: 'Input file is required. Use --input <path> or provide a positional argument.'
};
}
return { valid: true };
}
/**
* Check if dependencies are installed
* @returns {{available: boolean, missing: string[]}}
*/
function checkDependencies() {
const missing = [];
try {
require.resolve('md-to-pdf');
} catch {
missing.push('md-to-pdf');
}
try {
require.resolve('gray-matter');
} catch {
missing.push('gray-matter');
}
return {
available: missing.length === 0,
missing
};
}
/**
* Main entry point
* @returns {Promise<void>}
*/
async function main() {
const args = parseArgs(process.argv);
// Handle help flag
if (args.help) {
printHelp();
process.exit(0);
}
// Validate arguments
const validation = validateArgs(args);
if (!validation.valid) {
printResult({
success: false,
error: validation.error
});
process.exit(1);
}
// Check dependencies
const deps = checkDependencies();
if (!deps.available) {
printResult({
success: false,
error: `Missing dependencies: ${deps.missing.join(', ')}. Run 'npm install' in the skill directory.`,
hint: `cd ${path.dirname(__dirname)} && npm install`
});
process.exit(1);
}
// Import converter (lazy load after dependency check)
const { convert } = require('./lib/converter.cjs');
// Perform conversion
try {
const result = await convert({
input: args.input,
output: args.output,
css: args.css,
noHighlight: args.noHighlight
});
printResult(result);
process.exit(result.success ? 0 : 1);
} catch (error) {
printResult({
success: false,
error: error.message || 'Unexpected error during conversion'
});
process.exit(1);
}
}
// Run main function
main().catch(error => {
console.error(JSON.stringify({
success: false,
error: `Unhandled error: ${error.message}`
}));
process.exit(1);
});
/**
* Chrome/Chromium executable finder
* Detects system-installed Chrome to avoid downloading bundled Chromium
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
/**
* Known Chrome installation paths by platform
* @type {Record<string, string[]>}
*/
const CHROME_PATHS = {
win32: [
path.join(process.env.PROGRAMFILES || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
path.join(process.env['PROGRAMFILES(X86)'] || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
path.join(process.env.LOCALAPPDATA || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
// Edge (Chromium-based)
path.join(process.env.PROGRAMFILES || '', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
path.join(process.env['PROGRAMFILES(X86)'] || '', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
],
darwin: [
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/Applications/Chromium.app/Contents/MacOS/Chromium',
path.join(process.env.HOME || '', 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome'),
],
linux: [
'/usr/bin/google-chrome',
'/usr/bin/google-chrome-stable',
'/usr/bin/chromium',
'/usr/bin/chromium-browser',
'/snap/bin/chromium',
'/snap/bin/google-chrome',
]
};
/**
* Find Chrome executable on the system
* @returns {string|null} Path to Chrome executable or null if not found
*/
function findChrome() {
const platform = process.platform;
const paths = CHROME_PATHS[platform] || [];
for (const chromePath of paths) {
if (chromePath && fs.existsSync(chromePath)) {
return chromePath;
}
}
// Fallback: try 'which' command on Unix-like systems
if (platform !== 'win32') {
try {
const result = execSync('which google-chrome || which chromium || which chromium-browser 2>/dev/null', {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore']
}).trim();
if (result && fs.existsSync(result)) {
return result;
}
} catch {
// Command failed, no Chrome found
}
}
return null;
}
/**
* Get Puppeteer launch arguments for the current platform
* @returns {string[]} Array of Chrome launch arguments
*/
function getPuppeteerArgs() {
const args = [
'--disable-gpu',
'--disable-dev-shm-usage', // Helps in Docker/CI environments
];
// Windows and some Linux environments need --no-sandbox
if (process.platform === 'win32') {
args.push('--no-sandbox', '--disable-setuid-sandbox');
}
// Check if running in a sandbox-restricted environment
if (process.env.CI || process.env.DOCKER) {
args.push('--no-sandbox', '--disable-setuid-sandbox');
}
return args;
}
/**
* Get Chrome configuration for md-to-pdf
* @returns {{executablePath: string|undefined, args: string[], systemChrome: boolean}}
*/
function getChromeConfig() {
const executablePath = findChrome();
const args = getPuppeteerArgs();
return {
executablePath: executablePath || undefined,
args,
systemChrome: !!executablePath
};
}
module.exports = {
findChrome,
getPuppeteerArgs,
getChromeConfig,
CHROME_PATHS
};
/**
* Configuration and CSS file loader
* Handles custom CSS injection and config file parsing
*/
const fs = require('fs');
const path = require('path');
// Path to default CSS
const DEFAULT_CSS_PATH = path.join(__dirname, '..', '..', 'assets', 'default-style.css');
/**
* Load CSS from file path
* @param {string|null} cssPath - Path to CSS file (null for default)
* @returns {string} CSS content
*/
function loadCSS(cssPath) {
const targetPath = cssPath || DEFAULT_CSS_PATH;
if (!fs.existsSync(targetPath)) {
if (cssPath) {
throw new Error(`CSS file not found: ${cssPath}`);
}
// Return minimal fallback if default CSS missing
return `
body { font-family: Georgia, serif; font-size: 12pt; line-height: 1.6; }
pre { background: #f5f5f5; padding: 1em; overflow-x: auto; }
code { font-family: monospace; }
`;
}
return fs.readFileSync(targetPath, 'utf8');
}
/**
* Load markdown file and extract frontmatter
* @param {string} filePath - Path to markdown file
* @returns {{content: string, frontmatter: object}}
*/
function loadMarkdown(filePath) {
if (!fs.existsSync(filePath)) {
throw new Error(`Markdown file not found: ${filePath}`);
}
const content = fs.readFileSync(filePath, 'utf8');
// Lazy load gray-matter only when needed
let matter;
try {
matter = require('gray-matter');
} catch {
// gray-matter not installed, return raw content
return { content, frontmatter: {} };
}
const parsed = matter(content);
return {
content: parsed.content,
frontmatter: parsed.data || {}
};
}
/**
* Get CSS file path (resolves custom or default)
* @param {string|null} cssPath - Custom CSS path or null for default
* @returns {string} Resolved CSS file path
*/
function getCSSPath(cssPath) {
if (cssPath) {
const resolved = path.resolve(cssPath);
if (!fs.existsSync(resolved)) {
throw new Error(`CSS file not found: ${cssPath}`);
}
return resolved;
}
return DEFAULT_CSS_PATH;
}
/**
* Build md-to-pdf configuration object
* @param {object} options - Configuration options
* @param {string|null} options.cssPath - Path to custom CSS
* @param {boolean} options.noHighlight - Disable syntax highlighting
* @param {string} options.title - Document title
* @returns {object} md-to-pdf config
*/
function buildConfig(options = {}) {
// md-to-pdf expects stylesheet as file path, not content
const stylesheetPath = getCSSPath(options.cssPath);
const config = {
stylesheet: stylesheetPath,
pdf_options: {
format: 'A4',
margin: {
top: '2cm',
bottom: '2cm',
left: '2cm',
right: '2cm'
},
printBackground: true
},
highlight_style: options.noHighlight ? null : 'github',
marked_options: {
gfm: true,
breaks: false
}
};
// Add document title from frontmatter if available
if (options.title) {
config.document_title = options.title;
}
return config;
}
module.exports = {
loadCSS,
loadMarkdown,
buildConfig,
getCSSPath,
DEFAULT_CSS_PATH
};
/**
* Core markdown-to-PDF converter
* Wraps md-to-pdf with Chrome detection and cross-platform handling
*/
const fs = require('fs');
const path = require('path');
const { getChromeConfig } = require('./chrome-finder.cjs');
const { loadMarkdown, buildConfig } = require('./config-loader.cjs');
const { resolveOutputPath, cleanupTempFiles } = require('./output-handler.cjs');
/**
* Convert markdown file to PDF
*
* @param {object} options - Conversion options
* @param {string} options.input - Input markdown file path
* @param {string|null} options.output - Output PDF path (optional)
* @param {string|null} options.css - Custom CSS file path (optional)
* @param {boolean} options.noHighlight - Disable syntax highlighting
* @returns {Promise<{success: boolean, input: string, output: string, pages?: number, systemChrome?: boolean, error?: string}>}
*/
async function convert(options) {
const { input, output, css, noHighlight = false } = options;
// Validate input
if (!input) {
return { success: false, error: 'Input file path is required' };
}
const absoluteInput = path.resolve(input);
if (!fs.existsSync(absoluteInput)) {
return { success: false, error: `Input file not found: ${absoluteInput}` };
}
try {
// Clean up old temp files (async cleanup)
cleanupTempFiles();
// Load markdown and extract frontmatter
const { content, frontmatter } = loadMarkdown(absoluteInput);
// Build configuration
const config = buildConfig({
cssPath: css,
noHighlight,
title: frontmatter.title || path.basename(absoluteInput, '.md')
});
// Get Chrome configuration
const chromeConfig = getChromeConfig();
// Import md-to-pdf dynamically (lazy load)
const { mdToPdf } = require('md-to-pdf');
// Resolve output path
const outputPath = resolveOutputPath(absoluteInput, output);
// Perform conversion
await mdToPdf(
{ content },
{
...config,
dest: outputPath,
launch_options: {
executablePath: chromeConfig.executablePath,
args: chromeConfig.args,
headless: 'new' // Use new headless mode
},
basedir: path.dirname(absoluteInput) // Resolve relative paths from input dir
}
);
// Verify output was created
if (!fs.existsSync(outputPath)) {
return { success: false, error: 'PDF generation failed - no output file created' };
}
// Get page count (approximate from file size)
const stats = fs.statSync(outputPath);
const estimatedPages = Math.max(1, Math.ceil(stats.size / 50000)); // Rough estimate
return {
success: true,
input: absoluteInput,
output: outputPath,
pages: estimatedPages,
systemChrome: chromeConfig.systemChrome
};
} catch (error) {
// Handle specific error types
if (error.message && error.message.includes('Could not find Chromium')) {
return {
success: false,
error: 'Chromium not found. Run `npm install` in the skill directory or install Chrome/Chromium system-wide.'
};
}
if (error.message && error.message.includes('ENOENT')) {
return {
success: false,
error: `File not found: ${error.path || input}`
};
}
return {
success: false,
error: error.message || 'Unknown conversion error',
stack: process.env.DEBUG ? error.stack : undefined
};
}
}
/**
* Check if md-to-pdf is available
* @returns {boolean}
*/
function isAvailable() {
try {
require.resolve('md-to-pdf');
return true;
} catch {
return false;
}
}
module.exports = {
convert,
isAvailable
};
/**
* Output path resolution and file handling
* Handles various output path scenarios
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
/**
* Resolve output path based on input and user preference
*
* Logic:
* Input: ./docs/readme.md, Output: null → ./docs/readme.pdf
* Input: ./docs/readme.md, Output: ./out/ → ./out/readme.pdf
* Input: ./docs/readme.md, Output: ./my.pdf → ./my.pdf
*
* @param {string} inputPath - Input markdown file path
* @param {string|null} outputPath - User-specified output path (optional)
* @returns {string} Resolved absolute output path
*/
function resolveOutputPath(inputPath, outputPath) {
const absoluteInput = path.resolve(inputPath);
const inputDir = path.dirname(absoluteInput);
const inputBasename = path.basename(absoluteInput, path.extname(absoluteInput));
// Default: same directory as input, .pdf extension
if (!outputPath) {
return path.join(inputDir, `${inputBasename}.pdf`);
}
const absoluteOutput = path.resolve(outputPath);
// Check if output is a directory (existing or ends with separator)
const isDirectory = outputPath.endsWith(path.sep) ||
outputPath.endsWith('/') ||
(fs.existsSync(absoluteOutput) && fs.statSync(absoluteOutput).isDirectory());
if (isDirectory) {
// Ensure directory exists
fs.mkdirSync(absoluteOutput, { recursive: true });
return path.join(absoluteOutput, `${inputBasename}.pdf`);
}
// Output is a file path - ensure parent directory exists
const outputDir = path.dirname(absoluteOutput);
fs.mkdirSync(outputDir, { recursive: true });
// Ensure .pdf extension
if (!absoluteOutput.toLowerCase().endsWith('.pdf')) {
return `${absoluteOutput}.pdf`;
}
return absoluteOutput;
}
/**
* Create a temporary file path for intermediate operations
* @param {string} prefix - Filename prefix
* @returns {string} Temporary file path
*/
function createTempPath(prefix = 'md-to-pdf') {
const tempDir = path.join(os.tmpdir(), 'markdown-to-pdf');
fs.mkdirSync(tempDir, { recursive: true });
return path.join(tempDir, `${prefix}-${Date.now()}.pdf`);
}
/**
* Clean up old temporary files (older than 1 hour)
* @returns {void}
*/
function cleanupTempFiles() {
const tempDir = path.join(os.tmpdir(), 'markdown-to-pdf');
if (!fs.existsSync(tempDir)) return;
const oneHourAgo = Date.now() - 60 * 60 * 1000;
try {
const files = fs.readdirSync(tempDir);
for (const file of files) {
const filePath = path.join(tempDir, file);
try {
const stat = fs.statSync(filePath);
if (stat.mtimeMs < oneHourAgo) {
fs.unlinkSync(filePath);
}
} catch {
// Ignore individual file errors
}
}
} catch {
// Ignore cleanup errors
}
}
module.exports = {
resolveOutputPath,
createTempPath,
cleanupTempFiles
};
/**
* Tests for chrome-finder.cjs
*/
const path = require('path');
describe('chrome-finder', () => {
const { findChrome, getPuppeteerArgs, getChromeConfig, CHROME_PATHS } = require('../scripts/lib/chrome-finder.cjs');
it('should export CHROME_PATHS for current platform', () => {
const platform = process.platform;
assert.ok(CHROME_PATHS[platform], `CHROME_PATHS should have entries for ${platform}`);
assert.ok(Array.isArray(CHROME_PATHS[platform]), 'CHROME_PATHS entry should be an array');
});
it('should return array from getPuppeteerArgs', () => {
const args = getPuppeteerArgs();
assert.ok(Array.isArray(args), 'getPuppeteerArgs should return array');
assert.ok(args.includes('--disable-gpu'), 'Should include --disable-gpu');
});
it('should include --no-sandbox on Windows', () => {
if (process.platform === 'win32') {
const args = getPuppeteerArgs();
assert.ok(args.includes('--no-sandbox'), 'Windows should have --no-sandbox');
} else {
// On non-Windows, just verify the function runs
const args = getPuppeteerArgs();
assert.ok(Array.isArray(args), 'Should return array on any platform');
}
});
it('should return object from getChromeConfig', () => {
const config = getChromeConfig();
assert.ok(typeof config === 'object', 'getChromeConfig should return object');
assert.ok('args' in config, 'Config should have args property');
assert.ok('systemChrome' in config, 'Config should have systemChrome property');
assert.ok(typeof config.systemChrome === 'boolean', 'systemChrome should be boolean');
});
it('findChrome should return string or null', () => {
const result = findChrome();
assert.ok(result === null || typeof result === 'string', 'findChrome should return string or null');
});
it('should have at least 3 Chrome paths for each platform', () => {
for (const [platform, paths] of Object.entries(CHROME_PATHS)) {
assert.ok(paths.length >= 2, `Platform ${platform} should have at least 2 Chrome paths`);
}
});
});
/**
* Tests for converter.cjs and related modules
*/
const fs = require('fs');
const path = require('path');
describe('config-loader', () => {
const { loadCSS, loadMarkdown, buildConfig, getCSSPath, DEFAULT_CSS_PATH } = require('../scripts/lib/config-loader.cjs');
const fixturesDir = path.join(__dirname, 'fixtures');
const sampleMd = path.join(fixturesDir, 'sample.md');
it('should have correct DEFAULT_CSS_PATH', () => {
assert.ok(DEFAULT_CSS_PATH.endsWith('default-style.css'), 'DEFAULT_CSS_PATH should end with default-style.css');
});
it('should load default CSS', () => {
const css = loadCSS(null);
assert.ok(css.length > 0, 'Default CSS should not be empty');
assert.ok(css.includes('body'), 'CSS should have body styles');
});
it('should throw for missing custom CSS via loadCSS', () => {
let threw = false;
try {
loadCSS('/nonexistent/path/to/file.css');
} catch (e) {
threw = true;
assert.ok(e.message.includes('CSS file not found'), 'Error should mention CSS file not found');
}
assert.ok(threw, 'Should throw for missing CSS file');
});
it('should return default CSS path via getCSSPath', () => {
const cssPath = getCSSPath(null);
assert.equal(cssPath, DEFAULT_CSS_PATH, 'Should return default CSS path');
});
it('should throw for missing custom CSS via getCSSPath', () => {
let threw = false;
try {
getCSSPath('/nonexistent/path/to/file.css');
} catch (e) {
threw = true;
assert.ok(e.message.includes('CSS file not found'), 'Error should mention CSS file not found');
}
assert.ok(threw, 'Should throw for missing CSS file');
});
it('should load markdown with frontmatter', () => {
const { content, frontmatter } = loadMarkdown(sampleMd);
assert.ok(content.length > 0, 'Content should not be empty');
assert.ok(typeof frontmatter === 'object', 'Frontmatter should be object');
// Note: frontmatter parsing requires gray-matter
});
it('should throw for missing markdown file', () => {
let threw = false;
try {
loadMarkdown('/nonexistent/file.md');
} catch (e) {
threw = true;
assert.ok(e.message.includes('Markdown file not found'), 'Error should mention file not found');
}
assert.ok(threw, 'Should throw for missing markdown file');
});
it('should build config object', () => {
const config = buildConfig({ noHighlight: false });
assert.ok('stylesheet' in config, 'Config should have stylesheet');
assert.ok(config.stylesheet.endsWith('default-style.css'), 'stylesheet should be path to default CSS');
assert.ok('pdf_options' in config, 'Config should have pdf_options');
assert.equal(config.pdf_options.format, 'A4', 'Default format should be A4');
});
it('should disable highlighting when noHighlight is true', () => {
const config = buildConfig({ noHighlight: true });
assert.equal(config.highlight_style, null, 'highlight_style should be null when disabled');
});
it('should set document title', () => {
const config = buildConfig({ title: 'My Document' });
assert.equal(config.document_title, 'My Document', 'Should set document_title');
});
});
describe('output-handler', () => {
const { resolveOutputPath, createTempPath, cleanupTempFiles } = require('../scripts/lib/output-handler.cjs');
const os = require('os');
const fixturesDir = path.join(__dirname, 'fixtures');
it('should resolve output path from input (no output specified)', () => {
const result = resolveOutputPath('/path/to/doc.md', null);
assert.ok(result.endsWith('.pdf'), 'Result should end with .pdf');
assert.ok(result.includes('doc.pdf'), 'Result should contain doc.pdf');
});
it('should use explicit output path', () => {
const result = resolveOutputPath('/path/to/doc.md', '/output/file.pdf');
assert.ok(result.endsWith('.pdf'), 'Output should end with .pdf');
});
it('should handle directory output', () => {
// Use fixtures dir which exists
const result = resolveOutputPath('/path/to/doc.md', fixturesDir + '/');
assert.ok(result.includes('doc.pdf'), 'Should append filename to directory');
});
it('should add .pdf extension if missing', () => {
const result = resolveOutputPath('/path/to/doc.md', '/output/file');
assert.ok(result.endsWith('.pdf'), 'Should add .pdf extension');
});
it('should create temp path', () => {
const tempPath = createTempPath('test');
assert.ok(tempPath.includes(os.tmpdir()), 'Should be in temp directory');
assert.ok(tempPath.endsWith('.pdf'), 'Should end with .pdf');
});
it('should run cleanupTempFiles without error', () => {
// Just verify it doesn't throw
cleanupTempFiles();
assert.ok(true, 'cleanupTempFiles should not throw');
});
});
describe('converter', () => {
const { isAvailable } = require('../scripts/lib/converter.cjs');
it('should report availability', () => {
const available = isAvailable();
assert.ok(typeof available === 'boolean', 'isAvailable should return boolean');
});
});
Sample Markdown Document
This is a test document for the markdown-to-pdf skill.
Code Example
function hello() {
console.log('Hello, World!');
}Table Example
| Name | Value |
|---|---|
| Alpha | 1 |
| Beta | 2 |
List Example
- Item 1
- Item 2
- Nested item
Blockquote
This is a blockquote
spanning multiple lines.
---
End of document.
#!/usr/bin/env node
/**
* Test runner for markdown-to-pdf skill
*/
const fs = require('fs');
const path = require('path');
// Load test framework
require('./test-framework.cjs');
const testsDir = __dirname;
const testFiles = [
'chrome-finder.test.cjs',
'converter.test.cjs'
];
console.log('\n' + '='.repeat(60));
console.log('markdown-to-pdf Test Suite');
console.log('='.repeat(60));
// Load test files
for (const testFile of testFiles) {
const testPath = path.join(testsDir, testFile);
if (fs.existsSync(testPath)) {
try {
require(testPath);
} catch (error) {
console.error(`Error loading ${testFile}: ${error.message}`);
}
} else {
console.log(`Skipping ${testFile} (not found)`);
}
}
// Run all tests
global.runAllTests();
/**
* Simple test framework for Node.js (mocha-like)
* Provides describe/it/before/after/assert without external dependencies
*/
global.testStats = {
total: 0,
passed: 0,
failed: 0,
suites: [],
currentSuite: null
};
class TestSuite {
constructor(name) {
this.name = name;
this.tests = [];
this.beforeFn = null;
this.afterFn = null;
}
addTest(name, fn) {
this.tests.push({ name, fn });
}
setBefore(fn) {
this.beforeFn = fn;
}
setAfter(fn) {
this.afterFn = fn;
}
async run() {
const results = {
name: this.name,
passed: 0,
failed: 0,
errors: []
};
console.log(`\n ${this.name}`);
for (const test of this.tests) {
try {
if (this.beforeFn) await this.beforeFn();
await test.fn();
if (this.afterFn) await this.afterFn();
results.passed++;
process.stdout.write(' ✓ ' + test.name + '\n');
} catch (error) {
results.failed++;
results.errors.push({ test: test.name, error: error.message });
process.stdout.write(' ✗ ' + test.name + '\n');
console.log(' Error: ' + error.message);
}
}
return results;
}
}
global.testSuites = {};
global.describe = function(name, fn) {
const suite = new TestSuite(name);
global.testStats.currentSuite = suite;
global.testSuites[name] = suite;
fn();
};
global.it = function(name, fn) {
if (!global.testStats.currentSuite) {
throw new Error('it() called outside describe()');
}
global.testStats.currentSuite.addTest(name, fn);
};
global.before = function(fn) {
if (global.testStats.currentSuite) {
global.testStats.currentSuite.setBefore(fn);
}
};
global.after = function(fn) {
if (global.testStats.currentSuite) {
global.testStats.currentSuite.setAfter(fn);
}
};
// Simple assertion helper
global.assert = {
ok: (value, msg) => {
if (!value) throw new Error(msg || 'Assertion failed: expected truthy value');
},
equal: (a, b, msg) => {
if (a !== b) throw new Error(msg || `Expected ${JSON.stringify(a)} to equal ${JSON.stringify(b)}`);
},
deepEqual: (a, b, msg) => {
if (JSON.stringify(a) !== JSON.stringify(b)) {
throw new Error(msg || `Expected ${JSON.stringify(a)} to deep equal ${JSON.stringify(b)}`);
}
},
throws: async (fn, msg) => {
try {
await fn();
throw new Error(msg || 'Expected function to throw');
} catch (e) {
if (e.message === (msg || 'Expected function to throw')) throw e;
}
},
notEqual: (a, b, msg) => {
if (a === b) throw new Error(msg || `Expected ${JSON.stringify(a)} to not equal ${JSON.stringify(b)}`);
}
};
global.runAllTests = async function() {
console.log('\n' + '='.repeat(60));
console.log('Running Tests');
console.log('='.repeat(60));
const results = [];
for (const suite of Object.values(global.testSuites)) {
const result = await suite.run();
results.push(result);
global.testStats.passed += result.passed;
global.testStats.failed += result.failed;
global.testStats.total += result.passed + result.failed;
}
// Print summary
console.log('\n' + '='.repeat(60));
console.log('Results');
console.log('='.repeat(60) + '\n');
for (const result of results) {
const status = result.failed > 0 ? 'FAIL' : 'PASS';
console.log(`${status}: ${result.name} (${result.passed}/${result.passed + result.failed})`);
if (result.errors.length > 0) {
result.errors.forEach(err => {
console.log(` - ${err.test}: ${err.error}`);
});
}
}
console.log('\n' + '='.repeat(60));
console.log(`Total: ${global.testStats.total} | Passed: ${global.testStats.passed} | Failed: ${global.testStats.failed}`);
console.log('='.repeat(60) + '\n');
if (global.testStats.failed > 0) process.exit(1);
};
module.exports = { TestSuite, runAllTests };
Related skills
How it compares
Choose markdown-to-pdf for quick markdown exports; use dedicated static-site generators when the deliverable is a hosted doc site instead of PDF.
FAQ
What does markdown-to-pdf convert?
markdown-to-pdf converts markdown files into clean, professional PDFs suited for documentation, client proposals, and user guides, without requiring a separate desktop publishing workflow.
How popular is markdown-to-pdf on skills.sh?
markdown-to-pdf from duc01226/easyplatform reports 524 installs on skills.sh with rank 9223, indicating steady adoption for markdown-to-PDF documentation exports.