PageObject 类

class pypdf._page.PageObject(pdf: PdfCommonDocProtocol | None = None, indirect_reference: IndirectObject | None = None)[源代码]

基类:DictionaryObject

PageObject represents a single page within a PDF file.

Typically these objects will be created by accessing the pages property of the PdfReader class, but it is also possible to create an empty page with the create_blank_page() static method.

参数:
  • pdf -- PDF file the page belongs to.

  • indirect_reference -- Stores the original indirect reference to this object in its source PDF

original_page: PageObject
hash_bin() int[源代码]

Used to detect modified object.

Note: this function is overloaded to return the same results as a DictionaryObject.

返回:

Hash considering type and value.

hash_value_data() bytes[源代码]
property user_unit: float

A read-only positive number giving the size of user space units.

It is in multiples of 1/72 inch. Hence a value of 1 means a user space unit is 1/72 inch, and a value of 3 means that a user space unit is 3/72 inch.

static create_blank_page(pdf: PdfCommonDocProtocol | None = None, width: float | Decimal | None = None, height: float | Decimal | None = None) PageObject[源代码]

Return a new blank page.

If width or height is None, try to get the page size from the last page of pdf.

参数:
  • pdf -- PDF file the page is within.

  • width -- The width of the new page expressed in default user space units.

  • height -- The height of the new page expressed in default user space units.

返回:

The new blank page

抛出:

PageSizeNotDefinedError -- if pdf is None or contains no page

property images: VirtualListImages

Read-only property emulating a list of images on a page.

Get a list of all images on the page. The key can be: - A string (for the top object) - A tuple (for images within XObject forms) - An integer

示例

  • reader.pages[0].images[0] # return first image

  • reader.pages[0].images['/I0'] # return image '/I0'

  • reader.pages[0].images['/TP1','/Image1'] # return image '/Image1' within '/TP1' Xobject/Form

  • for img in reader.pages[0].images: # loops through all objects

images.keys() and images.items() can be used.

The ImageFile has the following properties:

  • .name : name of the object

  • .data : bytes of the object

  • .image : PIL Image Object

  • .indirect_reference : object reference

and the following methods:
.replace(new_image: PIL.Image.Image, **kwargs) :

replace the image in the pdf with the new image applying the saving parameters indicated (such as quality)

Example usage:

