keyboard-shortcut
d

HTML to PDF

2min read

an image

Why?

HTML and CSS allow you to build a myriad of things! It's not always easy (centering a div), but you can pretty much build whatever you want! Consequently, it's quite a hand tool when creating PDF docs. If it looks good in your browser, it'll probably make for a good PDF.

How?

weasyprint is a brilliant tool that works out of the box. It is a simple, point and shoot way to create PDF files!

uvx weasyprint index.html my_shareable_file.pdf

Page breaks and styling

You can use native HTML syntax and tooling to configure your page setup:

@page {
    size: A4;
    margin: 9mm 14mm 7mm 14mm;
}

If you have a gorgeous HTML file, inconvenient page breaks are the only thing that can reaaaally spoil your PDF file. You can configure the page break policy for specific sections in your CSS to prevent things like lists being split across pages or lonely sections on a page.

  • break-after
  • break-inside

  • avoid

  • auto
  • always

There are other settings (see here) but I haven't found much use for them.

Example usage:

header {
    break-after: avoid;
}

ul,
li,
p {
    break-inside: avoid;
}

table {
    break-inside: avoid;
}

Examples

The weasyprint website links to some amazing examples: https://github.com/CourtBouillon/weasyprint-samples/. If you need a stylish PDF, I'd suggest giving it a go!