API Reference

This page is for WeasyPrint ‘stable’. See changelog for older versions.

API Stability

Everything described here is considered “public”: this is what you can rely on. We will try to maintain backward-compatibility, and we really often do, but there is no hard promise.

Anything else should not be used outside of WeasyPrint itself. We reserve the right to change it or remove it at any point. Use it at your own risk, or have dependency to a specific WeasyPrint version.

Versioning

WeasyPrint provides frequent major releases, and minor releases with only bug fixes. Versioning is close to what many browsers do, including Firefox and Chrome: big major numbers, small minor numbers.

Even if each version does not break the API, each version does break the way documents are rendered, which is what really matters at the end. Providing minor versions would give the illusion that developers can just update WeasyPrint without checking that everything works.

Unfortunately, we have the same problem as the other browsers: when a new version is released, most of the user’s websites are rendered exactly the same, but a small part is not. And the only ways to know that, for web developers, are to read the changelog and to check that their pages are correctly rendered.

More about this choice can be found in issue #900.

Command-line API

weasyprint.__main__.main(argv=sys.argv)

The weasyprint program takes at least two arguments:

weasyprint [options] <input> <output>
input

URL or filename of the HTML input, or - for stdin.

output

Filename where output is written, or - for stdout.

-e <encoding>, --encoding <encoding>

Force the input character encoding.

-s <stylesheet>, --stylesheet <stylesheet>

URL or filename for a user CSS stylesheet.

This option can be passed multiple times.

-m <media-type>, --media-type <media-type>

Media type to use for @media, defaults to print.

-u <base-url>, --base-url <base-url>

Base for relative URLs in the HTML input, defaults to the input’s own filename or URL or the current directory for stdin.

-a <attachment>, --attachment <attachment>

URL or filename of a file to attach to the PDF document.

This option can be passed multiple times.

--pdf-identifier <pdf-identifier>

PDF file identifier.

--pdf-variant <pdf-variant>

PDF variant to generate.

Possible choices: pdf/a-1b, pdf/a-2b, pdf/a-3b, pdf/a-4b, pdf/ua-1.

--pdf-version <pdf-version>

PDF version number.

--pdf-forms

Include PDF forms.

--uncompressed-pdf

Do not compress PDF content, mainly for debugging purpose.

--custom-metadata

Include custom HTML meta tags in PDF metadata.

-p, --presentational-hints

Follow HTML presentational hints.

--optimize-images

Optimize size of embedded images with no quality loss.

-j <jpeg-quality>, --jpeg-quality <jpeg-quality>

JPEG quality between 0 (worst) to 95 (best).

--full-fonts

Embed unmodified font files when possible.

--hinting

Keep hinting information in embedded fonts.

-c <cache-folder>, --cache-folder <cache-folder>

Store cache on disk instead of memory, folder is created if needed and cleaned after the PDF is generated.

-D <dpi>, --dpi <dpi>

Set maximum resolution of images embedded in the PDF.

-v, --verbose

Show warnings and information messages.

-d, --debug

Show debugging messages.

-q, --quiet

Hide logging messages.

--version

Print WeasyPrint’s version number and exit.

-i, --info

Print system information and exit.

-t <timeout>, --timeout <timeout>

Set timeout in seconds for HTTP requests.

-h, --help

Show this help message and exit.

Python API

class weasyprint.HTML(input, **kwargs)

HTML document parsed by html5lib.

You can just create an instance with a positional argument: doc = HTML(something) The class will try to guess if the input is a filename, an absolute URL, or a file object.

Alternatively, use one named argument so that no guessing is involved:

Parameters
  • filename (str or pathlib.Path) – A filename, relative to the current directory, or absolute.

  • url (str) – An absolute, fully qualified URL.

  • file_obj (file object) – Any object with a read method.

  • string (str) – A string of HTML source.

Specifying multiple inputs is an error: HTML(filename="foo.html", url="localhost://bar.html") will raise a TypeError.

You can also pass optional named arguments:

Parameters
  • encoding (str) – Force the source character encoding.

  • base_url (str or pathlib.Path) – The base used to resolve relative URLs (e.g. in <img src="../foo.png">). If not provided, try to use the input filename, URL, or name attribute of file objects.

  • url_fetcher (callable) – A function or other callable with the same signature as default_url_fetcher() called to fetch external resources such as stylesheets and images. (See URL Fetchers.)

  • media_type (str) – The media type to use for @media. Defaults to 'print'. Note: In some cases like HTML(string=foo) relative URLs will be invalid if base_url is not provided.

