The PageObject Class
- class pypdf._page.PageObject(pdf: Optional[PdfCommonDocProtocol] = None, indirect_reference: Optional[IndirectObject] = None)[source]
Bases:
DictionaryObject
PageObject represents a single page within a PDF file.
Typically these objects will be created by accessing the
pages
property of thePdfReader
class, but it is also possible to create an empty page with thecreate_blank_page()
static method.- Parameters
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 [source]
Used to detect modified object.
Note: this function is overloaded to return the same results as a DictionaryObject.
- Returns
Hash considering type and value.
- 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: Optional[PdfCommonDocProtocol] = None, width: Optional[Union[float, Decimal]] = None, height: Optional[Union[float, Decimal]] = None) PageObject [source]
Return a new blank page.
If
width
orheight
isNone
, try to get the page size from the last page of pdf.- Parameters
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.
- Returns
The new blank page
- Raises
PageSizeNotDefinedError – if
pdf
isNone
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
Examples
reader.pages[0].images[0] # return fist 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 [source]
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 [source]
Rotate a page clockwise by increments of 90 degrees.
- Parameters
angle – Angle to rotate the page. Must be an increment of 90 deg.
- Returns
The rotated PageObject
- get_contents() Optional[ContentStream] [source]
Access the page contents.
- Returns
The
/Contents
object, orNone
if it does not exist./Contents
is optional, as described in §7.7.3.3 of the PDF Reference.
- replace_contents(content: Union[None, ContentStream, EncodedStreamObject, ArrayObject]) None [source]
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 [source]
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.
- Parameters
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: Union[Tuple[float, float, float, float, float, float], Transformation], over: bool = True, expand: bool = False) None [source]
merge_transformed_page is similar to merge_page, but a transformation matrix is applied to the merged stream.
- Parameters
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 [source]
merge_scaled_page is similar to merge_page, but the stream to be merged is scaled by applying a transformation matrix.
- Parameters
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 [source]
merge_rotated_page is similar to merge_page, but the stream to be merged is rotated by applying a transformation matrix.
- Parameters
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 [source]
mergeTranslatedPage is similar to merge_page, but the stream to be merged is translated by applying a transformation matrix.
- Parameters
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: Union[Transformation, Tuple[float, float, float, float, float, float]], expand: bool = False) None [source]
Apply a transformation matrix to the page.
- Parameters
ctm – A 6-element tuple containing the operands of the transformation matrix. Alternatively, a
Transformation
object can be passed.
- scale(sx: float, sy: float) None [source]
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.
- Parameters
sx – The scaling factor on horizontal axis.
sy – The scaling factor on vertical axis.
- scale_by(factor: float) None [source]
Scale a page by the given factor by applying a transformation matrix to its content and updating the page size.
- Parameters
factor – The scaling factor (for both X and Y axis).
- scale_to(width: float, height: float) None [source]
Scale a page to the specified dimensions by applying a transformation matrix to its content and updating the page size.
- Parameters
width – The new width.
height – The new height.
- compress_content_streams(level: int = - 1) None [source]
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: Optional[int]
Read-only property which returns the page number within the PDF file.
- Returns
int – page number; None if the page is not attached to a PDF.
- extract_text(*args: Any, orientations: Union[int, Tuple[int, ...]] = (0, 90, 180, 270), space_width: float = 200.0, visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None, visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None, visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None, extraction_mode: Literal['plain', 'layout'] = 'plain', **kwargs: Any) str [source]
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.
- Parameters
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)
- Returns
The extracted text
- extract_xform_text(xform: EncodedStreamObject, orientations: Tuple[int, ...] = (0, 90, 270, 360), space_width: float = 200.0, visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None, visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None, visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None) str [source]
Extract text from an XObject.
- Parameters
xform –
orientations –
space_width – force default space width (if not extracted from font (default 200)
visitor_operand_before –
visitor_operand_after –
visitor_text –
- Returns
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: Optional[ArrayObject]
- class pypdf._page.VirtualListImages(ids_function: Callable[[], List[Union[str, List[str]]]], get_function: Callable[[Union[str, List[str], Tuple[str]]], ImageFile])[source]
-
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.
- class pypdf._page.ImageFile(name: str = '', data: bytes = b'', image: Optional[Image] = None, indirect_reference: Optional[IndirectObject] = None)[source]
Bases:
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.- indirect_reference: Optional[IndirectObject] = None
Reference to the object storing the stream.
- replace(new_image: Image, **kwargs: Any) None [source]
Replace the image with a new PIL image.
- Parameters
new_image (Image) – The new PIL image to replace the existing image.
**kwargs – Additional keyword arguments to pass to Image.save().
- Raises
Note
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.