reader.pages[0].images[0]=replace(Image.open("new_image.jpg", quality = 20)

Inline images are extracted and named ~0~, ~1~, ..., with the indirect_reference set to None.

property rotation: int

The visual rotation of the page.

This number has to be a multiple of 90 degrees: 0, 90, 180, or 270 are valid values. This property does not affect /Contents.

transfer_rotation_to_content() None[源代码]

Apply the rotation of the page to the content and the media/crop/... boxes.

It is recommended to apply this function before page merging.

rotate(angle: int) PageObject[源代码]

Rotate a page clockwise by increments of 90 degrees.

参数:

angle -- Angle to rotate the page. Must be an increment of 90 deg.

返回:

The rotated PageObject

get_contents() ContentStream | None[源代码]

Access the page contents.

返回:

The /Contents object, or None if it does not exist. /Contents is optional, as described in §7.7.3.3 of the PDF Reference.

replace_contents(content: None | ContentStream | EncodedStreamObject | ArrayObject) None[源代码]

Replace the page contents with the new content and nullify old objects :param content: new content; if None delete the content field.

merge_page(page2: PageObject, expand: bool = False, over: bool = True) None[源代码]

Merge the content streams of two pages into one.

Resource references (i.e. fonts) are maintained from both pages. The mediabox/cropbox/etc of this page are not altered. The parameter page's content stream will be added to the end of this page's content stream, meaning that it will be drawn after, or "on top" of this page.

参数:
  • page2 -- The page to be merged into this one. Should be an instance of PageObject.

  • over -- set the page2 content over page1 if True (default) else under

  • expand -- If True, the current page dimensions will be expanded to accommodate the dimensions of the page to be merged.

merge_transformed_page(page2: PageObject, ctm: Tuple[float, float, float, float, float, float] | Transformation, over: bool = True, expand: bool = False) None[源代码]

merge_transformed_page is similar to merge_page, but a transformation matrix is applied to the merged stream.

参数:
  • page2 -- The page to be merged into this one.

  • ctm -- a 6-element tuple containing the operands of the transformation matrix

  • over -- set the page2 content over page1 if True (default) else under

  • expand -- Whether the page should be expanded to fit the dimensions of the page to be merged.

merge_scaled_page(page2: PageObject, scale: float, over: bool = True, expand: bool = False) None[源代码]

merge_scaled_page is similar to merge_page, but the stream to be merged is scaled by applying a transformation matrix.

参数:
  • page2 -- The page to be merged into this one.

  • scale -- The scaling factor

  • over -- set the page2 content over page1 if True (default) else under

  • expand -- Whether the page should be expanded to fit the dimensions of the page to be merged.

merge_rotated_page(page2: PageObject, rotation: float, over: bool = True, expand: bool = False) None[源代码]

merge_rotated_page is similar to merge_page, but the stream to be merged is rotated by applying a transformation matrix.

参数:
  • page2 -- The page to be merged into this one.

  • rotation -- The angle of the rotation, in degrees

  • over -- set the page2 content over page1 if True (default) else under

  • expand -- Whether the page should be expanded to fit the dimensions of the page to be merged.

merge_translated_page(page2: PageObject, tx: float, ty: float, over: bool = True, expand: bool = False) None[源代码]

mergeTranslatedPage is similar to merge_page, but the stream to be merged is translated by applying a transformation matrix.

参数:
  • page2 -- the page to be merged into this one.

  • tx -- The translation on X axis

  • ty -- The translation on Y axis

  • over -- set the page2 content over page1 if True (default) else under

  • expand -- Whether the page should be expanded to fit the dimensions of the page to be merged.

add_transformation(ctm: Transformation | Tuple[float, float, float, float, float, float], expand: bool = False) None[源代码]

Apply a transformation matrix to the page.

参数:

ctm -- A 6-element tuple containing the operands of the transformation matrix. Alternatively, a Transformation object can be passed.

See 裁剪和转换 PDF.

scale(sx: float, sy: float) None[源代码]

Scale a page by the given factors by applying a transformation matrix to its content and updating the page size.

This updates the mediabox, the cropbox, and the contents of the page.

参数:
  • sx -- The scaling factor on horizontal axis.

  • sy -- The scaling factor on vertical axis.

scale_by(factor: float) None[源代码]

Scale a page by the given factor by applying a transformation matrix to its content and updating the page size.

参数:

factor -- The scaling factor (for both X and Y axis).

scale_to(width: float, height: float) None[源代码]

Scale a page to the specified dimensions by applying a transformation matrix to its content and updating the page size.

参数:
  • width -- The new width.

  • height -- The new height.

compress_content_streams(level: int = -1) None[源代码]

Compress the size of this page by joining all content streams and applying a FlateDecode filter.

However, it is possible that this function will perform no action if content stream compression becomes "automatic".

property page_number: int | None

Read-only property which returns the page number within the PDF file.

返回:

int -- page number; None if the page is not attached to a PDF.

extract_text(*args: Any, orientations: int | Tuple[int, ...] = (0, 90, 180, 270), space_width: float = 200.0, visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None, visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None, visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None, extraction_mode: Literal['plain', 'layout'] = 'plain', **kwargs: Any) str[源代码]

Locate all text drawing commands, in the order they are provided in the content stream, and extract the text.

This works well for some PDF files, but poorly for others, depending on the generator used. This will be refined in the future.

Do not rely on the order of text coming out of this function, as it will change if this function is made more sophisticated.

Arabic and Hebrew are extracted in the correct order. If required a custom RTL range of characters can be defined; see function set_custom_rtl.

Additionally you can provide visitor methods to get informed on all operations and all text objects. For example in some PDF files this can be useful to parse tables.

参数:
  • orientations -- list of orientations extract_text will look for default = (0, 90, 180, 270) note: currently only 0 (up),90 (turned left), 180 (upside down), 270 (turned right) Silently ignored in "layout" mode.

  • space_width -- force default space width if not extracted from font (default: 200) Silently ignored in "layout" mode.

  • visitor_operand_before -- function to be called before processing an operation. It has four arguments: operator, operand-arguments, current transformation matrix and text matrix. Ignored with a warning in "layout" mode.

  • visitor_operand_after -- function to be called after processing an operation. It has four arguments: operator, operand-arguments, current transformation matrix and text matrix. Ignored with a warning in "layout" mode.

  • visitor_text -- function to be called when extracting some text at some position. It has five arguments: text, current transformation matrix, text matrix, font-dictionary and font-size. The font-dictionary may be None in case of unknown fonts. If not None it may e.g. contain key "/BaseFont" with value "/Arial,Bold". Ignored with a warning in "layout" mode.

  • extraction_mode (Literal["plain", "layout"]) -- "plain" for legacy functionality, "layout" for experimental layout mode functionality. NOTE: orientations, space_width, and visitor_* parameters are NOT respected in "layout" mode.

kwargs:
layout_mode_space_vertically (bool): include blank lines inferred from

y distance + font height. Defaults to True.

layout_mode_scale_weight (float): multiplier for string length when calculating

weighted average character width. Defaults to 1.25.

layout_mode_strip_rotated (bool): layout mode does not support rotated text.

Set to False to include rotated text anyway. If rotated text is discovered, layout will be degraded and a warning will result. Defaults to True.

layout_mode_debug_path (Path | None): if supplied, must target a directory.

creates the following files with debug information for layout mode functions if supplied:

  • fonts.json: output of self._layout_mode_fonts

  • tjs.json: individual text render ops with corresponding transform matrices

  • bts.json: text render ops left justified and grouped by BT/ET operators

  • bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines)