render(font_config=None, counter_style=None, **options)

Lay out and paginate the document, but do not (yet) export it.

This returns a document.Document object which provides access to individual pages and various meta-data. See write_pdf() to get a PDF directly.

Parameters
Returns

A document.Document object.

write_pdf(target=None, zoom=1, finisher=None, font_config=None, counter_style=None, **options)

Render the document to a PDF file.

This is a shortcut for calling render(), then Document.write_pdf().

Parameters
  • target (str, pathlib.Path or file object) – A filename where the PDF file is generated, a file object, or None.

  • zoom (float) – The zoom factor in PDF units per CSS units. Warning: All CSS units are affected, including physical units like cm and named sizes like A4. For values other than 1, the physical CSS units will thus be “wrong”.

  • finisher (callable) – A finisher function or callable that accepts the document and a pydyf.PDF object as parameters. Can be passed to perform post-processing on the PDF right before the trailer is written.

  • font_config (text.fonts.FontConfiguration) – A font configuration handling @font-face rules.

  • counter_style (css.counters.CounterStyle) – A dictionary storing @counter-style rules.

  • options – The options parameter includes by default the DEFAULT_OPTIONS values.

Returns

The PDF as bytes if target is not provided or None, otherwise None (the PDF is written to target).

class weasyprint.CSS(input, **kwargs)

CSS stylesheet parsed by tinycss2.

An instance is created in the same way as HTML, with the same arguments.

An additional argument called font_config must be provided to handle @font-face rules. The same text.fonts.FontConfiguration object must be used for different CSS objects applied to the same document.

CSS objects have no public attributes or methods. They are only meant to be used in the HTML.write_pdf() and HTML.render() methods of HTML objects.

class weasyprint.Attachment(input, **kwargs)

File attachment for a PDF document.

An instance is created in the same way as HTML, except that the HTML specific arguments (encoding and media_type) are not supported.

Parameters
  • description (str) – A description of the attachment to be included in the PDF document. May be None.

  • created (datetime.datetime) – Creation date and time. Default is current date and time.

  • modified (datetime.datetime) – Modification date and time. Default is current date and time.

  • relationship (str) – A string that represents the relationship between the attachment and the PDF it is embedded in. Default is ‘Unspecified’, other common values are defined in ISO-32000-2:2020, 7.11.3.

weasyprint.default_url_fetcher(url, timeout=10, ssl_context=None)

Fetch an external resource such as an image or stylesheet.

Another callable with the same signature can be given as the url_fetcher argument to HTML or CSS. (See URL Fetchers.)

Parameters
  • url (str) – The URL of the resource to fetch.

  • timeout (int) – The number of seconds before HTTP requests are dropped.

  • ssl_context (ssl.SSLContext) – An SSL context used for HTTP requests.

Raises

An exception indicating failure, e.g. ValueError on syntactically invalid URL.

Returns

A dict with the following keys:

  • One of string (a bytestring) or file_obj (a file object).

  • Optionally: mime_type, a MIME type extracted e.g. from a Content-Type header. If not provided, the type is guessed from the file extension in the URL.

  • Optionally: encoding, a character encoding extracted e.g. from a charset parameter in a Content-Type header

  • Optionally: redirected_url, the actual URL of the resource if there were e.g. HTTP redirects.

  • Optionally: filename, the filename of the resource. Usually derived from the filename parameter in a Content-Disposition header

If a file_obj key is given, it is the caller’s responsibility to call file_obj.close(). The default function used internally to fetch data in WeasyPrint tries to close the file object after retreiving; but if this URL fetcher is used elsewhere, the file object has to be closed manually.

weasyprint.DEFAULT_OPTIONS = {'attachments': None, 'cache': None, 'custom_metadata': False, 'dpi': None, 'full_fonts': False, 'hinting': False, 'jpeg_quality': None, 'media_type': 'print', 'optimize_images': False, 'pdf_forms': None, 'pdf_identifier': None, 'pdf_variant': None, 'pdf_version': None, 'presentational_hints': False, 'stylesheets': None, 'uncompressed_pdf': False}

Default values for command-line and Python API options. See __main__.main() to learn more about specific options for command-line.

Parameters
  • stylesheets (list) – An optional list of user stylesheets. The list can include are CSS objects, filenames, URLs, or file-like objects. (See Stylesheet Origins.)

  • media_type (str) – Media type to use for @media.

  • attachments (list) – A list of additional file attachments for the generated PDF document or None. The list’s elements are Attachment objects, filenames, URLs or file-like objects.

  • pdf_identifier (bytes) – A bytestring used as PDF file identifier.

  • pdf_variant (str) – A PDF variant name.

  • pdf_version (str) – A PDF version number.

  • pdf_forms (bool) – Whether PDF forms have to be included.

  • uncompressed_pdf (bool) – Whether PDF content should be compressed.

  • custom_metadata (bool) – Whether custom HTML metadata should be stored in the generated PDF.

  • presentational_hints (bool) – Whether HTML presentational hints are followed.

  • optimize_images (bool) – Whether size of embedded images should be optimized, with no quality loss.

  • jpeg_quality (int) – JPEG quality between 0 (worst) to 95 (best).

  • dpi (int) – Maximum resolution of images embedded in the PDF.

  • full_fonts (bool) – Whether unmodified font files should be embedded when possible.

  • hinting (bool) – Whether hinting information should be kept in embedded fonts.

  • cache (dict, pathlib.Path or str) – A dictionary used to cache images in memory, or a folder path where images are temporarily stored.

class weasyprint.document.Document(pages, metadata, url_fetcher, font_config)

A rendered document ready to be painted in a pydyf stream.

Typically obtained from HTML.render(), but can also be instantiated directly with a list of pages, a set of metadata, a url_fetcher function, and a font_config.

copy(pages='all')

Take a subset of the pages.

Parameters

pages (iterable) – An iterable of Page objects from pages.

Returns

A new Document object.

Examples:

Write two PDF files for odd-numbered and even-numbered pages:

# Python lists count from 0 but pages are numbered from 1.
# [::2] is a slice of even list indexes but odd-numbered pages.
document.copy(document.pages[::2]).write_pdf('odd_pages.pdf')
document.copy(document.pages[1::2]).write_pdf('even_pages.pdf')

Combine multiple documents into one PDF file, using metadata from the first:

all_pages = [p for doc in documents for p in doc.pages]
documents[0].copy(all_pages).write_pdf('combined.pdf')
fonts

A dict of fonts used by the document. Keys are hashes used to identify fonts, values are Font objects.

make_bookmark_tree(scale=1, transform_pages=False)

Make a tree of all bookmarks in the document.

Parameters
  • scale (float) – Zoom scale.

  • transform_pages (bool) – A boolean defining whether the default PDF page transformation matrix has to be applied to bookmark coordinates, setting the bottom-left corner as the origin.

Returns

A list of bookmark subtrees. A subtree is (label, target, children, state). label is a string, target is (page_number, x, y) and children is a list of child subtrees.

metadata

A DocumentMetadata object. Contains information that does not belong to a specific page but to the whole document.

pages

A list of Page objects.

url_fetcher

A function or other callable with the same signature as weasyprint.default_url_fetcher() called to fetch external resources such as stylesheets and images. (See URL Fetchers.)

write_pdf(target=None, zoom=1, finisher=None, **options)

Paint the pages in a PDF file, with metadata.

Parameters
  • target (str, pathlib.Path or file object) – A filename where the PDF file is generated, a file object, or None.

  • zoom (float) – The zoom factor in PDF units per CSS units. Warning: All CSS units are affected, including physical units like cm and named sizes like A4. For values other than 1, the physical CSS units will thus be “wrong”.

  • finisher (callable) – A finisher function or callable that accepts the document and a pydyf.PDF object as parameters. Can be passed to perform post-processing on the PDF right before the trailer is written.

  • options – The options parameter includes by default the weasyprint.DEFAULT_OPTIONS values.

Returns

The PDF as bytes if target is not provided or None, otherwise None (the PDF is written to target).

class weasyprint.document.DocumentMetadata

Meta-information belonging to a whole Document.

New attributes may be added in future versions of WeasyPrint.

attachments

