### Install pypdf Source: https://github.com/py-pdf/pypdf/blob/main/README.md Install the pypdf library using pip. For AES encryption/decryption support, install with the 'crypto' extra. ```bash pip install pypdf ``` ```bash pip install pypdf[crypto] ``` -------------------------------- ### Install Development Requirements Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/intro.md Use this command to install all necessary dependencies for pypdf development. ```bash pip install -r requirements/dev.txt ``` -------------------------------- ### Install Documentation Requirements Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/documentation.md Install the necessary Python packages for building the documentation. This is a prerequisite for running local documentation builds. ```bash pip install -r requirements/docs.txt ``` -------------------------------- ### Install pypdf using pip Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/installation.md Use this command to install the pypdf library. Ensure you have Python 3.9+ and pip installed. ```bash pip install pypdf ``` -------------------------------- ### Install pypdf with all optional dependencies Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/installation.md Installs pypdf along with all optional dependencies, such as those for cryptography and image handling. ```bash pip install pypdf[full] ``` -------------------------------- ### Install pypdf development version from GitHub Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/installation.md Installs the latest development version of pypdf directly from its GitHub repository. ```bash pip install git+https://github.com/py-pdf/pypdf.git ``` -------------------------------- ### Install pre-commit Hooks Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/intro.md Run this command once to install git hooks managed by pre-commit, which automatically checks code quality on commit. ```bash pre-commit install ``` -------------------------------- ### Beginbfchar Mapping Example Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/cmaps.md Shows a specific character mapping from a byte to a Unicode glyph. ```text 1 beginbfchar <1B> ``` -------------------------------- ### Install pypdf for current user Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/installation.md Install pypdf for the current user only, which is useful if you do not have superuser privileges. ```bash pip install --user pypdf ``` -------------------------------- ### Install pypdf with image dependencies Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/installation.md Install pypdf with Pillow, which is required for image extraction from PDFs. ```bash pip install pypdf[image] ``` -------------------------------- ### Example Function with Google-Style Docstrings Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/documentation.md Illustrates a Python function using Google-Style Docstrings, including type annotations, arguments, return values, raised exceptions, and doctest examples. Ensure 'Returns' block is omitted if there's no return value. ```python def example(param1: int, param2: str) -> bool: """ Example function with PEP 484 type annotations. Args: param1: The first parameter. param2: The second parameter. Returns: The return value. True for success, False otherwise. Raises: AttributeError: The ``Raises`` section is a list of all exceptions that are relevant to the interface. ValueError: If `param2` is equal to `param1`. Examples: Examples should be written in doctest format, and should illustrate how to use the function. >>> print([i for i in example_generator(4)]) [0, 1, 2, 3] """ ``` -------------------------------- ### Install jbig2dec for JBIG2 support on Ubuntu Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/installation.md Installs the jbig2dec system package on Ubuntu, which is required for JBIG2 support in pypdf. ```bash sudo apt-get install jbig2dec ``` -------------------------------- ### Install CI Requirements for pypdf Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/testing.md Install the necessary requirements for Continuous Integration testing. Use `ci-3.11.txt` if running Python version 3.11 or higher. ```bash pip install -r requirements/ci.txt ``` ```bash pip install -r requirements/ci-3.11.txt ``` -------------------------------- ### Install pypdf with crypto dependencies Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/installation.md Install pypdf with extra dependencies required for AES encryption and decryption of PDFs. ```bash pip install pypdf[crypto] ``` -------------------------------- ### Install pypdf from Git PR Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/testing.md Install a development version of pypdf directly from a GitHub pull request using pip. Replace the repository and branch with the desired PR details. ```bash pip install git+https://github.com/pubpub-zz/pypdf.git@iss2200 ``` -------------------------------- ### CMap Structure Example Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/cmaps.md Example of a CMap definition within a PDF file. ```text begincmap /CMapName /T1Encoding-UTF16 def /CMapType 2 def /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def 1 begincodespacerange <00> endcodespacerange 1 beginbfchar <1B> endbfchar endcmap CMapName currentdict /CMap defineresource pop ``` -------------------------------- ### Create XMP Metadata with pypdf Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/metadata.md Use the `XmpInformation.create()` method to easily create XMP metadata for a PDF. This is the starting point for adding custom XMP data. ```python from pypdf import PdfReader, PdfWriter from pypdf.metadata import XmpInformation reader = PdfReader("example.pdf") writer = PdfWriter() # Copy pages from reader to writer for page in reader.pages: writer.add_page(page) xmp = XmpInformation.create() xmp.title = "My PDF Title" xmp.author = "John Doe" xmp.subject = "Example Document" writer.add_metadata(xmp, "example_with_xmp.pdf") ``` -------------------------------- ### Transform Multiple Copies of a Page Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/cropping-and-transforming.md Create multiple instances of a page with transformations, useful for tasks like creating business card layouts. This example demonstrates positioning and requires manual adjustment of the source page's media box. ```python for i in range(4): for j in range(4): page.merge_page(source_page, offset=(i * page_width, j * page_height)) ``` -------------------------------- ### Basic PDF Reading with pypdf Source: https://github.com/py-pdf/pypdf/blob/main/README.md Demonstrates how to open a PDF file, get the number of pages, access a specific page, and extract text using the pypdf library. ```python from pypdf import PdfReader reader = PdfReader("example.pdf") number_of_pages = len(reader.pages) page = reader.pages[0] text = page.extract_text() ``` -------------------------------- ### Controlling Log Message Levels with 'logging' Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/suppress-warnings.md Shows how to set the logging level to control the verbosity of messages from the 'logging' module. This example sets the level to 'ERROR', meaning only critical errors will be displayed. ```python import logging logging.basicConfig(level=logging.ERROR) ``` -------------------------------- ### Initialize Git Submodule for Sample Files Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/intro.md Update and initialize the 'sample-files' git submodule to access extensive test case resources. ```bash git submodule update --init ``` -------------------------------- ### Initialize and Apply Transformation Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/Transformation.md Demonstrates creating a Transformation object, applying scale and translate operations, and adding it to a PDF page. ```python >>> from pypdf import PdfWriter, Transformation >>> page = PdfWriter().add_blank_page(800, 600) >>> op = Transformation().scale(sx=2, sy=3).translate(tx=10, ty=20) >>> page.add_transformation(op) ``` -------------------------------- ### Run Doctest Build Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/documentation.md Execute the documentation's doctest build using the 'make' command. This verifies code snippets within the documentation. ```bash make doctest ``` -------------------------------- ### Navigate to Docs Directory Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/documentation.md Change the current directory to the 'docs' folder. This is required before running documentation build commands. ```bash cd docs ``` -------------------------------- ### page_layout property Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PdfWriter.md Gets or sets the page layout property of the PDF document. ```APIDOC ## page_layout ### Description Page layout property. ### Valid `layout` values | /NoLayout | Layout explicitly not specified | |-----------------|------------------------------------------------------------| | /SinglePage | Show one page at a time | | /OneColumn | Show one column at a time | | /TwoColumnLeft | Show pages in two columns, odd-numbered pages on the left | | /TwoColumnRight | Show pages in two columns, odd-numbered pages on the right | | /TwoPageLeft | Show two pages at a time, odd-numbered pages on the left | | /TwoPageRight | Show two pages at a time, odd-numbered pages on the right | ``` -------------------------------- ### Text Stream Character Representation Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/cmaps.md Example of how characters are represented within a PDF text stream. ```text (The)-342(mis\034ts.) ``` -------------------------------- ### Add JavaScript to PDF Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PdfWriter.md Embeds JavaScript code that will execute when the PDF is opened. This example shows how to trigger the print dialog. ```python >>> from pypdf import PdfWriter >>> output = PdfWriter() >>> output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});") ``` -------------------------------- ### Download Test PDFs Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/testing.md Execute this command to download necessary PDF documents for tests that require the `enable_socket` marker. These files are stored locally after the first download. ```python from tests import download_test_pdfs; download_test_pdfs() ``` -------------------------------- ### Apply Multiple Transformations Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/Transformation.md Shows how to combine transformations, such as vertical and horizontal mirroring, by using the transform method. Ensure correct matrix values for desired effects. ```python >>> from pypdf import PdfWriter, Transformation >>> height, width = 40, 50 >>> page = PdfWriter().add_blank_page(800, 600) >>> op = Transformation((1, 0, 0, -1, 0, height)) # vertical mirror >>> op = Transformation().transform(Transformation((-1, 0, 0, 1, width, 0))) # horizontal mirror >>> page.add_transformation(op) ``` -------------------------------- ### set_page_label Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PdfWriter.md Sets a page label for a specified range of pages within a PDF document. This method allows customization of the label's style, prefix, and starting number. ```APIDOC ## set_page_label ### Description Set a page label to a range of pages. Page indexes must be given starting from 0. Labels must have a style, a prefix or both. If a range is not assigned any page label, a decimal label starting from 1 is applied. ### Method Signature `set_page_label(page_index_from: int, page_index_to: int, style: PageLabelStyle | None = None, prefix: str | None = None, start: int | None = 0) -> None` ### Parameters #### Path Parameters * **page_index_from** (int) - Required - Page index of the beginning of the range starting from 0. * **page_index_to** (int) - Required - Page index of the beginning of the range starting from 0. * **style** (PageLabelStyle | None) - Optional - The numbering style to be used for the numeric portion of each page label: * `/D` Decimal Arabic numerals * `/R` Uppercase Roman numerals * `/r` Lowercase Roman numerals * `/A` Uppercase letters (A to Z for the first 26 pages, AA to ZZ for the next 26, and so on) * `/a` Lowercase letters (a to z for the first 26 pages, aa to zz for the next 26, and so on) * **prefix** (str | None) - Optional - The label prefix for page labels in this range. * **start** (int | None) - Optional - The value of the numeric portion for the first page label in the range. Subsequent pages are numbered sequentially from this value, which must be greater than or equal to 1. Default value: 1. ``` -------------------------------- ### Create and push release tag Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/releasing.md Sign and push the release tag to the repository to trigger the CI release process. ```bash git tag -s 6.7.1 -eF RELEASE_COMMIT_MSG.md git push origin 6.7.1 ``` -------------------------------- ### PageObject.images Source: https://context7.com/py-pdf/pypdf/llms.txt Access and extract images from a page. Each ImageFile object provides access to the image name, raw data, and a PIL Image object if Pillow is installed. The .replace() method allows for in-place substitution of images. ```APIDOC ## PageObject.images ### Description Access and extract images from a page. Each `ImageFile` object provides access to the image name, raw data, and a PIL Image object if Pillow is installed. The `.replace()` method allows for in-place substitution of images. ### Usage ```python from pypdf import PdfReader, PdfWriter from PIL import Image # Extract all images from a PDF reader = PdfReader("document.pdf") for page_num, page in enumerate(reader.pages): for img_index, img in enumerate(page.images): print(f"Page {page_num}, image {img_index}: {img.name}, {len(img.data)} bytes") # Save to disk with open(f"page{page_num}_img{img_index}{img.name[-4:]}", "wb") as f: f.write(img.data) # Access as PIL Image if img.image: print(f" Size: {img.image.size}, Mode: {img.image.mode}") # Replace an image in a writer writer = PdfWriter(clone_from="document.pdf") new_image = Image.open("replacement.jpg") writer.pages[0].images[0].replace(new_image, quality=85) writer.write("replaced_images.pdf") ``` ``` -------------------------------- ### Create release commit Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/releasing.md Commit the changes using the prepared release commit message. ```bash git commit -eF RELEASE_COMMIT_MSG.md ``` -------------------------------- ### Modify XMP Metadata Structure with pypdf Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/metadata.md When modifying the XMP metadata structure, particularly for complex additions like PDF/UA identifiers, you can directly manipulate the XML structure. This example shows adding a PDF/UA identifier section. ```python from pypdf import PdfReader, PdfWriter from pypdf.metadata import XmpInformation reader = PdfReader("example.pdf") writer = PdfWriter() # Copy pages from reader to writer for page in reader.pages: writer.add_page(page) xmp = reader.xmp_metadata # Add PDF/UA identifier section xmp.add_xml_element( "pdfuaid", "http://www.aiim.org/pdfua/ns/id/", " 1 " ) writer.add_metadata(xmp, "example_modified_xmp.pdf") ``` -------------------------------- ### Create or Modify a PDF File with PdfWriter Source: https://context7.com/py-pdf/pypdf/llms.txt Creates a writer from scratch or by cloning a source PDF. Use `clone_from` to copy and modify. `incremental=True` appends changes without re-writing the full document, preserving digital signatures. ```python from pypdf import PdfWriter, PdfReader # Create a new empty PDF writer = PdfWriter() writer.add_blank_page(width=595, height=842) # A4 portrait in points writer.write("blank.pdf") # Clone an existing PDF and modify it writer = PdfWriter(clone_from="original.pdf") # Remove the last page writer.pages.pop() with open("modified.pdf", "wb") as f: writer.write(f) # Incremental update (preserves digital signatures) writer = PdfWriter("signed_form.pdf", incremental=True) writer.update_page_form_field_values(writer.pages[0], {"Name": "Alice"}) with open("filled_signed.pdf", "ab") as f: writer.write(f) ``` -------------------------------- ### Update release version and changelog Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/releasing.md Run this script to automatically update the CHANGELOG.md and _version.py files and prepare the release commit message. ```bash python make_release.py ``` -------------------------------- ### Accessing and iterating images on a page Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PageObject.md Demonstrates how to access images on a page using indices, keys, or iteration. ```python 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 ``` -------------------------------- ### XmpInformation Class Methods Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/XmpInformation.md Methods for creating, writing, and querying XMP metadata elements. ```APIDOC ## Class: XmpInformation ### Description Represents Extensible Metadata Platform (XMP) metadata for a PDF document. ### Methods - **create()**: Class method to create a new XmpInformation object with minimal structure. - **write_to_stream(stream, encryption_key)**: Writes the metadata to a stream. - **get_element(about_uri, namespace, name)**: Retrieves specific metadata elements. - **get_nodes_in_namespace(about_uri, namespace)**: Retrieves all nodes within a specific namespace. ``` -------------------------------- ### PdfWriter Initialization Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PdfWriter.md Initializes a PdfWriter object. It can be used to write a new PDF or to clone an existing one. ```APIDOC ## PdfWriter ### Description Initializes a PdfWriter object. It can be used to write a new PDF or to clone an existing one. ### Parameters * **fileobj**: The file object to write the PDF to. Defaults to an empty string. * **clone_from**: An existing PdfReader object or file path to clone from. If provided, the new PDF will be a copy of this source. * **incremental**: If true, loads the document and set the PdfWriter in incremental mode. New/modified content is appended to the original document. * **full**: If true, loads all the objects. This parameter may allow loading large PDFs. Always full if incremental = True. * **strict**: If true, pypdf will raise an exception if a PDF does not follow the specification. If false, pypdf will try to be forgiving and log a warning message. * **incremental_clone_object_count_limit**: Limit for cloning object count in incremental mode. * **incremental_clone_object_id_limit**: Limit for cloning object ID in incremental mode. ``` -------------------------------- ### Ignoring Warnings with the 'warnings' Module Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/suppress-warnings.md Demonstrates how to ignore all warnings using Python's built-in 'warnings' module. This can be useful for cleaner output, but consider the implications for debugging. ```python import warnings warnings.filterwarnings("ignore") ``` -------------------------------- ### Set XMP Metadata Fields with pypdf Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/metadata.md Access and set various XMP metadata fields using property-based access on the `XmpInformation` object. This includes Dublin Core, XMP, PDF, PDF/A, and Media Management fields. ```python from pypdf import PdfReader, PdfWriter from pypdf.metadata import XmpInformation reader = PdfReader("example.pdf") writer = PdfWriter() # Copy pages from reader to writer for page in reader.pages: writer.add_page(page) xmp = XmpInformation() xmp.title = "My PDF Title" xmp.author = "John Doe" xmp.subject = "Example Document" xmp.creator = "My Application" xmp.producer = "My Application" xmp.creation_date = "2023-10-27T10:00:00Z" xmp.mod_date = "2023-10-27T10:00:00Z" xmp.keywords = ["example", "pdf", "metadata"] xmp.language = "en-US" xmp.pdf_version = "1.7" xmp.pdf_part = "1" xmp.pdfa_id = "1" xmp.pdfa_part = "1" xmp.pdfa_conformance = "B" writer.add_metadata(xmp, "example_with_xmp.pdf") ``` -------------------------------- ### Add Highlight and Link Annotations Source: https://context7.com/py-pdf/pypdf/llms.txt Demonstrates adding a highlight annotation with a specific color and a hyperlink to a PDF page. Ensure the page number and annotation rectangle are correctly defined. ```python writer.add_annotation( page_number=0, annotation=Highlight( rect=(50, 500, 400, 520), quad_points=ArrayObject([ FloatObject(50), FloatObject(520), FloatObject(400), FloatObject(520), FloatObject(50), FloatObject(500), FloatObject(400), FloatObject(500), ]), highlight_color="ffff00", ), ) # External hyperlink writer.add_annotation( page_number=0, annotation=Link( rect=(100, 400, 300, 420), url="https://example.com", ), ) writer.write("annotated.pdf") ``` -------------------------------- ### Adding and Inserting Blank Pages with PaperSize Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PaperSize.md Demonstrates how to add or insert blank pages into a PDF document using predefined PaperSize constants. ```APIDOC ## Add blank page with PaperSize ## Insert blank page with PaperSize ``` -------------------------------- ### PdfReader Initialization Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PdfReader.md Initializes a PdfReader object to read PDF files. It can accept file-like objects, paths, or byte streams. Options include strict mode, password for decryption, and recovery limits for corrupted files. ```APIDOC ## PdfReader Initialization ### Description Initializes a PdfReader object. This operation can take some time as the PDF stream's cross-reference tables are read into memory. ### Parameters * **stream** (str | IO[Any] | Path) - A file object or an object that supports standard read and seek methods, or a string representing a path to a PDF file. * **strict** (bool) - Determines whether to warn about all problems and treat some correctable problems as fatal. Defaults to `False`. * **password** (None | str | bytes) - Password to decrypt the PDF file at initialization. Defaults to `None`. * **root_object_recovery_limit** (int | None) - The maximum number of objects to query for recovering the Root object in non-strict mode. Pass `None` to disable this security measure. Defaults to `10000`. ``` -------------------------------- ### Apply Lossless Compression to Page Content Streams Source: https://github.com/py-pdf/pypdf/blob/main/docs/user/file-size.md Compress a page's content streams using `page.compress_content_streams()` with zlib/deflate. The `level` parameter controls compression strength (0-9). ```python page.compress_content_streams(level=9) ``` -------------------------------- ### Fit Class Methods Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/Fit.md Methods for creating Fit objects to control page display behavior. ```APIDOC ## Class: pypdf.generic.Fit ### Description The Fit class provides class methods to define how a page is displayed in a PDF viewer, including magnification and positioning. ### Methods - **xyz(left, top, zoom)**: Displays page with coordinates (left, top) at upper-left corner, magnified by zoom. - **fit()**: Magnifies page to fit entirely within the window. - **fit_horizontally(top)**: Fits page width to window, positioning vertical coordinate top at the top edge. - **fit_vertically(left)**: Fits page height to window, positioning horizontal coordinate left at the left edge. - **fit_rectangle(left, bottom, right, top)**: Magnifies to fit the specified rectangle within the window. - **fit_box()**: Magnifies to fit the page bounding box within the window. - **fit_box_horizontally(top)**: Fits bounding box width to window, positioning vertical coordinate top at the top edge. - **fit_box_vertically(left)**: Fits bounding box height to window, positioning horizontal coordinate left at the left edge. ### Returns - All methods return a `Fit` object. ``` -------------------------------- ### Open and Parse a PDF File with PdfReader Source: https://context7.com/py-pdf/pypdf/llms.txt Opens a PDF from a file path, file-like object, or BytesIO. Use as a context manager for proper stream closure. Handles encrypted PDFs with a password. ```python from pypdf import PdfReader # Open a file by path with PdfReader("document.pdf") as reader: print(f"PDF version: {reader.pdf_header}") # '%PDF-1.7' print(f"Number of pages: {len(reader.pages)}") meta = reader.metadata if meta: print(f"Title: {meta.title}") print(f"Author: {meta.author}") print(f"Created: {meta.creation_date}") # Open an encrypted PDF reader = PdfReader("secure.pdf", password="secret") print(reader.pages[0].extract_text()) # Open from a BytesIO buffer import io with open("document.pdf", "rb") as f: data = f.read() reader = PdfReader(io.BytesIO(data)) print(len(reader.pages)) ``` -------------------------------- ### pypdf API Renaming Reference Source: https://github.com/py-pdf/pypdf/blob/main/docs/meta/migration-1-to-2.md A comprehensive list of API changes and refactored method names across the pypdf library. ```APIDOC ## API Migration Reference ### Description This section outlines the transition from legacy camelCase naming conventions to the updated snake_case conventions in pypdf. ### PdfReader Changes - `reader.getPage(pageNumber)` -> `reader.pages[page_number]` - `reader.getNumPages()` / `reader.numPages` -> `len(reader.pages)` - `getDocumentInfo` -> `metadata` - `getOutlines` -> `get_outlines` ### PdfWriter Changes - `writer.getPage(pageNumber)` -> `writer.pages[page_number]` - `writer.getNumPages()` -> `len(writer.pages)` - `addMetadata` -> `add_metadata` - `addPage` -> `add_page` - `addAttachment(fname, fdata)` -> `add_attachment(filename, data)` ### Page Class Changes - `artBox` / `bleedBox` / `cropBox` / `mediaBox` / `trimBox` -> `artbox` / `bleedbox` / `cropbox` / `mediabox` / `trimbox` - `getWidth` / `getHeight` -> `width` / `height` - `mergePage` -> `merge_page` - `rotateClockwise` -> `rotate_clockwise` ``` -------------------------------- ### NameObject Static Methods Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/generic.md Details static methods for NameObject, including reading from a stream. ```APIDOC ## read_from_stream ### Description Reads a NameObject from a stream. ### Parameters - **stream**: The IO stream to read from. - **pdf**: The PDF document object. ### Returns [NameObject](#pypdf.generic.NameObject): The read NameObject. ``` -------------------------------- ### XmpInformationProtocol Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/generic.md Protocol for XMP (Extensible Metadata Platform) information, inheriting from PdfObjectProtocol. ```APIDOC ## class pypdf._protocols.XmpInformationProtocol(*args, **kwargs) Bases: [`PdfObjectProtocol`](#pypdf._protocols.PdfObjectProtocol) ``` -------------------------------- ### PDF Information and Navigation Methods Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PdfReader.md Methods for retrieving document-level information, page counts, and navigation structures. ```APIDOC ## get_num_pages() ### Description Calculate the number of pages in this PDF file. ### Returns - **int** - The number of pages of the parsed PDF file. ### Raises - **PdfReadError** - If restrictions prevent this action. ## get_page(page_number: int) ### Description Retrieve a page by number from this PDF file. ### Parameters #### Path Parameters - **page_number** (int) - Required - The page number to retrieve (pages begin at zero). ### Returns - **PageObject** - A PageObject instance. ``` -------------------------------- ### Contributor entry format options Source: https://github.com/py-pdf/pypdf/blob/main/docs/meta/CONTRIBUTORS.md Use these formats to add a contributor entry in alphabetical order. Ensure the text after the name/username does not exceed 140 characters. ```default * Last name, First name: 140-characters of text; links to LinkedIn / GitHub / other profiles and personal pages are ok ``` ```default * GitHub Username: 140-characters of text; links to LinkedIn / GitHub / other profiles and personal pages are ok ``` -------------------------------- ### PdfWriterProtocol Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/generic.md Protocol for PDF writers, extending PdfCommonDocProtocol. ```APIDOC ## class pypdf._protocols.PdfWriterProtocol(*args, **kwargs) Bases: [`PdfCommonDocProtocol`](#pypdf._protocols.PdfCommonDocProtocol), `Protocol` #### incremental *: bool* #### abstractmethod write(stream: Path | str | IO[Any]) -> tuple[bool, IO[Any]] ``` -------------------------------- ### Run pypdf tests with pytest Source: https://github.com/py-pdf/pypdf/blob/main/README.md Execute the pypdf test suite using pytest. This command will run all collected tests and report the results. ```bash $ pytest ===================== test session starts ===================== platform linux -- Python 3.6.15, pytest-7.0.1, pluggy-1.0.0 rootdir: /home/moose/GitHub/Martin/pypdf plugins: cov-3.0.0 collected 233 items tests/test_basic_features.py .. [ 0%] tests/test_constants.py . [ 1%] tests/test_filters.py .................x..... [ 11%] tests/test_generic.py ................................. [ 25%] ............. [ 30%] tests/test_javascript.py .. [ 31%] tests/test_merger.py . [ 32%] tests/test_page.py ......................... [ 42%] tests/test_pagerange.py ................ [ 49%] tests/test_papersizes.py .................. [ 57%] tests/test_reader.py .................................. [ 72%] ............... [ 78%] tests/test_utils.py .................... [ 87%] tests/test_workflows.py .......... [ 91%] tests/test_writer.py ................. [ 98%] tests/test_xmp.py ... [100%] ========== 232 passed, 1 xfailed, 1 warning in 4.52s ========== ``` -------------------------------- ### OutlineItem Method Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/generic.md Method for OutlineItem to write its representation to a stream. ```APIDOC ## write_to_stream ### Description Writes the OutlineItem to a stream. ### Parameters - **stream**: The IO stream to write to. - **encryption_key** (None | str | bytes, optional): The encryption key to use. Defaults to None. ``` -------------------------------- ### Uncompress PDF with pdftk Source: https://github.com/py-pdf/pypdf/blob/main/docs/dev/cmaps.md Use this command to uncompress a PDF file to inspect its internal structure. ```bash pdftk crazyones.pdf output crazyones-uncomp.pdf uncompress ``` -------------------------------- ### Password-Protect and Decrypt PDF Files Source: https://context7.com/py-pdf/pypdf/llms.txt Encrypt a PDF document with user and owner passwords, optionally restricting permissions. Demonstrates how to decrypt a protected PDF for reading. ```python from pypdf import PdfWriter from pypdf.constants import UserAccessPermissions writer = PdfWriter(clone_from="document.pdf") # Basic encryption with AES-256 writer.encrypt(user_password="user123", owner_password="owner456", algorithm="AES-256") writer.write("encrypted.pdf") # Restrict permissions — print only, no copy or modify permissions = UserAccessPermissions.PRINT | UserAccessPermissions.PRINT_HIGH_QUALITY writer2 = PdfWriter(clone_from="document.pdf") writer2.encrypt( user_password="readonly", owner_password="admin_secret", permissions_flag=permissions, algorithm="AES-256", ) writer2.write("restricted.pdf") # Decrypt a protected PDF for reading from pypdf import PdfReader reader = PdfReader("encrypted.pdf", password="user123") print(reader.pages[0].extract_text()) ``` -------------------------------- ### Page Transformation and Scaling API Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PageObject.md Methods for applying transformations, scaling, and resizing pages. ```APIDOC ## add_transformation ### Description Applies a transformation matrix to the page. See [Cropping and Transforming PDFs](../user/cropping-and-transforming.md). ### Method This is a method of a PageObject. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python page.add_transformation(ctm=transformation_matrix) ``` ### Response #### Success Response (200) None (This method returns None) #### Response Example None ``` ```APIDOC ## scale ### Description Scales a page by the given factors by applying a transformation matrix to its content and updating the page size. This updates the various page boundaries (bleedbox, trimbox, etc.) and the contents of the page. ### Method This is a method of a PageObject. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python page.scale(sx=0.5, sy=0.5) ``` ### Response #### Success Response (200) None (This method returns None) #### Response Example None ``` ```APIDOC ## scale_by ### Description Scales a page by the given factor by applying a transformation matrix to its content and updating the page size. ### Method This is a method of a PageObject. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python page.scale_by(factor=2.0) ``` ### Response #### Success Response (200) None (This method returns None) #### Response Example None ``` ```APIDOC ## scale_to ### Description Scales a page to the specified dimensions by applying a transformation matrix to its content and updating the page size. ### Method This is a method of a PageObject. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python page.scale_to(width=600, height=800) ``` ### Response #### Success Response (200) None (This method returns None) #### Response Example None ``` -------------------------------- ### Contributor entry format using name Source: https://github.com/py-pdf/pypdf/blob/main/CONTRIBUTORS.md Use this format to list a contributor by their full name. ```text * Last name, First name: 140-characters of text; links to LinkedIn / GitHub / other profiles and personal pages are ok ``` -------------------------------- ### PdfDocCommon Class Overview Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/PdfDocCommon.md This section details the PdfDocCommon class, its properties, and abstract methods. ```APIDOC ## class pypdf._doc_common.PdfDocCommon ### Description Common functions from PdfWriter and PdfReader objects. This root class is strongly abstracted. ### Properties - **strict** (bool, optional, default=False) - **flattened_pages** (list[PageObject] | None, optional, default=None) - **root_object** (abstract property, DictionaryObject) - Abstract property representing the root object. - **pdf_header** (abstract property, str) - Abstract property representing the PDF header. - **metadata** (DocumentInformation | None, optional) - Retrieves the PDF file’s document information dictionary, if it exists. Note that some PDF files use metadata streams instead of document information dictionaries, and these metadata streams will not be accessed by this function. - **xmp_metadata** (XmpInformation | None, optional) - **viewer_preferences** (ViewerPreferences | None, optional) - Returns the existing ViewerPreferences as an overloaded dictionary. - **named_destinations** (dict[str, Destination]) - A read-only dictionary which maps names to destinations. - **open_destination** (None | Destination | TextStringObject | ByteStringObject, optional) - Property to access the opening destination (`/OpenAction` entry in the PDF catalog). It returns `None` if the entry does not exist or is not set. Raises Exception if a destination is invalid. ### Methods - **get_object(indirect_reference: int | IndirectObject) -> PdfObject | None** - Retrieves an object by its indirect reference. - **get_num_pages() -> int** - Calculate the number of pages in this PDF file. Returns the number of pages of the parsed PDF file. Raises PdfReadError if restrictions prevent this action. - **get_page(page_number: int) -> PageObject** - Retrieve a page by number from this PDF file. Most of the time `.pages[page_number]` is preferred. Parameters: page_number (int) - The page number to retrieve (pages begin at zero). Returns: A PageObject instance. - **get_named_dest_root() -> ArrayObject** - Retrieves the root of named destinations. - **get_fields(tree: TreeObject | None = None, retval: dict[Any, Any] | None = None, fileobj: Any | None = None, stack: list[PdfObject] | None = None) -> dict[str, Any] | None** - Extract field data if this PDF contains interactive form fields. The tree, retval, stack parameters are for recursive use. Parameters: tree (TreeObject | None) - Current object to parse. retval (dict[Any, Any] | None) - In-progress list of fields. fileobj (Any | None) - A file object (usually a text file) to write a report to on all interactive form fields found. stack (list[PdfObject] | None) - List of already parsed objects. Returns: A dictionary where each key is a field name, and each value is a Field object. By default, the mapping name is used for keys. None if form data could not be located. - **get_form_text_fields(full_qualified_name: bool = False) -> dict[str, Any]** - Retrieve form fields from the document with textual data. Parameters: full_qualified_name (bool, optional, default=False) - to get full name. Returns: A dictionary. The key is the name of the form field, the value is the content of the field. If the document contains multiple form fields with the same name, the second and following will get the suffix .2, .3, … - **get_pages_showing_field(field: Field | PdfObject | IndirectObject) -> list[PageObject]** - Provides list of pages where the field is called. Parameters: field (Field | PdfObject | IndirectObject) - Field Object, PdfObject or IndirectObject referencing a Field. Returns: List of pages - Empty list: The field has no widgets attached (either hidden field or ancestor field). Single page list: Page where the widget is present (most common). Multi-page list: Field with multiple kids widgets (example: radio buttons, field repeated on multiple pages). ``` -------------------------------- ### Contributor entry format using GitHub username Source: https://github.com/py-pdf/pypdf/blob/main/CONTRIBUTORS.md Use this format to list a contributor by their GitHub username. ```text * GitHub Username: 140-characters of text; links to LinkedIn / GitHub / other profiles and personal pages are ok ``` -------------------------------- ### PdfObject Methods Source: https://github.com/py-pdf/pypdf/blob/main/docs/modules/generic.md Provides details on common methods available for PdfObject and its subclasses, such as cloning, hashing, and writing to streams. ```APIDOC ## clone ### Description Clone object into pdf_dest. ### Parameters - **pdf_dest**: The destination object to clone into. - **force_duplicate** (bool, optional): Whether to force duplication. Defaults to False. - **ignore_fields** (Sequence[str | int] | None, optional): Fields to ignore during cloning. Defaults to None. ### Returns [PdfObject](#pypdf.generic.PdfObject): The cloned object. ``` ```APIDOC ## hash_bin ### Description Used to detect modified object. ### Returns int: Hash considering type and value. ``` ```APIDOC ## write_to_stream ### Description Writes the object's data to a stream. ### Parameters - **stream**: The IO stream to write to. - **encryption_key** (None | str | bytes, optional): The encryption key to use. Defaults to None. ``` ```APIDOC ## replicate ### Description Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter) without ensuring links. This is used in clone_document_from_root with incremental = True. ### Parameters - **pdf_dest**: Target to clone to. ### Returns [PdfObject](#pypdf.generic.PdfObject): The cloned PdfObject ```