Document Creation¶
The SmithDocument class is the central API for papersmith. It wraps python-docx and provides a high-level, fluent interface for building professional Word documents.
Creating a Document¶
from papersmith import SmithDocument
# With a named preset
doc = SmithDocument(preset="academic")
# With a custom preset dictionary
doc = SmithDocument(preset={
"name": "custom",
"font": "Arial",
"font_size": 11,
"line_spacing": 1.15,
"margins": {"top": 2.0, "bottom": 2.0, "left": 2.5, "right": 2.5},
})
Adding Content¶
Headings¶
doc.add_heading("Chapter 1: Introduction", level=1)
doc.add_heading("1.1 Background", level=2)
doc.add_heading("1.1.1 Historical Context", level=3)
Heading levels range from 1 to 6, matching HTML heading semantics.
Text¶
# Plain text
doc.add_text("This is a paragraph of text.")
# Formatted text
doc.add_text("This is bold.", bold=True)
doc.add_text("This is italic.", italic=True)
doc.add_text("This is underlined.", underline=True)
# Text with inline LaTeX
doc.add_text("The quadratic formula is $x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$.")
Images¶
# From a file path
doc.add_image("chart.png", width=12.0, caption="Figure 1: Sales Data")
# From bytes
doc.add_image(image_bytes, width=10.0, caption="Generated chart")
Code Blocks¶
doc.add_code(
"""def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)""",
language="python",
)
Page Breaks and Separators¶
Cover Pages¶
doc.add_cover_page(
title="Annual Financial Report",
subtitle="Fiscal Year 2026",
author="Finance Department",
institution="Acme Corporation",
date="June 2026",
)
Saving Documents¶
# Save as .docx
doc.save("output.docx")
# Export as bytes (no file I/O)
raw_bytes = doc.to_bytes()
# Export as BytesIO stream
stream = doc.to_stream()
# Export as PDF (requires docx2pdf + Office/LibreOffice)
doc.export_pdf("output.pdf")