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

5.0 KiB

Weasyprint

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

HTML()

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>')

or

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

or

In [ ]:
html = HTML(url="https://pzwiki.wdka.nl/mediadesign/Category:WordsfortheFuture")

CSS()

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='''
@page{
        size: A4;
        margin: 15mm;
        background-color: lightgrey;
        font-family: monospace;
        font-size: 8pt;
        color: red;
        border:1px dotted red;
        
        @top-left{
            content: "natural";
        }
        @top-center{
            content: "language";
        }
        @top-right{
            content: "artificial";
        }
        @top-middle{
            content: ""
        }
        @left-top{
            content: "computer control";
        }
        @right-top{
            content: "markup";
        }
        @bottom-left{
            content: "formal";
        }
        @bottom-center{
            content: "programming";
        }
        @bottom-right{
            content: "machine";
        }
    }
    body{
        font-family: serif;
        font-size: 12pt;
        line-height: 1.4;
        color: magenta;
    }
    h1{
        width: 100%;
        text-align: center;
        font-size: 250%;
        line-height: 1.25;
        color: orange;
    }
    strong{
        color: blue;
    }
    em{
        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 [ ]: