Code blocks in PDF: syntax highlighting without cut-off lines

Measured: overflow: auto silently clips long lines, overflow: visible shrinks the page. One print rule fixes both.

Updated · 3 min read

Documentation, tutorials and API references are full of code. On screen, a long line scrolls sideways. A PDF can’t scroll, so something has to give. We converted the same code block with a typical highlighter theme to see what.

Left: a syntax-highlighted code block whose last line stops mid-URL at the edge of the box. Right: the same block with the long line wrapped onto a second line.
Left: overflow: auto, as most highlighter themes set it; the end of the line is lost. Right: with the print rule below.

What happens to long lines

  • overflow: auto (the usual theme setting): the line is cut at the edge of the box. Text past the edge is missing from the PDF entirely, with no warning.
  • overflow: visible (the browser default): the line runs past the page edge, and the converter shrinks the whole page to fit the widest line, so every page’s text gets smaller.

The fix

@media print {
  pre {
    white-space: pre-wrap;      /* keep indentation, but wrap long lines */
    overflow-wrap: anywhere;    /* break long URLs and strings */
    overflow: visible;
  }
  pre, figure.code { break-inside: avoid; }  /* keep short blocks on one page */
}

Indentation and line breaks are kept; only lines too long for the page wrap. break-inside: avoid keeps short blocks together but still lets a block longer than a page continue onto the next.

Highlighting colours

Highlighters such as Prism, highlight.js and Shiki colour code with ordinary CSS, so those colours print. Background colours on the block print too, even with Print backgrounds off, because only the page background is affected by that setting; see background colours in PDF. Highlighters that run in the browser must finish before the PDF is made. Scripts that run while the page loads generally do, but highlighting that is delayed or triggered by scrolling may not, so highlighting on the server is the safest choice.

Readable code on paper

  • Use a monospace font that’s installed or embedded. The generic monospace family printed as DejaVu Sans Mono on the converter.
  • 9.5pt monospace fits about 90 characters across A4 portrait with 10 mm margins, a little less inside a padded box.
  • Dark themes use a lot of ink. Consider a light theme inside @media print.