### Setup WeasyPrint Development Environment Source: https://github.com/kozea/weasyprint/blob/main/docs/contribute.rst Commands to clone the repository, initialize a virtual environment, and install necessary dependencies for testing and documentation. ```shell git clone https://github.com/Kozea/WeasyPrint.git cd WeasyPrint python -m venv venv venv/bin/pip install -e '.[doc,test]' ``` -------------------------------- ### Install on Ubuntu Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Commands for installing WeasyPrint or its dependencies on Ubuntu. ```bash apt install weasyprint ``` ```bash apt install python3-pip libpango-1.0-0 libharfbuzz0b libpangoft2-1.0-0 libharfbuzz-subset0 ``` ```bash apt install python3-pip libpango-1.0-0 libharfbuzz0b libpangoft2-1.0-0 libharfbuzz-subset0 libffi-dev libjpeg-dev libopenjp2-7-dev ``` -------------------------------- ### Install on Debian Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Commands for installing WeasyPrint or its dependencies on Debian. ```bash apt install weasyprint ``` ```bash apt install python3-pip libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz-subset0 ``` ```bash apt install python3-pip libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz-subset0 libjpeg-dev libopenjp2-7-dev libffi-dev ``` -------------------------------- ### Install on Fedora Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Commands for installing WeasyPrint or its dependencies on Fedora. ```bash dnf install weasyprint ``` ```bash dnf install python-pip pango ``` ```bash dnf install python3-pip pango gcc python3-devel gcc-c++ zlib-devel libjpeg-devel openjpeg2-devel libffi-devel ``` -------------------------------- ### Install on Archlinux Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Commands for installing WeasyPrint or its dependencies on Archlinux. ```bash pacman -S python-weasyprint ``` ```bash pacman -S python-pip pango ``` ```bash pacman -S python-pip pango gcc libjpeg-turbo openjpeg2 ``` -------------------------------- ### Install via Virtual Environment Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Standard procedure for setting up a virtual environment and installing WeasyPrint via pip. ```bash python3 -m venv venv source venv/bin/activate pip install weasyprint weasyprint --info ``` -------------------------------- ### Install WeasyPrint on Windows with Pip Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Steps to install WeasyPrint using pip within a virtual environment on Windows. Ensure Python and MSYS2 with Pango are installed first. ```sh python -m venv venv venv\Scripts\activate.bat python -m pip install weasyprint python -m weasyprint --info ``` -------------------------------- ### Install on Alpine Linux Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Commands for installing WeasyPrint or its dependencies on Alpine Linux. ```bash apk add weasyprint ``` ```bash apk add py3-pip so:libgobject-2.0.so.0 so:libpango-1.0.so.0 so:libharfbuzz.so.0 so:libharfbuzz-subset.so.0 so:libfontconfig.so.1 so:libpangoft2-1.0.so.0 ``` ```bash apk add py3-pip so:libgobject-2.0.so.0 so:libpango-1.0.so.0 so:libharfbuzz.so.0 so:libharfbuzz-subset.so.0 so:libfontconfig.so.1 so:libpangoft2-1.0.so.0 apk add gcc musl-dev python3-dev zlib-dev jpeg-dev openjpeg-dev libwebp-dev g++ libffi-dev ``` -------------------------------- ### Install WeasyPrint with Homebrew Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Use this command to install WeasyPrint and its dependencies on macOS using Homebrew. ```sh brew install weasyprint ``` -------------------------------- ### Verify System Dependencies Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Check the installed versions of Python and Pango to ensure they meet the minimum requirements. ```bash python3 --version pango-view --version ``` -------------------------------- ### Factur-X RDF Metadata Example Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Example of RDF metadata for Factur-X/ZUGFeRD documents. This includes conformance level, document file name, type, and version. ```xml MINIMUM factur-x.xml INVOICE 1.0 Factur-X PDFA Extension Schema urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0# fx DocumentFileName Text external name of the embedded XML invoice file DocumentType Text external INVOICE Version Text external ``` -------------------------------- ### Install WeasyPrint Dependencies with Macports Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Install necessary dependencies for WeasyPrint on macOS using Macports. ```sh sudo port install py-pip pango libffi ``` -------------------------------- ### Factur-X XML Example Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst An example of the Factur-X XML structure, which is used for electronic invoicing. ```xml A1 urn:factur-x.eu:1p0:minimum 123 380 20200131 Buyer Supplyer Corp 123456782 FR FR11123456782 Buyer Corp 987654324 456 EUR 100.00 20.00 120.00 120.00 ``` -------------------------------- ### Set WEASYPRINT_DLL_DIRECTORIES on Windows Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Example of setting the WEASYPRINT_DLL_DIRECTORIES environment variable in cmd.exe to help WeasyPrint find DLL files. ```batch set WEASYPRINT_DLL_DIRECTORIES=C:\msys64\mingw64\bin ``` -------------------------------- ### Basic HTML Invoice Example Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst A simple HTML structure for an invoice, intended to be processed by WeasyPrint. ```html