A list of attachments, empty by default. Extracted from the <link rel=attachment> elements in HTML and written to the /EmbeddedFiles dictionary in PDF.

authors

The authors of the document, as a list of strings. (Defaults to the empty list.) Extracted from the <meta name=author> elements in HTML and written to the /Author info field in PDF.

created

The creation date of the document, as a string or None. Dates are in one of the six formats specified in W3C’s profile of ISO 8601. Extracted from the <meta name=dcterms.created> element in HTML and written to the /CreationDate info field in PDF.

custom

Custom metadata, as a dict whose keys are the metadata names and values are the metadata values.

description

The description of the document, as a string or None. Extracted from the <meta name=description> element in HTML and written to the /Subject info field in PDF.

generator

The name of one of the software packages used to generate the document, as a string or None. Extracted from the <meta name=generator> element in HTML and written to the /Creator info field in PDF.

keywords

Keywords associated with the document, as a list of strings. (Defaults to the empty list.) Extracted from <meta name=keywords> elements in HTML and written to the /Keywords info field in PDF.

lang

Document language as BCP 47 language tags. Extracted from <html lang=lang> in HTML.

modified

The modification date of the document, as a string or None. Dates are in one of the six formats specified in W3C’s profile of ISO 8601. Extracted from the <meta name=dcterms.modified> element in HTML and written to the /ModDate info field in PDF.

title

The title of the document, as a string or None. Extracted from the <title> element in HTML and written to the /Title info field in PDF.

class weasyprint.document.Page

Represents a single rendered page.

Should be obtained from Document.pages but not instantiated directly.

anchors

The dict mapping each anchor name to its target, an (x, y) point in CSS pixels from the top-left of the page.

bleed

The page bleed widths as a dict with 'top', 'right', 'bottom' and 'left' as keys, and values in CSS pixels.

bookmarks

The list of (level, label, target, state) tuples. level and label are respectively an int and a string, based on the CSS properties of the same names. target is an (x, y) point in CSS pixels from the top-left of the page.

height

The page height, including margins, in CSS pixels.

inputs

The list of (element, attributes, rectangle) tuples. A rectangle is (x, y, width, height), in CSS pixels from the top-left of the page. atributes is a dict of HTML tag attributes and values.

The list of (link_type, target, rectangle, box) tuples. A rectangle is (x, y, width, height), in CSS pixels from the top-left of the page. link_type is one of three strings:

  • 'external': target is an absolute URL

  • 'internal': target is an anchor name (see Page.anchors). The anchor might be defined in another page, in multiple pages (in which case the first occurence is used), or not at all.

  • 'attachment': target is an absolute URL and points to a resource to attach to the document.

paint(stream, scale=1)

Paint the page into the PDF file.

Parameters
  • stream (document.Stream) – A document stream.

  • left_x (float) – X coordinate of the left of the page, in PDF points.

  • top_y (float) – Y coordinate of the top of the page, in PDF points.

  • scale (float) – Zoom scale.

  • clip (bool) – Whether to clip/cut content outside the page. If false or not provided, content can overflow.

width

The page width, including margins, in CSS pixels.

class weasyprint.text.fonts.FontConfiguration

A FreeType font configuration.

Keep a list of fonts, including fonts installed on the system, fonts installed for the current user, and fonts referenced by cascading stylesheets.

When created, an instance of this class gathers available fonts. It can then be given to weasyprint.HTML methods or to weasyprint.CSS to find fonts in @font-face rules.

class weasyprint.css.counters.CounterStyle

Counter styles dictionary.

Keep a list of counter styles defined by @counter-style rules, indexed by their names.

See https://www.w3.org/TR/css-counter-styles-3/.

Supported Features

URLs

WeasyPrint can read normal files, HTTP, FTP and data URIs. It will follow HTTP redirects but more advanced features like cookies and authentication are currently not supported, although a custom URL fetcher can help.

HTML

Supported HTML Tags

Many HTML elements are implemented in CSS through the HTML5 User-Agent stylesheet.

Some elements need special treatment:

  • The <base> element, if present, determines the base for relative URLs.

  • CSS stylesheets can be embedded in <style> elements or linked by <link rel=stylesheet> elements.

  • <img>, <embed> or <object> elements accept images either in raster formats supported by Pillow (including PNG, JPEG, GIF, …) or in SVG. SVG images are not rasterized but rendered as vectors in the PDF output.

