Canvas

The pikepdf.canvas provides a low-level PDF rendering API.

class pikepdf.canvas.Canvas(*, page_size)

Canvas for rendering PDFs with pikepdf.

All drawing is done on a pikepdf canvas using the .do property. This interface manages the graphics state of the canvas.

A Canvas can be exported as a single page Pdf using .to_pdf. This Pdf can then be merged into other PDFs or written to a file.

Parameters:

page_size (tuple[int | float, int | float])

add_font(resource_name, font)

Add a font to the page.

Parameters:
  • resource_name (pikepdf.objects.Name)

  • font (Font)

Return type:

None

property do: _CanvasAccessor

Do operations on the current graphics state.

Return type:

_CanvasAccessor

page_size
to_pdf()

Render the canvas as a single page PDF.

Return type:

Pdf

class pikepdf.canvas._CanvasAccessor(cs, images=None)

Contains all drawing methods class for drawing on a Canvas.

Parameters:
cm(matrix)

Concatenate a new transformation matrix to the current matrix.

Parameters:

matrix (Matrix)

Return type:

Self

dashes(*args)

Set dashes.

Parameters:

args (collections.abc.Sequence[int | float | decimal.Decimal] | int | float | decimal.Decimal | None)

Return type:

Self

draw_image(image, x, y, width, height)

Draw image at (x,y) with width w and height h.

Parameters:
  • image (pathlib.Path | str | PIL.Image.Image)

  • x (float)

  • y (float)

  • width (float)

  • height (float)

Return type:

Self

draw_text(text)

Draw text object.

Parameters:

text (Text)

Return type:

Self

fill_color(color)

Set fill color.

Parameters:

color (Color)

Return type:

Self

line(x1, y1, x2, y2)

Draw line from (x1,y1) to (x2,y2).

Parameters:
  • x1 (float)

  • y1 (float)

  • x2 (float)

  • y2 (float)

Return type:

Self

line_width(width)

Set line width.

Parameters:

width (int | float | decimal.Decimal)

Return type:

Self

pop()

Restore the previous graphics state.

Return type:

Self

push()

Save the graphics state.

Return type:

Self

rect(x, y, w, h, fill)

Draw optionally filled rectangle at (x,y) with width w and height h.

Parameters:
  • x (float)

  • y (float)

  • w (float)

  • h (float)

  • fill (bool)

Return type:

Self

save_state(*, cm=None)

Save the graphics state and restore it on exit.

Optionally, concatenate a transformation matrix. Implements the commonly used pattern of:

q cm … Q

Parameters:

cm (Matrix | None)

Return type:

collections.abc.Iterator[Self]

stroke_color(color)

Set stroke color.

Parameters:

color (Color)

Return type:

Self

class pikepdf.canvas.ContentStreamBuilder

Content stream builder.

append_rectangle(x, y, w, h)

Append rectangle to path.

Parameters:
  • x (float)

  • y (float)

  • w (float)

  • h (float)

Return type:

Self

begin_marked_content(mctype)

Begin marked content sequence.

Parameters:

mctype (pikepdf.objects.Name)

Return type:

Self

begin_marked_content_proplist(mctype, mcid)

Begin marked content sequence.

Parameters:
  • mctype (pikepdf.objects.Name)

  • mcid (int)

Return type:

Self

begin_text()

Begin text object.

All text operations must be contained within a text object, and are invalid otherwise. The text matrix and font are reset for each text object. Text objects may not be nested.

Return type:

Self

build()

Build content stream.

Return type:

bytes

cm(matrix)

Concatenate matrix.

Parameters:

matrix (Matrix)

Return type:

Self

draw_xobject(name)

Draw XObject.

Add instructions to render an XObject. The XObject must be defined in the document.

Parameters:

name (pikepdf.objects.Name) – Name of XObject

Return type:

Self

end_marked_content()

End marked content sequence.

Return type:

Self

end_text()

End text object.

Return type:

Self

extend(other)

Append another content stream.

Parameters:

