
A code to PDF tool has only three jobs. It colors the code, it lays the code out on a paper-sized page, and it hands that page to something that can write a PDF. Python does the first two with one package called Pygments, and the browser you already have does the third through its print dialog. The file below is the whole tool at 238 lines. Run it and you get a page in your browser with a code box, a language list, font size, theme, margin and line number options, and a Generate PDF button. Your code never leaves your own computer, so you can use it for work files you would not paste into a website.
You Need Python and One Package Before You Start
- Python 3.9 or newer. Type
python --versionin a terminal to check. On Windows, get it from python.org and tick “Add Python to PATH” during setup. - Pygments. This is the library that knows the grammar of more than 500 languages and colors each word correctly.
Terminal (Windows, Mac or Linux)
pip install pygments
Nothing else is required. The web server inside the tool comes with Python itself.
Save This File As Code_to_pdf.py
Make a new folder, create a file named code_to_pdf.py in it and paste the code below. Use the Copy button so that no line is missed.
"""code_to_pdf.py - turn source code into a clean, highlighted PDF.
Two ways to use it:
1. As a web tool in your browser (paste or upload, pick options, press Generate PDF):
python code_to_pdf.py
then open http://127.0.0.1:8000
2. From the command line:
python code_to_pdf.py app.py -> app.py.html (open it, press Ctrl+P)
python code_to_pdf.py app.py --pdf -> app.py.pdf (needs: pip install playwright)
python code_to_pdf.py app.py --theme dark --font 11 --margin 1.5 --no-lines
Only one package is needed: pip install pygments
"""
import argparse
import html
import sys
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import TextLexer, get_lexer_by_name, guess_lexer, guess_lexer_for_filename
from pygments.util import ClassNotFound
MAX_CHARS = 50_000
THEMES = {"light": "default", "dark": "monokai"}
LANGUAGES = [
("auto", "Auto detect"), ("python", "Python"), ("javascript", "JavaScript"), ("typescript", "TypeScript"),
("html", "HTML"), ("css", "CSS"), ("php", "PHP"), ("java", "Java"), ("c", "C"), ("cpp", "C++"),
("csharp", "C#"), ("go", "Go"), ("rust", "Rust"), ("ruby", "Ruby"), ("kotlin", "Kotlin"), ("swift", "Swift"),
("sql", "SQL"), ("bash", "Bash"), ("powershell", "PowerShell"), ("json", "JSON"), ("yaml", "YAML"),
("xml", "XML"), ("markdown", "Markdown"), ("dart", "Dart"), ("text", "Plain text"),
]
def pick_lexer(code: str, language: str, filename: str = ""):
"""Use the chosen language; fall back to the file name, then to guessing, then to plain text."""
if language and language != "auto":
try:
return get_lexer_by_name(language)
except ClassNotFound:
pass
try:
return guess_lexer_for_filename(filename, code) if filename else guess_lexer(code)
except ClassNotFound:
return TextLexer()
def build_document(code: str, language="auto", filename="", theme="light",
font_px=12, margin_cm=2.0, line_numbers=True, auto_print=True) -> str:
"""Return one self-contained, print-ready HTML page for the code."""
code = code.replace("\r\n", "\n").expandtabs(4)
lexer = pick_lexer(code, language, filename)
formatter = HtmlFormatter(style=THEMES.get(theme, "default"), linespans="line", cssclass="code")
body = highlight(code, lexer, formatter)
title = html.escape(filename or f"{lexer.name} code")
numbered = "position: relative; padding-left: 3.6em;" if line_numbers else ""
hide_numbers = "" if line_numbers else "display: none;"
page_bg = "#272822" if theme == "dark" else "#ffffff"
ink = "#f8f8f2" if theme == "dark" else "#111111"
pad = "12px 14px" if theme == "dark" else "0"
return f"""<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><title>{title}</title>
<style>
@page {{ size: A4; margin: {margin_cm}cm; }}
* {{ -webkit-print-color-adjust: exact; print-color-adjust: exact; box-sizing: border-box; }}
html, body {{ margin: 0; background: {page_bg}; color: {ink}; }}
body {{ padding: {pad}; }}
header {{ font: 600 {font_px + 1}px/1.4 system-ui, sans-serif; padding: 0 0 8px; margin: 0 0 10px;
border-bottom: 1px solid #9995; display: flex; justify-content: space-between; gap: 12px; }}
header span {{ font-weight: 400; opacity: .7; }}
.code pre {{ margin: 0; font: {font_px}px/1.5 "JetBrains Mono", "Cascadia Code", Consolas, Menlo, monospace;
white-space: pre-wrap; overflow-wrap: anywhere; tab-size: 4; }}
.code pre {{ counter-reset: line; padding: 8px 10px; }}
.code pre > span[id] {{ display: block; {numbered} }}
.code pre > span[id]::before {{ counter-increment: line; content: counter(line); position: absolute; left: 0; width: 2.6em;
text-align: right; color: #8a8a8a; {hide_numbers} }}
@media screen {{ body {{ max-width: 21cm; margin: 0 auto; padding: {margin_cm}cm; }} }}
{formatter.get_style_defs(".code")}
</style></head><body>
<header><div>{title}</div><span>{lexer.name} · {len(code.splitlines())} lines</span></header>
{body}
{"<script>window.addEventListener('load', () => window.print());</script>" if auto_print else ""}
</body></html>"""
def tool_page() -> str:
options = "".join(f'<option value="{v}">{html.escape(n)}</option>' for v, n in LANGUAGES)
return f"""<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Code to PDF</title>
<style>
:root {{ --bg:#f3f1ec; --card:#fff; --ink:#15201c; --muted:#5f6b66; --line:#d9ddd9; --go:#0b6b4f; }}
* {{ box-sizing: border-box; }}
body {{ margin:0; background:var(--bg); color:var(--ink); font:16px/1.5 system-ui,sans-serif; }}
main {{ max-width:1080px; margin:0 auto; padding:28px 16px 48px; }}
h1 {{ font-size:clamp(1.5rem,4vw,2.1rem); margin:0 0 4px; text-align:center; }}
.sub {{ text-align:center; color:var(--muted); margin:0 0 22px; }}
.grid {{ display:grid; grid-template-columns:minmax(0,1.25fr) minmax(0,1fr); gap:18px; }}
@media (max-width:760px) {{ .grid {{ grid-template-columns:1fr; }} }}
.card {{ background:var(--card); border:1px solid var(--line); border-radius:14px; padding:16px; }}
textarea {{ width:100%; height:340px; border:1px solid var(--line); border-radius:10px; padding:12px; resize:vertical;
font:13px/1.5 Consolas,Menlo,monospace; tab-size:4; }}
.under {{ display:flex; justify-content:space-between; align-items:center; gap:10px; margin-top:8px; flex-wrap:wrap;
color:var(--muted); font-size:.9rem; }}
label.row {{ display:flex; justify-content:space-between; align-items:center; gap:12px; padding:9px 0;
border-bottom:1px solid var(--line); }}
label.row:last-child {{ border-bottom:0; }}
select, input[type=text] {{ font:inherit; padding:6px 10px; border:1px solid var(--line); border-radius:8px; background:#fff; max-width:60%; }}
.note {{ text-align:center; color:var(--muted); margin:18px 0 10px; font-size:.95rem; }}
.actions {{ display:flex; gap:12px; justify-content:center; flex-wrap:wrap; }}
button {{ font:600 1rem system-ui; padding:12px 26px; border-radius:10px; border:1px solid var(--line); background:#fff; cursor:pointer; }}
button.go {{ background:var(--go); color:#fff; border-color:var(--go); min-width:260px; }}
button:focus-visible, select:focus-visible, textarea:focus-visible {{ outline:3px solid #0b6b4f55; outline-offset:2px; }}
</style></head><body><main>
<h1>Code to PDF</h1>
<p class="sub">Paste code, pick how it should look, save it as a PDF. Nothing leaves this computer.</p>
<form method="post" action="/render" target="_blank" id="f">
<div class="grid">
<div class="card">
<textarea name="code" id="code" maxlength="{MAX_CHARS}" placeholder="Paste your code here..." required></textarea>
<div class="under"><span id="count">0 / {MAX_CHARS:,}</span>
<span>Have a file? <input type="file" id="file"></span></div>
</div>
<div class="card">
<label class="row">Language <select name="language" id="language">{options}</select></label>
<label class="row">File name on the page <input type="text" name="filename" id="filename" placeholder="optional"></label>
<label class="row">Font size <select name="font">
<option>9</option><option>10</option><option>11</option><option selected>12</option><option>14</option><option>16</option></select></label>
<label class="row">Theme <select name="theme"><option value="light">Light</option><option value="dark">Dark</option></select></label>
<label class="row">Page margin <select name="margin">
<option value="1">Narrow (1cm)</option><option value="2" selected>Default (2cm)</option><option value="3">Wide (3cm)</option></select></label>
<label class="row">Show line numbers <input type="checkbox" name="lines" value="1" checked></label>
</div>
</div>
<p class="note">Your browser's print dialog will open. Choose "Save as PDF" as the destination.</p>
<div class="actions"><button type="button" id="clear">Clear</button><button class="go">Generate PDF</button></div>
</form></main>
<script>
const code = document.getElementById('code'), count = document.getElementById('count');
const tick = () => count.textContent = code.value.length.toLocaleString() + ' / {MAX_CHARS:,}';
code.addEventListener('input', tick);
document.getElementById('clear').addEventListener('click', () => {{ document.getElementById('f').reset(); tick(); }});
document.getElementById('file').addEventListener('change', async (e) => {{
const file = e.target.files[0]; if (!file) return;
code.value = (await file.text()).slice(0, {MAX_CHARS}); tick();
document.getElementById('filename').value = file.name;
document.getElementById('language').value = 'auto';
}});
code.addEventListener('keydown', (e) => {{ // Tab types a tab instead of leaving the box
if (e.key !== 'Tab') return; e.preventDefault();
const s = code.selectionStart; code.setRangeText(' ', s, code.selectionEnd, 'end'); tick();
}});
</script></body></html>"""
class Handler(BaseHTTPRequestHandler):
def send_page(self, status: int, page: str):
data = page.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
self.send_page(200, tool_page()) if self.path == "/" else self.send_page(404, "Not found")
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
if self.path != "/render" or length > MAX_CHARS * 12: # url-encoding can triple the size
return self.send_page(413, "Too large. The limit is 50,000 characters.")
form = {k: v[0] for k, v in parse_qs(self.rfile.read(length).decode("utf-8"), keep_blank_values=True).items()}
code = form.get("code", "")
if not code.strip() or len(code) > MAX_CHARS:
return self.send_page(400, "Paste some code first (50,000 characters at most).")
font = min(max(int(form.get("font", 12) or 12), 8), 18)
margin = min(max(float(form.get("margin", 2) or 2), 0.5), 4)
self.send_page(200, build_document(code, form.get("language", "auto"), form.get("filename", "").strip()[:80],
form.get("theme", "light"), font, margin, form.get("lines") == "1"))
def log_message(self, *args): # keep the terminal quiet
pass
def html_to_pdf(html_path: Path, pdf_path: Path):
"""Optional: straight to PDF with headless Chromium. pip install playwright && playwright install chromium"""
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto(html_path.resolve().as_uri())
page.pdf(path=str(pdf_path), prefer_css_page_size=True, print_background=True)
browser.close()
def main():
ap = argparse.ArgumentParser(description="Turn source code into a highlighted PDF.")
ap.add_argument("file", nargs="?", help="source file to convert; leave out to start the web tool")
ap.add_argument("--language", default="auto")
ap.add_argument("--theme", default="light", choices=list(THEMES))
ap.add_argument("--font", type=int, default=12, help="font size in px")
ap.add_argument("--margin", type=float, default=2.0, help="page margin in cm")
ap.add_argument("--no-lines", action="store_true", help="hide line numbers")
ap.add_argument("--pdf", action="store_true", help="write a .pdf directly (needs playwright)")
ap.add_argument("--port", type=int, default=8000)
a = ap.parse_args()
if not a.file: # web tool
url = f"http://127.0.0.1:{a.port}"
print(f"Code to PDF is running at {url} (Ctrl+C to stop)")
webbrowser.open(url)
try:
ThreadingHTTPServer(("127.0.0.1", a.port), Handler).serve_forever()
except KeyboardInterrupt:
print("\nStopped.")
return
src = Path(a.file)
code = src.read_text(encoding="utf-8", errors="replace")
out_html = src.with_name(src.name + ".html")
out_html.write_text(build_document(code, a.language, src.name, a.theme, a.font, a.margin,
not a.no_lines, auto_print=not a.pdf), encoding="utf-8")
if a.pdf:
out_pdf = src.with_name(src.name + ".pdf")
html_to_pdf(out_html, out_pdf)
out_html.unlink()
print(f"Wrote {out_pdf}")
else:
print(f"Wrote {out_html} -> open it and press Ctrl+P, then Save as PDF")
if __name__ == "__main__":
sys.exit(main())
Start the Tool and Make Your First PDF in Six Steps
python code_to_pdf.py
What you should see
Code to PDF is running at http://127.0.0.1:8000 (Ctrl+C to stop)
- Your browser opens
http://127.0.0.1:8000by itself. If it does not, type that address in. - Paste your code into the box, or press Choose File to load a file from your computer. The counter shows how much of the 50,000 character limit you have used.
- Pick the language, or leave it on Auto detect. A loaded file sets its own name and the tool reads the language from it.
- Set the font size, theme, page margin and line numbers.
- Press Generate PDF. A new tab opens with the finished page and the print dialog appears on top of it.
- Choose Save as PDF as the destination (on a Mac, the PDF button at the bottom left) and save.