HTML presentational hints are not supported by default, but most of them can be supported:

  • by using the --presentational-hints CLI parameter, or

  • by setting the presentational_hints parameter of the HTML.render or HTML.write_* methods to True.

Presentational hints include a wide array of attributes that direct styling in HTML, including font color and size, list attributes like type and start, various table alignment attributes, and others. If the document generated by WeasyPrint is missing some of the features you expect from the HTML, try to enable this option.

Stylesheet Origins

HTML documents are rendered with stylesheets from three origins:

  • The HTML5 user agent stylesheet (defines the default appearance of HTML elements);

  • Author stylesheets embedded in the document in <style> elements or linked by <link rel=stylesheet> elements;

  • User stylesheets provided in the API.

Keep in mind that user stylesheets have a lower priority than author stylesheets in the cascade, unless you use !important in declarations to raise their priority.

PDF

In addition to text, raster and vector graphics, WeasyPrint’s PDF files can contain hyperlinks, bookmarks and attachments.

Hyperlinks will be clickable in PDF viewers that support them. They can be either internal, to another part of the same document (eg. <a href="#pdf">) or external, to an URL. External links are resolved to absolute URLs: <a href="/samples/"> on the WeasyPrint website would always point to https://weasyprint.org/samples/ in PDF files.

PDF bookmarks are also called outlines and are generally shown in a sidebar. Clicking on an entry scrolls the matching part of the document into view. By default all <h1> to <h6> titles generate bookmarks, but this can be controlled with PDF bookmarks.)

Attachments are related files, embedded in the PDF itself. They can be specified through <link rel=attachment> elements to add resources globally or through regular links with <a rel=attachment> to attach a resource that can be saved by clicking on said link. The title attribute can be used as description of the attachment.

The generation of PDF/A documents (A-1b, A-2b, A-3b and A-4b) is supported. However, the generated documents are not guaranteed to be valid, and users have the responsibility to check that they follow the rules listed by the related specifications. The major rules to follow are to include a PDF identifier, to check the PDF version, and to avoid anti-aliasing for images using image-rendering: crisp-edges.

The generation of PDF/UA documents (UA-1) is supported. However, the generated documents are not guaranteed to be valid, and users have the responsibility to check that they follow the rules listed by the related specifications. The main constraint is to use a correct HTML structure to avoid inconsistencies in the PDF structure.

Generated PDFs can include forms, using the appearance: auto CSS property or the --pdf-forms CLI option. Text inputs, text areas and check boxes are supported.

Fonts

WeasyPrint can use any font that Pango can find installed on the system. Fonts are automatically embedded in PDF files.

Pango always uses fontconfig to access fonts, even on Windows and macOS. You can list the available fonts thanks to the fc-list command, and know which font is matched by a given pattern thanks to fc-match. Copying a font file into the ~/.local/share/fonts directory is generally enough to install a new font. WeasyPrint should support the major font formats handled by Harfbuzz.

CSS

WeasyPrint supports many of the CSS specifications written by the W3C. You will find in this chapter a comprehensive list of the specifications or drafts with at least one feature implemented in WeasyPrint.

The results of some of the test suites provided by the W3C are also available at test.weasyprint.org. This website uses a tool called WeasySuite that can be useful if you want to implement new features in WeasyPrint.

CSS Level 2 Revision 1

The CSS Level 2 Revision 1 specification, best known as CSS 2.1, is pretty well supported by WeasyPrint. Since version 0.11, it passes the famous Acid2 Test.

The CSS 2.1 features listed here are not supported:

To the best of our knowledge, everything else that applies to the print media is supported. Please report a bug if you find this list incomplete.

Selectors Level 3 / 4

With the exceptions noted here, all Selectors Level 3 are supported.

PDF is generally not interactive. The :hover, :active, :focus, :target and :visited pseudo-classes are accepted as valid but never match anything.

Everything in Selectors Level 4 is supported, except:

  • :dir,

  • input pseudo-classes (:valid, :invalid…),

  • column selector (||, :nth-col(), :nth-last-col()).

CSS Text Module Level 3 / 4