Invoice

``` -------------------------------- ### Set DYLD_FALLBACK_LIBRARY_PATH on macOS Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Example of setting the DYLD_FALLBACK_LIBRARY_PATH environment variable in bash to help WeasyPrint find .dylib files. ```sh export DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib:$DYLD_FALLBACK_LIBRARY_PATH ``` -------------------------------- ### Manipulate Document Pages Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Examples for splitting documents into odd/even pages and printing the document outline. ```python # Write odd and even pages separately: # Lists count from 0 but page numbers usually 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') ``` ```python # Print the outline of the document. # Output on https://www.w3.org/TR/CSS21/intro.html # 1. Introduction to CSS 2.1 (page 2) # 1. A brief CSS 2.1 tutorial for HTML (page 2) # 2. A brief CSS 2.1 tutorial for XML (page 5) # 3. The CSS 2.1 processing model (page 6) # 1. The canvas (page 7) # 2. CSS 2.1 addressing model (page 7) # 4. CSS design principles (page 8) def print_outline(bookmarks, indent=0): for i, bookmark in enumerate(bookmarks, 1): page = bookmark.destination[0] print('%s%d. %s (page %d)' % ( ' ' * indent, i, bookmark.label.lstrip('0123456789. '), page)) print_outline(bookmark.children, indent + 2) print_outline(document.make_bookmark_tree()) ``` -------------------------------- ### Define HTML Document Structure Source: https://github.com/kozea/weasyprint/blob/main/tests/resources/doc1.html A basic HTML structure example containing a heading, a list with links, and Unicode character support for document rendering. ```html

WeasyPrint test document (with Ünicōde)

Hello

``` -------------------------------- ### Adjust Page Size and Margins with CSS Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Control document dimensions and margins using the CSS @page at-rule. This example sets the page size to A3 landscape and applies a 3cm margin to all pages. ```css @page { size: A3 landscape; /* Change from the default size and orientation of A4 portrait */ margin: 3cm; /* Set margin on each page */ } ``` -------------------------------- ### Instantiate HTML and CSS Objects Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Demonstrates various ways to initialize HTML and CSS objects using files, URLs, file objects, or raw strings. ```python from weasyprint import HTML HTML('../foo.html') # Same as … HTML(filename='../foo.html') HTML('https://weasyprint.org') # Same as … HTML(url='https://weasyprint.org') HTML(sys.stdin) # Same as … HTML(file_obj=sys.stdin) ``` ```python from weasyprint import HTML, CSS # HTML('

foo') would be filename HTML(string='''

The title