other (ContentStreamBuilder | bytes)

Return type:

None

fill()

Stroke and close path.

Return type:

Self

line(x1, y1, x2, y2)

Draw line.

Parameters:
  • x1 (float)

  • y1 (float)

  • x2 (float)

  • y2 (float)

Return type:

Self

move_cursor(dx, dy)

Move cursor by the given offset, relative to the start of the current line.

This operator modifies the both current text matrix and the text line matrix. This means that, in addition to moving the current cursor, the new cursor will also be defined as the start of a new line.

The new position will be redefined as the new start of the line even if the y offset is 0; what to a user may look like a single line of text could be encoded in the PDF content stream as multiple “lines”. It’s not uncommon for PDFs to be written with every word as a separate “line”, allowing the PDF writer to explicitly define the spacing between each word.

Parameters:
  • dx (int | float | decimal.Decimal)

  • dy (int | float | decimal.Decimal)

Return type:

Self

move_cursor_new_line()

Move cursor to the start of the next line.

This moves down by the current leading value, and resets the x position back to the value it had at the beginning of the current line.

This operator modifies the both current text matrix and the text line matrix. This means that, in addition to moving the current cursor, the new cursor will also be defined as the start of a new line.

The value this operation moves the cursor is set using set_text_leading.

Return type:

Self

pop()

Restore the graphics state.

Return type:

Self

push()

Save the graphics state.

Return type:

Self

set_dashes(array=None, phase=0)

Set dashes.

Parameters:
  • array (collections.abc.Sequence[int | float | decimal.Decimal] | int | float | None)

  • phase (int | float | decimal.Decimal)

Return type:

Self

set_fill_color(r, g, b)

Set RGB fill color.

Parameters:
  • r (float)

  • g (float)

  • b (float)

Return type:

Self

set_line_width(width)

Set line width.

Parameters:

width (int | float | decimal.Decimal)

Return type:

Self

set_stroke_color(r, g, b)

Set RGB stroke color.

Parameters:
  • r (float)

  • g (float)

  • b (float)

Return type:

Self

set_text_char_spacing(size)

Set the character spacing (Tc) for future text operations.

This is a value, measured in unscaled text-space units, which will be used to adjust the spacing between characters. A value of 0 (the default) means that, for each rendered glyph, the cursor will advance only the actual width of the glyph. Positive values will result in additional space between characters, and negative values will cause glyphs to overlap.

In vertical writing, the sign works opposite of what one might expect: a positive value shrinks the space, and a negative value increases it.

Parameters:

size (int | float | decimal.Decimal)

Return type:

Self

set_text_font(font, size)

Set text font and size.

This operator is mandatory in order to show text. Any text object which attempts to show text without first calling this operator is invalid.

The font name must match an entry in the current resources dictionary. The font size is expressed in text-space units. Assuming no text scaling is in place, and the PDF has not set a user-defined unit in the page dictionary, then text space units will be points (defined as 1/72 of an inch).

Parameters:
  • font (pikepdf.objects.Name)

  • size (int | float | decimal.Decimal)

Return type:

Self

set_text_horizontal_scaling(scale)

Set text horizontal scaling.

Parameters:

scale (float)

Return type:

Self

set_text_leading(size)

Set the leading value (TL) for future text operations.

This is the vertical spacing between lines. Specifically, it is defined as the distance between the baseline of the previous line to the baseline of the next line.

Parameters:

size (int | float | decimal.Decimal)

Return type:

Self

set_text_matrix(matrix)

Set text matrix.

The text matrix defines the conversion between text-space and page-space, in terms of both scaling and translation. If this matrix scales the text, then it redefines text-space units as being some scale factor of page-space units.

Parameters:

matrix (Matrix)

Return type:

Self

set_text_rendering(mode)

Set text rendering mode.

Parameters:

mode (int)

Return type:

Self

set_text_word_spacing(size)

Set the word spacing (Tw) for future text operations.

This is a value, measured in unscaled text-space units, which will be added to the width of any ASCII space characters.

