You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

weasyprint.ipynb 5.0KB


Weasyprint is a python library to layout HTML (and CSS) as print pages, saving to a PDF. In this way, it can be a part of a "web to print" workflow.

In [ ]:
from weasyprint import HTML, CSS
from weasyprint.fonts import FontConfiguration


The main class that weasyprint is HTML, it represents an HTML document, and provides functions to save as PDF (or PNG). When creating an HTML object you can specify the HTML either via HTML source as a string (via the string option), a file (via the filename option), or even an online page (via url).

In [ ]:
html = HTML(string='<h1>hello</h1>')


In [ ]:
html = HTML(filename="FILENAME.html")


In [ ]:
html = HTML(url="")


The CSS class lets you include an (additional) CSS file. Just as with the HTML class, you can give a string, filename, or URL. If the HTML already has stylesheets, they will be combined. (is this true?)

In [ ]:
css = CSS(string='''
        size: A4;
        margin: 15mm;
        background-color: lightgrey;
        font-family: monospace;
        font-size: 8pt;
        color: red;
        border:1px dotted red;
            content: "natural";
            content: "language";
            content: "artificial";
            content: ""
            content: "computer control";
            content: "markup";
            content: "formal";
            content: "programming";
            content: "machine";
        font-family: serif;
        font-size: 12pt;
        line-height: 1.4;
        color: magenta;
        width: 100%;
        text-align: center;
        font-size: 250%;
        line-height: 1.25;
        color: orange;
        color: blue;
        color: green;

In [ ]:
html.write_pdf('mydocument.pdf', stylesheets=[css])
In [ ]:
# Preview your PDF in the notebook!
from IPython.display import IFrame, display
IFrame("mydocument.pdf", width=900, height=600)
In [ ]:
In [ ]: