Usage Guide
This section covers the core concepts of using PlutoPrint programmatically.
The Book Object
The Book is the central object in PlutoPrint. It represents a document that can be loaded with content, styled, and rendered.
import plutoprint
# Initialize with defaults (A4, Normal Margins, Print Media)
book = plutoprint.Book()
# Initialize with custom settings
book = plutoprint.Book(
size=plutoprint.PAGE_SIZE_LETTER.landscape(),
margins=plutoprint.PAGE_MARGINS_NARROW,
media=plutoprint.MEDIA_TYPE_PRINT
)
Loading Content
You can load content into a Book from various sources. All loading methods accept optional user_style (CSS) and user_script (JS) arguments.
From HTML String
html = "<h1>Title</h1><p>Content...</p>"
css = "h1 { color: red; }"
book.load_html(html, user_style=css)
From a URL or File Path
# Load a local file
book.load_url("file:///absolute/path/to/invoice.html")
# Load a remote URL (requires internet access)
book.load_url("https://example.com")
From XML
PlutoPrint also supports XML rendering if you have associated stylesheets.
book.load_xml("<root><item>Value</item></root>")
Exporting Documents
Writing to PDF
You can write the entire document or a specific range of pages.
# Write all pages
book.write_to_pdf("output.pdf")
# Write specific page range (e.g., pages 2 to 5)
book.write_to_pdf("range.pdf", page_start=2, page_end=5)
# Write to a Python file-like object (stream)
import io
buffer = io.BytesIO()
book.write_to_pdf_stream(buffer)
# buffer now contains the PDF binary data
Writing to PNG
PNG export is useful for single-page views or converting web components to images.
# Auto-size based on content
book.write_to_png("output.png")
# Force specific dimensions (content may stretch)
book.write_to_png("thumbnail.png", width=300, height=300)
Metadata
You can attach standard PDF metadata to your document before writing it.
book.set_metadata(plutoprint.PDF_METADATA_TITLE, "Annual Report")
book.set_metadata(plutoprint.PDF_METADATA_AUTHOR, "Jane Doe")
book.set_metadata(plutoprint.PDF_METADATA_CREATOR, "PlutoPrint System")
Manual Rendering (Canvas)
For maximum control, you can render pages onto a Canvas manually. This allows you to perform affine transformations (scale, rotate, translate) before the content is drawn.
# Create a PDF Canvas manually
with plutoprint.PDFCanvas("manual.pdf", book.get_page_size()) as canvas:
# Scale everything down by 50%
canvas.scale(0.5, 0.5)
# Render page 0
book.render_page(canvas, 0)
# Finalize the page
canvas.show_page()