Content goes here ''') CSS(string='@page { size: A3; margin: 1cm }') ``` -------------------------------- ### Run WeasyPrint via CLI Source: https://github.com/kozea/weasyprint/blob/main/docs/contribute.rst Demonstrates how to invoke the WeasyPrint module to convert an HTML file into a PDF document. ```shell venv/bin/python -m weasyprint example.html example.pdf ``` -------------------------------- ### Build Project Documentation Source: https://github.com/kozea/weasyprint/blob/main/docs/contribute.rst Command to generate the project documentation using Sphinx, which outputs HTML files in the build directory. ```shell venv/bin/sphinx-build docs docs/_build ``` -------------------------------- ### Use WeasyPrint Command Line Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Basic usage of the WeasyPrint command-line interface to convert a URL to a PDF file. Warnings about unsupported CSS properties may appear on stderr. ```sh weasyprint https://weasyprint.org /tmp/weasyprint-website.pdf ``` -------------------------------- ### weasyprint.__main__.main Source: https://github.com/kozea/weasyprint/blob/main/docs/manpage.rst The main entry point function for the WeasyPrint command-line interface. ```APIDOC ## main(argv=sys.argv) ### Description Executes the WeasyPrint conversion process using the provided command-line arguments. ### Parameters #### Arguments - **argv** (list) - Optional - A list of command-line arguments, defaulting to sys.argv. ``` -------------------------------- ### Convert URL to PDF via CLI Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Use shell redirection to inject custom CSS during command-line conversion. ```sh weasyprint https://weasyprint.org /tmp/weasyprint-website.pdf \ -s <(echo 'body { font-family: serif !important }') ``` -------------------------------- ### Generate PDF/A-3 with Factur-X XML Attachment (CLI) Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Use the command-line interface to generate a PDF/A-3 document with an XML attachment, specifying the attachment relationship and XMP metadata. ```sh weasyprint invoice.html invoice.pdf --attachment=factur-x.xml --attachment-relationship=Data --xmp-metadata=rdf.xml --pdf-variant=pdf/a-3a ``` -------------------------------- ### Command-line API Source: https://github.com/kozea/weasyprint/blob/main/docs/api_reference.rst The command-line interface for WeasyPrint allows direct PDF generation from HTML files. ```APIDOC ## Command-line API ### Description Provides a command-line interface for generating PDFs from HTML and CSS files. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters - **argv** (list) - Required - Command-line arguments, typically `sys.argv`. ### Request Example ```bash weasyprint input.html output.pdf ``` ### Response N/A ``` -------------------------------- ### Implement Custom URL Fetcher for Specific Schemes Source: https://github.com/kozea/weasyprint/blob/main/docs/first_steps.rst Create a custom URL fetcher to handle specific URL schemes, such as 'graph:'. This allows for dynamic content generation based on URL parameters before passing it to WeasyPrint. ```python from weasyprint import HTML from weasyprint.urls import URLFetcher, URLFetcherResponse class MyFetcher(URLFetcher): def fetch(self, url, headers=None): if url.startswith('graph:'): graph_data = [float(value) for value in url[6:].split(',')] string = generate_graph(graph_data) # Assuming generate_graph is defined elsewhere return URLFetcherResponse(url, string, {'Content-Type': 'image/png'}) return super().fetch(url, headers) source = '' HTML(string=source, url_fetcher=MyFetcher()).write_pdf('out.pdf') ``` -------------------------------- ### Generate PDF/A-3 with Factur-X XML Attachment (Python API) Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Utilize the Python API to render an HTML file to PDF/A-3, programmatically adding an XML file as an attachment and setting XMP metadata. ```python from weasyprint import Attachment, HTML document = HTML("invoice.html").render() factur_x_xml = Path("factur-x.xml").read_text() attachment = Attachment(string=factur_x_xml, name="factur-x.xml", relationship="Data") document.metadata.attachments = [attachment] xmp_metadata = Path("rdf.xml").read_text().encode() document.metadata.xmp_metadata = [xmp_metadata] document.write_pdf("invoice.pdf", pdf_variant="pdf/a-3b") ``` -------------------------------- ### Enable PDF Forms via CSS Source: https://github.com/kozea/weasyprint/blob/main/docs/api_reference.rst Shows how to enable interactive PDF form generation using the appearance property in CSS. ```css input, textarea, select { appearance: auto; } ``` -------------------------------- ### Execute Project Tests and Linting Source: https://github.com/kozea/weasyprint/blob/main/docs/contribute.rst Commands to run the test suite using pytest and verify code style using the ruff linter. ```shell venv/bin/python -m pytest venv/bin/python -m ruff check ``` -------------------------------- ### Supported Features - Stylesheet Origins Source: https://github.com/kozea/weasyprint/blob/main/docs/api_reference.rst Explains the different origins of stylesheets that WeasyPrint considers when rendering documents. ```APIDOC ## Supported Features - Stylesheet Origins ### Description WeasyPrint applies stylesheets from three origins: the HTML5 user-agent stylesheet (default), author stylesheets (embedded or linked in HTML), and user stylesheets (provided via API). Author stylesheets have higher priority than user stylesheets unless `!important` is used. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example ```python from weasyprint import HTML, CSS html_content = """

Styled Heading

""" user_css = CSS(string='h1 { text-decoration: underline; }') h = HTML(string=html_content) h.write_pdf('styled.pdf', stylesheets=[user_css]) ``` ### Response N/A ``` -------------------------------- ### Create Fillable PDF Forms (Python API) Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Generate a PDF document with fillable form fields by setting the `pdf_forms` parameter to `True` in the `write_pdf` method. ```python from weasyprint import HTML HTML(string="").write_pdf("test.pdf", pdf_forms=True) ``` -------------------------------- ### Generate PDF/UA Variant with CLI Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Generate a PDF document conforming to the PDF/UA standard using the WeasyPrint command-line interface. PDF/UA ensures accessibility for users with disabilities. ```sh $ weasyprint document.html --pdf-variant="pdf/ua-1" document.pdf ``` -------------------------------- ### Define PDF Hyperlinks and Attachments in HTML Source: https://github.com/kozea/weasyprint/blob/main/docs/api_reference.rst Demonstrates how to create internal/external hyperlinks and embed file attachments within a document using standard HTML tags. ```html Jump to section Read our blog Download Report ``` -------------------------------- ### Attach Files to PDF via Python Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Use the 'Attachment' class from 'weasyprint' to create a list of attachments and pass it to the 'attachments' parameter when writing the PDF. ```python from weasyprint import Attachment, HTML attachments = [Attachment("note.txt"), Attachment("photo.jpg")] HTML(string="

PDF with attachments

").write_pdf("recipe.pdf", attachments=attachments) ``` -------------------------------- ### Supported Features - HTML Source: https://github.com/kozea/weasyprint/blob/main/docs/api_reference.rst Describes how WeasyPrint handles HTML elements, including special elements, images, and presentational hints. ```APIDOC ## Supported Features - HTML ### Description WeasyPrint supports a wide range of HTML elements, rendering them according to the HTML5 user-agent stylesheet. Special handling is provided for ``, ` ``` -------------------------------- ### CSS PDF Bookmarks Source: https://github.com/kozea/weasyprint/blob/main/docs/api_reference.rst Controls the generation of PDF bookmarks using properties like bookmark-level, bookmark-label, and bookmark-state. Bookmarks are automatically generated for headers by default. ```css h1 { bookmark-level: none } ``` -------------------------------- ### CSS Layout and Positioning Test Rules Source: https://github.com/kozea/weasyprint/blob/main/tests/resources/acid2-test.html A comprehensive set of CSS rules used to verify layout rendering, including fixed positioning, float behavior, and complex selector matching. These styles are designed to test the rendering engine's ability to handle CSS2.1 specifications like min/max height constraints and stacking orders. ```css html { font: 12px sans-serif; margin: 0; padding: 0; overflow: hidden; background: white; color: red; } .picture p { position: fixed; margin: 0; padding: 0; border: 0; top: 9em; left: 11em; width: 140%; max-width: 4em; height: 8px; min-height: 1em; max-height: 2mm; background: black; border-bottom: 0.5em yellow solid; } [class~=one].first.one { position: absolute; top: 0; margin: 36px 0 0 60px; padding: 0; border: black 2em; border-style: none solid; } .forehead { margin: 4em; width: 8em; border-left: solid black 1em; border-right: solid black 1em; background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4%2F58BAAT%2FAf9jgNErAAAAAElFTkSuQmCC); } ``` -------------------------------- ### Cache Images in Memory for Multiple PDF Renders Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Use a shared cache object to store images in memory when rendering multiple PDFs that might reuse the same images. This can significantly speed up the process by avoiding repeated image loading and processing. ```python cache = {} for i in range(10): HTML(f'https://weasyprint.org/').write_pdf( f'example-{i}.pdf', cache=cache) ``` -------------------------------- ### Python API - URLFetcher Source: https://github.com/kozea/weasyprint/blob/main/docs/api_reference.rst The URLFetcher class and its related components allow for custom handling of URL fetching during document processing. ```APIDOC ## URLFetcher ### Description Provides an interface for custom URL fetching logic, allowing advanced features like authentication or caching. ### Method Class Instantiation ### Endpoint N/A ### Parameters N/A (This is an abstract base class for custom implementations) ### Request Example ```python from weasyprint import HTML from weasyprint.urls import URLFetcher class MyFetcher(URLFetcher): def fetch(self, url): # Custom fetching logic here pass h = HTML(string='', url_fetcher=MyFetcher()) h.write_pdf('output.pdf') ``` ### Response #### Success Response (200) N/A (This is a class for custom implementation) #### Response Example N/A ``` -------------------------------- ### Define PDF Metadata in HTML Source: https://github.com/kozea/weasyprint/blob/main/docs/common_use_cases.rst Embed metadata like title, author, and creation date directly within HTML tags in the . WeasyPrint automatically normalizes and includes these in the PDF. ```html PDF Sample with Metadata ```