API reference¶
Unless otherwise noted, all classes are immutable.
pdfje¶
- final class pdfje.Document(content=None, style=Style.EMPTY)[source]¶
a PDF Document
- Parameters:
Examples
Below are some examples of creating documents.
>>> Document() # the minimal PDF -- one empty page >>> Document("hello world") # a document with pages of text >>> Document([ # document with explicit pages ... Page(...), ... AutoPage([LOREM_IPSUM, ZEN_OF_PYTHON]), ... Page(), ... ])
Note
A document must contain at least one page to be valid
- write(target=None)[source]¶
Write the document to a given target. If no target is given, outputs the binary PDF content iteratively. See examples below.
- Parameters:
target (PathLike | str | IO[bytes] | None) – The target to write to. If not given, the PDF content is returned as an iterator.
- Return type:
Examples
String,
Path
, orPathLike
target:>>> doc.write("myfolder/foo.pdf") >>> doc.write(Path.home() / "documents/foo.pdf")
Files and file-like objects:
>>> with open("my/file.pdf", 'wb') as f: ... doc.write(f) >>> doc.write(b:= BytesIO())
Iterator output is useful for streaming PDF contents. Below is an example of an HTTP request using the
httpx
library.>>> httpx.post("https://mysite.foo/upload", content=doc.write(), ... headers={"Content-Type": "application/pdf"})
- final class pdfje.Page(content=(), size=XY(595, 842), rotate=0, margin=Sides(top=72, right=72, bottom=72, left=72), columns=())[source]¶
A single page within a document. Contains drawings at given positions.
Example
from pdfje import Page, Line, Rect, Text, A5 title_page = Page([ Text((100, 200), "My awesome story"), Line((100, 100), (200, 100)), Rect((50, 50), width=200, height=300), ], size=A5)
- Parameters:
content (
Iterable
[Drawing
]) – The drawings to render on the page.size (
XY
|tuple
[float
,float
]) –The size of the page in points. Common page sizes are available as constants:
from pdfje.units import Page, A4, A5, A6, letter, legal, tabloid
rotate (
Literal
[0
,90
,180
,270
]) – The rotation of the page in degrees.margin (
Union
[Sides
,Tuple
[float
,float
,float
,float
],Tuple
[float
,float
,float
],Tuple
[float
,float
],float
]) – The margin around the page in points, used for layout. Can be a single value, or a 2, 3 or 4-tuple following the CSS shorthand convention. see https://www.w3schools.com/css/css_margin.aspcolumns (
Sequence
[Column
]) – The columns to use for laying out the content. If not given, the content is laid out in a single column based on the page size and margin.
- final class pdfje.AutoPage(content, template=always(Page(content=(), size=XY(595, 842), rotate=0, columns=[Column(origin=XY(72, 72), width=451, height=698)])))[source]¶
Automatically lays out content on multiple pages.
- Parameters:
content (Iterable[Block | str] | Block | str) – The content to lay out on the pages. Can be parsed from single string or block.
template (Page | Callable[[int], Page]) – A page to use as a template for the layout. If a callable is given, it is called with the page number as the only argument to generate the page. Defaults to the default
Page
.
- final class pdfje.RGB(red=0, green=0, blue=0)[source]¶
Represents a color in RGB space, with values between 0 and 1.
Common colors are available as constants:
from pdfje import red, lime, blue, black, white, yellow, cyan, magenta
Note
In most cases where you would use a color, you can use a string of the form
#RRGGBB
or instead, e.g.#fa9225
- final class pdfje.XY(x=0, y=0)[source]¶
Represents a point, vector, or size in 2D space, where the first coordinate is the horizontal component and the second is the vertical one.
This class supports some basic operators:
>>> XY(1, 2) + XY(3, 4) XY(4, 6) # two-tuples are also supported >>> XY(1, 2) - (3, 4) XY(-2, -2) >>> XY(1, 2) / 2 XY(0.5, 1.0) >>> XY(1, 2) * 2 XY(2, 4)
It also implements the
Sequence
protocol:>>> xy = XY(1, 2) >>> xy[0] 1 >>> x, y = xy >>> list(xy) [1, 2]
pdfje.style¶
- final class pdfje.style.Style(font=None, size=None, bold=None, italic=None, color=None, line_spacing=None, hyphens=NOT_SET)[source]¶
Settings for visual style of text. All parameters are optional.
The default style is Helvetica (regular) size 12, with line spacing 1.25
- Parameters:
font (TrueType | BuiltinTypeface) – Typeface to use.
size (float) – Size of the font, in points.
bold (bool) – Whether to use bold font.
italic (bool) – Whether to use italic font.
color (RGB | str) – Color of the text; can be given as a hex string (e.g.
#ff0000
)line_spacing (float) – Line spacing, as a multiplier of the font size.
hyphens (Pyphen | None | Callable[[str], Iterable[str]]) – Hyphenation algorithm to use. Passing an explicit
None
disables hyphenation.
Example
Below we can see how to create a style, and how to combine them.
>>> from pdfje import Style, RGB, times_roman >>> body = Style(font=times_roman, size=14, italic=True)) >>> heading = body | Style(size=24, bold=True, color=RGB(0.5, 0, 0)) >>> # fonts and colors can be used directly in place of styles >>> emphasis = times_roman | "#ff0000"
- final class pdfje.style.Span(content, style=Style.EMPTY)[source]¶
A fragment of text with a style.
- Parameters:
Examples
from pdfje.style import Span, Style, bold from pdfje.fonts import times_roman # A simple span Span("Hello, world!", Style(size=24, color="#ff0000")) # A nested span Span([ "Beautiful is ", Span("better", helvetica | bold), " than ugly.", ], style=times_roman)
- pdfje.style.bold = Style(bold=True)¶
Shortcut for bold style.
- pdfje.style.italic = Style(italic=True)¶
Shortcut for italic style.
- pdfje.style.regular = Style(bold=False, italic=False)¶
Shortcut for regular (non-bold or italic) style.
pdfje.layout¶
- class pdfje.layout.Block[source]¶
Base class for block elements that can be laid out in a column by
AutoPage
.
- final class pdfje.layout.Paragraph(content, style=Style.EMPTY, align=Align.LEFT, indent=0, avoid_orphans=True, optimal=True)[source]¶
A
Block
that renders a paragraph of text.- Parameters:
content (
Union
[str
,Span
,Sequence
[str
|Span
]]) – The text to render. Can be a string, or a nestedSpan
.style (
Union
[Style
,RGB
,BuiltinTypeface
,TrueType
,str
]) – The style to render the text with. See tutorial for more details.align (Align |
"left"
|"center"
|"right"
|"justify"
) – The horizontal alignment of the text.indent (
float
) – The amount of space to indent the first line of the paragraph.avoid_orphans (
bool
) – Whether to avoid orphans (single lines before or after a page or column break).optimal (
LinebreakParams
|bool
|None
) – Whether to use the optimal paragraph layout algorithm. If set toFalse
orNone
, a faster but less optimal algorithm is used. To customize the algorithm parameters, pass anLinebreakParams
object.
Examples
from pdfje.layout import Paragraph from pdfje.style import Style Paragraph( "This is a paragraph of text.", style="#003311", align="center", ) Paragraph( [ "It can also be ", Span("styled", "#00ff00"), " in multiple ", Span("ways", Style(size=14, italic=True)), ".", ], style=times_roman, optimal=False, )
- final class pdfje.layout.Rule(color=RGB(0.000, 0.000, 0.000), margin=Sides(top=6, right=0, bottom=6, left=0))[source]¶
A
Block
that draws a horizontal line
- class pdfje.layout.LinebreakParams(tolerance=1, hyphen_penalty=1000, consecutive_hyphen_penalty=1000, fitness_diff_penalty=1000)[source]¶
Parameters for tweaking the optimum-fit algorithm.
- Parameters:
tolerance (
float
) – The tolerance for the stretch of each line. If no feasible solution is found, the tolerance is increased until there is. Increase the tolerance if you want to avoid hyphenation at the cost of more stretching and longer runtime.hyphen_penalty (
float
) – The penalty for hyphenating a word. If increasing this value does not result in fewer hyphens, try increasing the tolerance.consecutive_hyphen_penalty (
float
) – The penalty for placing hyphens on consecutive lines. If increasing this value does not appear to work, try increasing the tolerance.fitness_diff_penalty (
float
) – The penalty for very tight and very loose lines following each other.
pdfje.draw¶
- final class pdfje.draw.Circle(center, radius, fill=None, stroke=RGB(0.000, 0.000, 0.000))[source]¶
A
Drawing
of a circle.- Parameters:
center (
XY
|tuple
[float
,float
]) – The center of the circle. Can be parsed from a 2-tuple.radius (
float
) – The radius of the circle.fill (RGB | str | None) – The fill color – can be parsed from a hex string (e.g.
#ff0000
)stroke (RGB | str | None) – The stroke color – can be parsed from a hex string (e.g.
#ff0000
)
- final class pdfje.draw.Ellipse(center, width, height, fill=None, stroke=RGB(0.000, 0.000, 0.000))[source]¶
A
Drawing
of an ellipse.- Parameters:
center (
XY
|tuple
[float
,float
]) – The center of the ellipse. Can be parsed from a 2-tuple.width (
float
) – The width of the ellipse.height (
float
) – The height of the ellipse.fill (RGB | str | None) – The fill color – can be parsed from a hex string (e.g.
#ff0000
)stroke (RGB | str | None) – The stroke color – can be parsed from a hex string (e.g.
#ff0000
)
- final class pdfje.draw.Line(start, end, stroke=RGB(0.000, 0.000, 0.000))[source]¶
A
Drawing
of a straight line segment.
- final class pdfje.draw.Polyline(points, close=False, fill=None, stroke=RGB(0.000, 0.000, 0.000))[source]¶
A
Drawing
of a polyline.- Parameters:
points (
Iterable
[XY
|tuple
[float
,float
]]) – The points of the polyline. Can be parsed from a 2-tuple.close (
bool
) – Whether to close the polyline.fill (RGB | str | None) – The fill color – can be parsed from a hex string (e.g.
#ff0000
)stroke (RGB | str | None) – The stroke color – can be parsed from a hex string (e.g.
#ff0000
)
- final class pdfje.draw.Rect(origin, width, height, fill=None, stroke=RGB(0.000, 0.000, 0.000))[source]¶
A
Drawing
of a rectangle.- Parameters:
origin (
XY
|tuple
[float
,float
]) – The bottom left corner of the rectangle. Can be parsed from a 2-tuple.width (
float
) – The width of the rectangle.height (
float
) – The height of the rectangle.fill (RGB | str | None) – The fill color – can be parsed from a hex string (e.g.
#ff0000
)stroke (RGB | str | None) – The stroke color – can be parsed from a hex string (e.g.
#ff0000
)
- final class pdfje.draw.Text(loc, content, style=Style.EMPTY, align=Align.LEFT)[source]¶
A
Drawing
of text at the given location (not wrapped)- Parameters:
loc (
XY
|tuple
[float
,float
]) – The location of the text. Can be parsed from a 2-tuple.content (str | Span | Sequence[str | Span]) – The text to render. Can be a string, or a nested
Span
.style (
Union
[Style
,RGB
,BuiltinTypeface
,TrueType
,str
]) – The style to apply to the text.align (
Union
[Align
,Literal
['left'
,'center'
,'right'
]]) – The horizontal alignment of the text.
pdfje.fonts¶
- pdfje.fonts.helvetica = BuiltinTypeface(Helvetica)¶
A typeface that is built into the PDF renderer.
- pdfje.fonts.times_roman = BuiltinTypeface(Times-Roman)¶
A typeface that is built into the PDF renderer.
- pdfje.fonts.courier = BuiltinTypeface(Courier)¶
A typeface that is built into the PDF renderer.
- pdfje.fonts.symbol = BuiltinTypeface(Symbol)¶
A typeface that is built into the PDF renderer.
- pdfje.fonts.zapf_dingbats = BuiltinTypeface(ZapfDingbats)¶
A typeface that is built into the PDF renderer.
- final class pdfje.fonts.BuiltinTypeface(regular, bold, italic, bold_italic)[source]¶
A typeface that is built into the PDF renderer.
pdfje.units¶
- pdfje.units.inch(b, /)¶
Convert inches to points
- pdfje.units.cm(b, /)¶
Convert centimeters to points
- pdfje.units.mm(b, /)¶
Convert millimeters to points
- pdfje.units.pc(b, /)¶
Convert picas to points
Page sizes
Below are common page sizes.
Because the page size is a XY
object, you can use
x
and y
attributes to get the width and height of a page size.
The landscape variants can be obtained by calling flip()
.
from pdfje.units import A4
A4.x # 595
A4.y # 842
A4.flip() # XY(842, 595) -- the landscape variant
A4 / 2 # XY(297.5, 421) -- point at the center of the page
- pdfje.units.A0 = XY(2380, 3368)¶
A0 paper size
- pdfje.units.A1 = XY(1684, 2380)¶
A1 paper size
- pdfje.units.A2 = XY(1190, 1684)¶
A2 paper size
- pdfje.units.A3 = XY(842, 1190)¶
A3 paper size
- pdfje.units.A4 = XY(595, 842)¶
A4 paper size
- pdfje.units.A5 = XY(420, 595)¶
A5 paper size
- pdfje.units.A6 = XY(297, 420)¶
A6 paper size
- pdfje.units.letter = XY(612, 792)¶
Letter paper size
- pdfje.units.legal = XY(612, 1008)¶
Legal paper size
- pdfje.units.tabloid = XY(792, 1224)¶
Tabloid paper size
- pdfje.units.ledger = XY(1224, 792)¶
Ledger paper size, same as tabloid landscape