- Clear empties the box and puts every option back to its default.
- The Tab key types four spaces inside the box, so you can fix indentation before printing.
- For the dark theme in Firefox, tick Print backgrounds in the print dialog. Chrome and Edge keep the dark background on their own.

The Same File Also Works From the Command Line
When you have a folder of files to print, the browser page is slower than a command. Give the script a file name and it skips the web tool.
python code_to_pdf.py app.py python code_to_pdf.py app.py --theme dark --font 11 --margin 1.5 --no-lines python code_to_pdf.py app.py --pdf
What you should see
Wrote app.py.html -> open it and press Ctrl+P, then Save as PDF
Wrote app.py.html -> open it and press Ctrl+P, then Save as PDF
Wrote app.py.pdf
- Without
--pdfit writes a print-ready HTML file next to your source file. Open it and press Ctrl+P. - With
--pdfit writes the PDF directly with a hidden copy of Chromium. That mode needs two more commands once:
pip install playwright playwright install chromium
How the Tool Works, Part by Part
Pygments Reads the Code and Colors It
A lexer is the part of Pygments that understands one language. The tool takes your choice from the list first. If you left it on Auto detect, it tries the file name, then guesses from the code, and falls back to plain text so the tool never crashes on a file it does not know.
def pick_lexer(code, language, filename=""):
if language and language != "auto":
try:
return get_lexer_by_name(language)
except ClassNotFound:
pass
try:
return guess_lexer_for_filename(filename, code) if filename else guess_lexer(code)
except ClassNotFound:
return TextLexer()
The formatter then turns the colored tokens into HTML. The option linespans="line" wraps each line of code in its own tag, and the line numbers are built on that.
Print CSS Turns a Web Page Into a Paper Page
@page { size: A4; margin: 2cm; }
* { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
.code pre { white-space: pre-wrap; overflow-wrap: anywhere; counter-reset: line; }
.code pre > span[id] { display: block; position: relative; padding-left: 3.6em; }
.code pre > span[id]::before { counter-increment: line; content: counter(line);
position: absolute; left: 0; width: 2.6em; text-align: right; }
@pagesets the paper to A4 and applies the margin you picked.print-color-adjust: exacttells the browser to keep the colors and the dark background, which printers drop by default.pre-wrapwithoverflow-wrap: anywherewraps a long line onto the next row. Without it, anything past the right margin is cut off in the PDF.- The CSS counter draws the line numbers. They are not part of the text, so a wrapped line keeps one number and its second row lines up under the code, as line 17 does in the first image.
The Browser Writes the PDF
The generated page ends with one line of JavaScript that opens the print dialog as soon as the page has loaded. Every modern browser has Save as PDF built into that dialog, which is why the tool needs no PDF library at all.
window.addEventListener('load', () => window.print());
A Small Server Joins the Parts Together
Python’s own http.server answers two addresses. A visit to / returns the tool page. A press of Generate PDF sends the form to /render, which checks the size, builds the document and sends it back. The server listens on 127.0.0.1 only, so other machines on your network cannot reach it.
What Was Tested Before This Was Published
The tool was run on Python 3.13 with Pygments 2.21. A headless Chromium pasted a 25-line file into the page, pressed the button, saved the PDF and then pressed Clear. Empty input and input over the limit were sent on purpose.
counter: 777 / 50,000 render title: inventory.py | header: inventory.py Python · 25 lines after clear: '' 0 / 50,000 empty -> 400 | 60k chars -> 400 Pages: 1 Page size: 594.96 x 841.92 pts (A4)
- The file name box was also sent a
<script>tag. It came back escaped as text, so a pasted name cannot run code on the page. - The Windows and Mac steps follow the standard Python setup and were not run on those systems for this article.
Fix These Four Things If Something Goes Wrong
ModuleNotFoundError: No module named 'pygments': runpython -m pip install pygmentsso the package goes into the Python you are running.OSError: [Errno 98] Address already in use(10048 on Windows): another program holds port 8000. Start withpython code_to_pdf.py --port 8080.- The new tab did not open: the browser blocked the pop-up. Allow pop-ups for 127.0.0.1 and press the button again.
- Colors are missing in the PDF: in the print dialog open More settings and tick Background graphics.
Put It Online Only After Adding a Real Server in Front
The built-in server is made for one person on one computer. If you want the tool on a public website, keep build_document() as it is and call it from a Flask or FastAPI route behind Nginx with a request size limit. The highlighting and the print CSS do not change. Only the part that receives the form does.
