Code to PDF

Upload or paste source code, optionally add line numbers, then export it as a PDF.

Back to all tools on ToolForge

More in PDF & Export

Upload Code File

You can upload a code file or paste code below.

Title:

About Code to PDF

This Code to PDF tool exports source code into a clean, readable PDF using a monospace layout. It is useful for reviews, documentation, snippets, printed handouts and offline sharing.

The conversion runs in your browser and supports both file upload and manual paste input.

jsPDF Text Rendering Basics

jsPDF uses a coordinate system measured in points (1 point = 1/72 inch):

Code PDF Generation Implementation

const pdf = new jsPDF("p", "pt", "a4");
const margin = 36;
const pageHeight = pdf.internal.pageSize.getHeight();
let y = margin;

// Title in bold Helvetica
pdf.setFont("helvetica", "bold");
pdf.setFontSize(14);
pdf.text(title, margin, y);
y += 22;

// Code in monospace Courier
pdf.setFont("courier", "normal");
pdf.setFontSize(9);

lines.forEach((line, index) => {
  const content = showLineNumbers
    ? String(index + 1).padStart(4, " ") + "  " + line
    : line;
  const wrapped = pdf.splitTextToSize(content, usableWidth);

  wrapped.forEach(segment => {
    if (y > pageHeight - margin) {
      pdf.addPage();
      pdf.setFont("courier", "normal");
      pdf.setFontSize(9);
      y = margin;
    }
    pdf.text(segment, margin, y);
    y += 12; // Line height
  });
});

pdf.save("code.pdf");

Supported File Extensions

LanguageExtensionsLanguageExtensions
JavaScript.js, .mjs, .cjsPython.py, .pyw
TypeScript.ts, .tsxJava.java
React JSX.jsxC/C++.c, .cpp, .h, .hpp
Go.goC#.cs
Rust.rsPHP.php
Ruby.rbSwift.swift
CSS/SCSS.css, .scss, .sassKotlin.kt
HTML/XML.html, .xml, .xhtmlShell.sh, .bash, .zsh
JSON/YAML.json, .yaml, .ymlMarkdown.md
SQL.sqlPlain text.txt

Line Number Formatting

// Add line numbers with padding
const lineNumber = String(index + 1).padStart(4, " ");
const prefixedLine = lineNumber + "  " + codeLine;

// Output:
//    1  function hello() {
//    2    console.log("Hello");
//    3  }

// Benefits:
// - Easy reference during code reviews
// - Helps locate specific lines in printed docs
// - Aligns with IDE line numbering conventions

PDF Font Options for Code

FontTypeAvailabilityBest For
CourierMonospaceBuilt-inStandard code formatting
Courier BoldMonospaceBuilt-inEmphasized code sections
HelveticaSans-serifBuilt-inTitles and headings
Times RomanSerifBuilt-inDocument body text
SymbolSymbolBuilt-inMathematical symbols
ZapfDingbatsDecorativeBuilt-inSpecial characters

Code PDF Best Practices

Frequently Asked Questions

Why use monospace fonts for code in PDFs?
Monospace fonts (Courier, Consolas, Monaco) ensure each character has equal width, preserving code alignment and indentation structure. This is critical for languages like Python where indentation is syntactically significant, and for reading nested code blocks, aligned columns, and ASCII art. Proportional fonts break visual code structure.
How does jsPDF handle text rendering and page breaks?
jsPDF uses a coordinate system (points at 72 DPI) with text positioned at baseline. The splitTextToSize() function wraps text to fit width. Manual page break detection checks if y-position exceeds page height minus margin, then addPage() creates a new page. Font settings must be reapplied after each page break.
What are best practices for formatting code in PDFs?
Use 9-11pt monospace font, 12-14pt line height, 36pt margins, and include line numbers for reference. Add a title header with bold Helvetica. Preserve original indentation (2-4 spaces). For long lines, enable text wrapping or use landscape orientation. Keep lines under 100 characters when possible.
How do you add syntax highlighting to code PDFs?
jsPDF supports basic text coloring with setTextColor(). Tokenize code into keywords, strings, comments, and identifiers. Apply colors before rendering each token (e.g., blue for keywords, green for strings, red for comments). This requires manual text positioning since colored text resets after each .text() call.
What PDF page orientation works best for code?
Portrait (A4: 595x842pt) suits most code with lines under 80-100 characters. Landscape (A4: 842x595pt) accommodates wider lines up to 120-140 characters. Consider portrait for documentation readability, landscape for wide data structures or when printing on standard paper without rotation.
How do you handle special characters and Unicode in code PDFs?
Standard jsPDF fonts support basic ASCII and Latin-1 characters. For Unicode (emojis, CJK, special symbols), load custom TTF fonts using addFileToVFS() and addFont(). Encode text as UTF-8. Built-in Courier font handles most programming characters but not full Unicode. Test with target characters before distribution.