In vertical writing, the sign works opposite of what one might expect: a positive value shrinks the space, and a negative value increases it.

Parameters:

size (int | float | decimal.Decimal)

Return type:

Self

show_text(encoded)

Show text.

The text must be encoded in character codes expected by the font.

Parameters:

encoded (bytes)

Return type:

Self

show_text_line(encoded)

Advance to the next line and show text.

The text must be encoded in character codes expected by the font.

This is functionally equivalent to move_cursor_new_line() followed by show_text_string(encoded), but in a single operation.

Parameters:

encoded (bytes)

Return type:

Self

show_text_line_with_spacing(encoded, word_spacing, char_spacing)

Advance to the next line and show text.

The text must be encoded in character codes expected by the font.

This is functionally equivalent to set_text_char_spacing(char_spacing) and set_text_word_spacing(), followed by move_cursor_new_line() and then show_text(encoded), all in a single operation.

Parameters:
  • encoded (bytes)

  • word_spacing (int)

  • char_spacing (int)

Return type:

Self

show_text_with_kerning(*parts)

Show text, with manual spacing (kerning) options.

Arguments are either bytes, which represent the actual text to show, or numbers, which move the cursor. The units for the numbers are expressed in thousandths of a text-space unit (thus typically equivalent to a glyph-space unit).

For horizontal writing, positive values move the cursor left, and negative right. For vertical writing, positive values move down and negative up.

The text must be encoded in character codes expected by the font.

Parameters:

parts (bytes | int | float | decimal.Decimal)

Return type:

Self

stroke_and_close()

Stroke and close path.

Return type:

Self

class pikepdf.canvas.LoadedImage

Loaded image.

This class is used to track images that have been loaded into a canvas.

image: PIL.Image.Image
name: pikepdf.objects.Name

Text and fonts

class pikepdf.canvas.Text(direction=TextDirection.LTR)

Text object for rendering text on a pikepdf canvas.

Parameters:

direction (TextDirection)

font(font, size)

Set font and size.

Parameters:
  • font (pikepdf.objects.Name)

  • size (float)

Return type:

Self

horiz_scale(scale)

Set text horizontal scaling.

Parameters:

scale (float)

Return type:

Self

move_cursor(x, y)

Move cursor.

Parameters:
  • x (int | float | decimal.Decimal)

  • y (int | float | decimal.Decimal)

Return type:

Self

render_mode(mode)

Set text rendering mode.

Parameters:

mode (int)

Return type:

Self

show(text)

Show text.

The text must be encoded in character codes expected by the font. If a text string is passed, it will be encoded as UTF-16BE. Text rendering will not work properly if the font’s character codes are not consistent with UTF-16BE. This is a rudimentary interface. You’ve been warned.

Parameters:

text (str | bytes)

Return type:

Self

text_transform(matrix)

Set text matrix.

Parameters:

matrix (Matrix)

Return type:

Self

class pikepdf.canvas.TextDirection

Enumeration for text direction.

LTR = 1

Left to right, the default.

RTL = 2

Right to left, Arabic, Hebrew, Persian, etc.

class pikepdf.canvas.Font

Base class for fonts.

abstractmethod register(pdf)

Register the font.

Create several data structures in the Pdf to describe the font.

After registering the font, the returned object should be added to the /Resources dictionary of any page or Form XObject that uses the font. For example one might write:

`python page.Resources.Font[Name.Arial] = font.register(pdf) `

The same object can be used for multiple pages or Form XObjects, since it is an indirect object.

Returns a Dictionary suitable for insertion into a /Resources /Font dictionary.

Parameters:

pdf (Pdf)

Return type:

pikepdf.objects.Dictionary

abstractmethod text_width(text, fontsize=1, *, char_spacing=0, word_spacing=0)

Estimate the width of a text string when rendered with the given font.

Parameters:
  • text (str | bytes)

  • fontsize (float | int | decimal.Decimal)

  • char_spacing (int | decimal.Decimal)

  • word_spacing (int | decimal.Decimal)

Return type:

float | int | decimal.Decimal

class pikepdf.canvas.Helvetica

Helvetica font.

Helvetica is one of the 14 PDF standard fonts that can typically be counted on being present even if not embedded in the PDF document. However, starting with PDF 2.0, PDF processors are no longer guaranteed to have these fonts. See 9.6.2.2.

register(pdf)

Register the font.

Parameters:

pdf (Pdf)

Return type:

pikepdf.objects.Dictionary

abstractmethod text_width(text, fontsize=1, *, char_spacing=0, word_spacing=0)

Estimate the width of a text string when rendered with the given font.

Parameters:
  • text (str | bytes)

  • fontsize (float | int | decimal.Decimal)

  • char_spacing (int | decimal.Decimal)

  • word_spacing (int | decimal.Decimal)

Return type:

float | int | decimal.Decimal

class pikepdf.canvas.SimpleFont(data)

Font implementation designed to work with Type 1 Fonts and TrueType fonts.

As described in section 9.6 of the PDF spec.

See also section 9.8: Font Descriptors.

The PDF spec also considers Type3 fonts to be “Simple Fonts”, but Type3 fonts are not implemented here.

Parameters:

data (pikepdf.objects.Dictionary)

property ascent: decimal.Decimal

Returns ascent for a SimpleFont.

Return type:

decimal.Decimal

convert_width(width, fontsize=1)

Convert width from glyph space to text space, scaling by font size.

Scaling based on the nominal height (see 9.2.2):

“This standard is arranged so that the nominal height of tightly spaced lines of text is 1 unit. … The standard-size font shall then be scaled to be usable.”

This means, essentially, that a font size of 1 means a character is 1 text-space unit high, and a font size of 12 is 12 text-space units high. Assuming no text scaling is in place (such as via the text matrix), and the PDF has not set a user-defined unit in the page dictionary, then text space units will be points (defined as 1/72 of an inch).

Parameters:
  • width (int | decimal.Decimal)

  • fontsize (int | decimal.Decimal)

Return type:

int | decimal.Decimal

convert_width_reverse(width, fontsize=1)

Convert width from text space back to glyph space, scaling by font size.

Parameters:
  • width (int | decimal.Decimal)

  • fontsize (int | decimal.Decimal)

Return type:

int | decimal.Decimal

data: pikepdf.objects.Dictionary
property descent: decimal.Decimal

Returns descent for a SimpleFont.

Return type:

decimal.Decimal

encode(text)

Encode a string in the encoding used by this font.

This currently only works with fonts that use the WinAnsiEncoding or the MacRomanEncoding. Differences maps are supported, though with a limited set of recognized character names.

Parameters:

text (str)

Return type:

bytes

property leading: int | decimal.Decimal

Returns leading for a SimpleFont.

Return type:

int | decimal.Decimal

classmethod load(name, resource_dict)

Load a font from the specified resource dictionary.

Parameters:
  • name (pikepdf.objects.Name)

  • resource_dict (pikepdf.objects.Dictionary)

Return type:

SimpleFont

register(pdf)

Register the font.

Parameters:

pdf (Pdf)

Return type:

pikepdf.objects.Dictionary

text_width(text, fontsize=1, *, char_spacing=0, word_spacing=0)

Get the width of the string.

This is the width of the string when rendered with the current font, scaled by the given font size.

Parameters:
  • text (str | bytes) – The string to check

  • fontsize (float | int | decimal.Decimal) – The target font size in text-space units. (Assuming text space isn’t being scaled, this means the font size in points.)

  • char_spacing (int | decimal.Decimal) – Additional space that will be added between each character. May be negative.

  • word_spacing (int | decimal.Decimal) – Additional space that will be added after each ASCII space character (’ ‘). May be negative.

Return type:

float | int | decimal.Decimal

unscaled_char_width(char)

Get the (unscaled) width of the character, in glyph-space units.

Parameters:

char (int | bytes | str) – The character to check. May be a char code, or a string containing a single character.

Return type:

decimal.Decimal