The CSS Text Module Level 3 and CSS Text Module Level 4 are working drafts defining “properties for text manipulation” and covering “line breaking, justification and alignment, white space handling, and text transformation”.

Among their features, some are already included in CSS 2.1, sometimes with missing or different values (text-indent, text-align, letter-spacing, word-spacing, text-transform, white-space).

New properties defined in Level 3 are supported:

  • the overflow-wrap property replacing word-wrap;

  • the break-all value of the word-break property (see #1153);

  • the full-width value of the text-transform property; and

  • the start, end and justify-all values of the text-align property;

  • the text-align-last and text-justify properties; and

  • the tab-size property.

Properties controlling hyphenation are supported by WeasyPrint:

  • hyphens,

  • hyphenate-character,

  • hyphenate-limit-chars, and

  • hyphenate-limit-zone.

To get automatic hyphenation, you to set it to auto and have the lang HTML attribute set to one of the languages supported by Pyphen.

<!doctype html>
<html lang=en>
<style>
  html { hyphens: auto }
</style>

Automatic hyphenation can be disabled again with the manual value:

html { hyphens: auto }
a[href]::after { content: ' [' attr(href) ']'; hyphens: manual }

The other features provided by CSS Text Module Level 3 are not supported:

  • the line-break property;

  • the match-parent value of the text-align property;

  • the text-indent and hanging-punctuation properties.

The other features provided by CSS Text Module Level 4 are not supported:

  • the text-space-collapse and text-space-trim properties;

  • the text-wrap, wrap-before, wrap-after and wrap-inside properties;

  • the text-align property with an alignment character;

  • the pre-wrap-auto value of the white-space property; and

  • the text-spacing property.

CSS Fonts Module Level 3 / 4

The CSS Fonts Module Level 3 is a candidate recommendation describing “how font properties are specified and how font resources are loaded dynamically”.

WeasyPrint supports the font-size, font-stretch, font-style and font-weight properties, coming from CSS 2.1.

WeasyPrint also supports the following font features added in Level 3: - font-kerning, - font-variant-ligatures, - font-variant-position, - font-variant-caps, - font-variant-numeric, - font-variant-east-asian, - font-feature-settings, and - font-language-override.

font-family is supported. The string is given to Pango that tries to find a matching font in a way different from what is defined in the recommendation, but that should not be a problem for common use.

The shorthand font and font-variant properties are supported.

WeasyPrint supports the @font-face rule.

WeasyPrint does not support the @font-feature-values rule and the values of font-variant-alternates other than normal and historical-forms.

The font-variant-caps property is supported but needs the small-caps variant of the font to be installed. WeasyPrint does not simulate missing small-caps fonts.

From CSS Fonts Module Level 4 we only support the font-variation-settings property enabling specific font variations.

CSS Paged Media Module Level 3

The CSS Paged Media Module Level 3 is a working draft including features for paged media “describing how:

  • page breaks are created and avoided;

  • the page properties such as size, orientation, margins, border, and padding are specified;

  • headers and footers are established within the page margins;

  • content such as page counters are placed in the headers and footers; and

  • orphans and widows can be controlled.”

All the features of this draft are available, including:

  • the @page rule and the :left, :right, :first and :blank selectors;

  • the page margin boxes;

  • the page-based counters (with known limitations #93);

  • the page size, bleed and marks properties;

  • the named pages.

CSS Generated Content for Paged Media Module

The CSS Generated Content for Paged Media Module (GCPM) is a working draft defining “new properties and values, so that authors may bring new techniques (running headers and footers, footnotes, page selection) to paged media”.

Page selectors are supported by WeasyPrint. You can select pages according to their position in the document:

@page :nth(3) { background: red } /* Third page */
@page :nth(2n+1) { background: green } /* Odd pages */

You can also use running elements to put HTML boxes into the page margins (but the start parameter of element() is not supported).

Footnotes are supported. You can put a box in the footnote area using the float: footnote property. Footnote markers and footnote calls can be defined using the ::footnote-marker and ::footnote-call pseudo-elements. You can also change the way footnotes are displayed using the footnote-display property (compact is not supported), and influence over the rendering of difficult pages with footnote-policy.

Page groups (:nth(X of pagename) pseudo-class) are not supported.

CSS Generated Content Module Level 3

The CSS Generated Content Module Level 3 is a working draft helping “authors [who] sometimes want user agents to render content that does not come from the document tree. One familiar example of this is numbered headings […]. Similarly, authors may want the user agent to insert the word “Figure” before the caption of a figure […], or replacing elements with images or other multimedia content.”

Named strings are supported by WeasyPrint. You can define strings related to the first or last element of a type present on a page, and display these strings in page borders. This feature is really useful to add the title of the current chapter at the top of the pages of a book for example.

The named strings can embed static strings, counters, cross-references, tag contents and tag attributes.

@top-center { content: string(chapter) }
h2 { string-set: chapter "Current chapter: " content() }

Cross-references retrieve counter or content values from targets (anchors or identifiers) in the current document:

a::after { content: ", on page " target-counter(attr(href), page) }
a::after { content: ", see " target-text(attr(href)) }

In particular, target-counter() and target-text() are useful when it comes to tables of contents (see an example).

You can also control PDF bookmarks with WeasyPrint. Using the bookmark-level, bookmark-label and bookmark-state properties, you can add bookmarks that will be available in your PDF reader.

Bookmarks have already been added in the WeasyPrint’s user agent stylesheet, so your generated documents will automatically have bookmarks on headers (from <h1> to <h6>). But for example, if you have only one top-level <h1> and do not wish to include it in the bookmarks, add this in your stylesheet:

h1 { bookmark-level: none }

The other features of this module are not implemented:

  • quotes (content: *-quote);

  • leaders (content: leader()).

CSS Color Module Level 3

The CSS Color Module Level 3 is a recommendation defining “CSS properties which allow authors to specify the foreground color and opacity of an element”. Its main goal is to specify how colors are defined, including color keywords and the #rgb, #rrggbb, rgb(), rgba(), hsl(), hsla() syntaxes. Opacity and alpha compositing are also defined in this document.

This recommendation is fully implemented in WeasyPrint, except the deprecated System Colors.

CSS Transforms Module Level 1

The CSS Transforms Module Level 1 working draft “describes a coordinate system within each element is positioned. This coordinate space can be modified with the transform property. Using transform, elements can be translated, rotated and scaled in two or three dimensional space.”

WeasyPrint supports the transform and transform-origin properties, and all the 2D transformations (matrix, rotate, translate, translateX, translateY, scale, scaleX, scaleY, skew, skewX, skewY).

WeasyPrint does not support the transform-style, perspective, perspective-origin and backface-visibility properties, and all the 3D transformations (matrix3d, rotate3d, rotateX, rotateY, rotateZ, translate3d, translateZ, scale3d, scaleZ).

CSS Backgrounds and Borders Module Level 3

The CSS Backgrounds and Borders Module Level 3 is a candidate recommendation defining properties dealing “with the decoration of the border area and with the background of the content, padding and border areas”.

The border part of this module is supported, as it is already included in the the CSS 2.1 specification.

WeasyPrint supports the background part of this module (allowing multiple background layers per box), including the background, background-color, background-image, background-repeat, background-attachment, background-position, background-clip, background-origin and background-size properties.

WeasyPrint also supports the rounded corners part of this module, including the border-radius property.

WeasyPrint does not support the border images part of this module, including the border-image, border-image-source, border-image-slice, border-image-width, border-image-outset and border-image-repeat properties.

WeasyPrint does not support the box shadow part of this module, including the box-shadow property. This feature has been implemented in a git branch that is not released, as it relies on raster implementation of shadows.

CSS Image Values and Replaced Content Module Level 3 / 4

The Image Values and Replaced Content Module Level 3 is a candidate recommendation introducing “additional ways of representing 2D images, for example as a list of URIs denoting fallbacks, or as a gradient”, defining “several properties for manipulating raster images and for sizing or positioning replaced elements” and “generic sizing algorithm for replaced elements”.

The Image Values and Replaced Content Module Level 4 is a working draft on the same subject.

The linear-gradient(), radial-gradient() and repeating-radial-gradient() properties are supported as background images.

The the url() notation is supported, but the image() notation is not supported for background images.

The object-fit and object-position properties are supported.

The from-image and snap values of the image-resolution property are not supported, but the resolution value is supported.

The image-rendering and image-orientation properties are supported.

CSS Box Sizing Module Level 3

The CSS Box Sizing Module Level 3 is a candidate recommendation extending “the CSS sizing properties with keywords that represent content-based ‘intrinsic’ sizes and context-based ‘extrinsic’ sizes.”

The new property defined in this document is implemented in WeasyPrint: box-sizing.

The min-content, max-content and fit-content() sizing values are not supported.

CSS Overflow Module Level 3

The CSS Overflow Module Level 3 is a working draft containing “the features of CSS relating to scrollable overflow handling in visual media.”

The overflow property is supported, as defined in CSS2. overflow-x, overflow-y, overflow-clip-margin, overflow-inline and overflow-block are not supported.

The text-overflow, block-ellipsis, line-clamp, max-lines and continue properties are supported.

CSS Values and Units Module Level 3

The CSS Values and Units Module Level 3 defines various units and keywords used in “value definition field of each CSS property”.

The initial and inherit CSS-wide keywords are supported, but the unset keyword is not supported.

Quoted strings, URLs and numeric data types are supported.

Font-related lengths (em, ex, ch, rem), absolute lengths (cm, mm, q, in, pt, pc, px), angles (rad, grad, turn, deg), resolutions (dpi, dpcm, dppx) are supported.

The attr() functional notation is allowed in the content and string-set properties.

The calc() function is not supported.

Viewport-percentage lengths (vw, vh, vmin, vmax) are not supported.

CSS Multi-column Layout Module

The CSS Multi-column Layout Module “describes multi-column layouts in CSS, a style sheet language for the web. Using functionality described in the specification, content can be flowed into multiple columns with a gap and a rule between them.”

Simple multi-column layouts are supported in WeasyPrint. Features such as constrained height, spanning columns or column breaks are not supported. Pagination and overflow are not seriously tested.

The column-width and column-count properties, and the columns shorthand property are supported.

The column-gap, column-rule-color, column-rule-style and column-rule-width properties, and the column-rule shorthand property are supported.

The break-before, break-after and break-inside properties are supported.

The column-span property is supported for direct children of columns.

The column-fill property is supported, with a column balancing algorithm that should be efficient with simple cases.

CSS Fragmentation Module Level 3 / 4

The CSS Fragmentation Module Level 3 “describes the fragmentation model that partitions a flow into pages, columns, or regions. It builds on the Page model module and introduces and defines the fragmentation model. It adds functionality for pagination, breaking variable fragment size and orientation, widows and orphans.”

The CSS Fragmentation Module Level 4 is a working draft on the same subject.

The break-before, break-after and break-inside properties are supported for pages, but not for columns and regions. page-break-* aliases as defined in CSS2 are supported too.

The orphans and widows properties are supported.

The box-decoration-break property is supported, but backgrounds are always repeated and not extended through the whole box as it should be with ‘slice’ value.

The margin-break property is supported.

CSS Custom Properties for Cascading Variables Module Level 1

The CSS Custom Properties for Cascading Variables Module Level 1 “introduces cascading variables as a new primitive value type that is accepted by all CSS properties, and custom properties for defining them.”

The custom properties and the var() notation are supported.

CSS Text Decoration Module Level 3

The CSS Text Decoration Module Level 3 “contains the features of CSS relating to text decoration, such as underlines, text shadows, and emphasis marks.”

The text-decoration-line, text-decoration-style and text-decoration-color properties are supported, except from the wavy value of text-decoration-style. The text-decoration shorthand is also supported.

The other properties (text-underline-position, text-emphasis-*, text-shadow) are not supported.

CSS Flexible Box Layout Module Level 1

The CSS Flexible Box Layout Module Level 1 “describes a CSS box model optimized for user interface design”, also known as “flexbox”.

This module works for simple use cases but is not deeply tested.

All the flex-*, align-*, justify-* and order properties are supported. The flex and flex-flow shorthands are supported too.

CSS Basic User Interface Module Level 3/4

The CSS Basic User Interface Module Level 3/4 “enables authors to style user interface related properties and values.”

The outline-width, outline-style, outline-color properties and the outline shorthand are supported. The outline-offset property is not supported.

The resize, cursor, caret-* and nav-* properties are not supported.

The appearance property is supported. When set to auto, it displays form fields as PDF form fields (supported for text inputs, check boxes, text areas, and select only).

The accent-color property is not supported.