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)

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:

pikepdf._core.Pdf

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

Contains all drawing methods class for drawing on a Canvas.

Parameters:

cs (ContentStreamBuilder)

cm(matrix)

Concatenate a new transformation matrix to the current matrix.

Parameters:

matrix (pikepdf._core.Matrix)

dashes(*args)

Set dashes.

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)

draw_text(text)

Draw text object.

Parameters:

text (Text)

fill_color(color)

Set fill color.

Parameters:

color (Color)

line(x1, y1, x2, y2)

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

line_width(width)

Set line width.

pop()

Restore the previous graphics state.

push()

Save the graphics state.

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

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

Parameters:

fill (bool)

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 (pikepdf._core.Matrix | None)

stroke_color(color)

Set stroke color.

Parameters:

color (Color)

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)

begin_marked_content(mctype)

Begin marked content sequence.

Parameters:

mctype (pikepdf.objects.Name)

begin_marked_content_proplist(mctype, mcid)

Begin marked content sequence.

Parameters:
  • mctype (pikepdf.objects.Name)

  • mcid (int)

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.

build()

Build content stream.

Return type:

bytes

cm(matrix)

Concatenate matrix.

Parameters:

matrix (pikepdf._core.Matrix)

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

end_marked_content()

End marked content sequence.

end_text()

End text object.

extend(other)

Append another content stream.

Parameters:

other (ContentStreamBuilder | bytes)

fill()

Stroke and close path.

line(x1, y1, x2, y2)

Draw line.

Parameters:
  • x1 (float)

  • y1 (float)

  • x2 (float)

  • y2 (float)

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.

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.

pop()

Restore the graphics state.

push()

Save the graphics state.

set_dashes(array=None, phase=0)

Set dashes.

set_fill_color(r, g, b)

Set RGB fill color.

Parameters:
  • r (float)

  • g (float)

  • b (float)

set_line_width(width)

Set line width.

set_stroke_color(r, g, b)

Set RGB stroke color.

Parameters:
  • r (float)

  • g (float)

  • b (float)

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)

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)

set_text_horizontal_scaling(scale)

Set text horizontal scaling.

Parameters:

scale (float)

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)

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 (pikepdf._core.Matrix)

set_text_rendering(mode)

Set text rendering mode.

Parameters:

mode (int)

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)

show_text(encoded)

Show text.

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

Parameters:

encoded (bytes)

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)

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)

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)

stroke_and_close()

Stroke and close path.

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.

font(font, size)

Set font and size.

Parameters:
  • font (pikepdf.objects.Name)

  • size (float)

horiz_scale(scale)

Set text horizontal scaling.

move_cursor(x, y)

Move cursor.

render_mode(mode)

Set text rendering mode.

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)

text_transform(matrix)

Set text matrix.

Parameters:

matrix (pikepdf._core.Matrix)

class pikepdf.canvas.TextDirection(*args, **kwds)

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.

abstract property ascent: decimal.Decimal | int | None

The max height of the font above the baseline.

Return type:

decimal.Decimal | int | None

abstract property descent: decimal.Decimal | int | None

The max height of the font below the baseline.

Return type:

decimal.Decimal | int | None

abstractmethod encode(text)

Encode a string in the encoding used by this font.

Parameters:

text (str)

Return type:

bytes

abstract property leading: decimal.Decimal | int

Default leading (line spacing) value for this font; 0 if not applicable.

Return type:

decimal.Decimal | int

abstractmethod register(pdf)

Register the font.

Create several data structures in the Pdf to describe the font. While it create the data, a reference should be set in at least one page’s /Resources dictionary to retain the font in the output PDF and ensure it is usable on that page.

The returned Dictionary should be created as an indirect object, using pdf.make_indirect().

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

Parameters:

pdf (pikepdf._core.Pdf)

Return type:

pikepdf.objects.Dictionary

abstractmethod text_width(text, fontsize)

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

Parameters:
  • text (str | bytes)

  • fontsize (float | 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.

property ascent

Returns None as no standard information is available.

property descent

Returns None as no standard information is available.

abstractmethod encode(text)

Encode a string in the encoding used by this font.

Parameters:

text (str)

Return type:

bytes

property leading

Returns leading for Helvetica (0pt).

register(pdf)

Register the font.

Parameters:

pdf (pikepdf._core.Pdf)

Return type:

pikepdf.objects.Dictionary

abstractmethod text_width(text, fontsize)

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

Parameters:
  • text (str | bytes)

  • fontsize (float | 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 (pikepdf._core.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 (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:

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