layout_mode_font_height_weight (float): multiplier for font height when calculating

blank lines. Defaults to 1.

返回:

The extracted text

extract_xform_text(xform: EncodedStreamObject, orientations: Tuple[int, ...] = (0, 90, 270, 360), space_width: float = 200.0, visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None, visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None, visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None) str[源代码]

Extract text from an XObject.

参数:
  • xform

  • orientations

  • space_width -- force default space width (if not extracted from font (default 200)

  • visitor_operand_before

  • visitor_operand_after

  • visitor_text

返回:

The extracted text

property mediabox

A RectangleObject, expressed in default user space units, defining the boundaries of the physical medium on which the page is intended to be displayed or printed.

property cropbox

A RectangleObject, expressed in default user space units, defining the visible region of default user space.

When the page is displayed or printed, its contents are to be clipped (cropped) to this rectangle and then imposed on the output medium in some implementation-defined manner. Default value: same as mediabox.

property bleedbox

A RectangleObject, expressed in default user space units, defining the region to which the contents of the page should be clipped when output in a production environment.

property trimbox

A RectangleObject, expressed in default user space units, defining the intended dimensions of the finished page after trimming.

property artbox

A RectangleObject, expressed in default user space units, defining the extent of the page's meaningful content as intended by the page's creator.

property annotations: ArrayObject | None
class pypdf._page.VirtualListImages(ids_function: Callable[[], List[str | List[str]]], get_function: Callable[[str | List[str] | Tuple[str]], ImageFile])[源代码]

基类:Sequence[ImageFile]

Provides access to images referenced within a page. Only one copy will be returned if the usage is used on the same page multiple times. See PageObject.images() for more details.

keys() List[str | List[str]][源代码]
items() List[Tuple[str | List[str], ImageFile]][源代码]
class pypdf._page.ImageFile(name: str = '', data: bytes = b'', image: object | None = None, indirect_reference: IndirectObject | None = None)[源代码]

基类:object

Image within the PDF file. This object is not designed to be built.

This object should not be modified except using ImageFile.replace() to replace the image with a new one.

name: str = ''

Filename as identified within the PDF file.

data: bytes = b''

Data as bytes.

image: object | None = None

Data as PIL image.

indirect_reference: IndirectObject | None = None

Reference to the object storing the stream.

replace(new_image: object, **kwargs: Any) None[源代码]

Replace the image with a new PIL image.

参数:
  • new_image (Image) -- The new PIL image to replace the existing image.

  • **kwargs -- Additional keyword arguments to pass to Image.save().

抛出:
  • TypeError -- If the image is inline or in a PdfReader.

  • TypeError -- If the image does not belong to a PdfWriter.

  • TypeError -- If new_image is not a PIL Image.

备注

This method replaces the existing image with a new image. It is not allowed for inline images or images within a PdfReader. The kwargs parameter allows passing additional parameters to Image.save(), such as quality.

pypdf.mult(m: List[float], n: List[float]) List[float][源代码]