### Install Dependencies and Build Documentation Source: https://pikepdf.readthedocs.io/en/latest/source_build.html Installs project dependencies, documentation-specific dependencies, navigates to the docs directory, and builds the HTML documentation. ```bash uv pip install -e . uv pip install --group docs cd docs make html ``` -------------------------------- ### Starting with an Empty PDF Source: https://pikepdf.readthedocs.io/en/latest/topics/jobs.html Illustrates how to start a JobBuilder job with an empty PDF, similar to `qpdf --empty`. ```APIDOC ## Starting with an Empty PDF Use the `empty()` method to begin a job with a blank PDF, which is useful for creating new PDFs from scratch. ### Method ```python JobBuilder().empty().output('new.pdf').run() ``` ### Description - `empty()`: Initializes the job with a blank PDF. - `output(filename)`: Specifies the name for the new PDF file. - `run()`: Executes the job to create the empty PDF. ``` -------------------------------- ### Manual installation on FreeBSD Source: https://pikepdf.readthedocs.io/en/latest/installation.html Attempt a manual installation of pikepdf on FreeBSD by installing necessary dependencies and then using pip. This procedure is known to work on specific FreeBSD versions. ```bash pkg install python3 py311-lxml py311-pip py311-nanobind qpdf pip install --user pikepdf ``` -------------------------------- ### Set up virtual environment and install pikepdf Source: https://pikepdf.readthedocs.io/en/latest/source_build.html Creates and activates a Python virtual environment, then installs pikepdf in editable mode using custom qpdf build. Requires QPDF_SOURCE_TREE and QPDF_BUILD_LIBDIR environment variables. ```bash # Create a fresh virtual environment cd $PIKEPDF_SOURCE_TREE uv venv source .venv/bin/activate # Build pikepdf from source env QPDF_SOURCE_TREE=$QPDF_SOURCE_TREE QPDF_BUILD_LIBDIR=$QPDF_BUILD_LIBDIR \ uv pip install -e . ``` -------------------------------- ### Configure environment and install pikepdf on Windows Source: https://pikepdf.readthedocs.io/en/latest/source_build.html Sets up include and library paths for qpdf, copies the DLL, creates a virtual environment, and installs pikepdf in editable mode. Ensure $qpdf and $pikepdf variables point to the correct directories. ```powershell cd $pikepdf $env:INCLUDE = "$qpdf\include" $env:LIB = "$qpdf\build\libqpdf\Release\" cp $LIB\libqpdfXX.dll src\pikepdf # Help Python loader find libqpdf.dll uv venv .venv\scripts\activate uv pip install -e . ``` -------------------------------- ### Install pikepdf on Fedora Source: https://pikepdf.readthedocs.io/en/latest/installation.html Install pikepdf using the dnf package manager on Fedora. This method may provide a version that lags behind PyPI. ```bash dnf install python_pikepdf ``` -------------------------------- ### Install pikepdf on FreeBSD Source: https://pikepdf.readthedocs.io/en/latest/installation.html Install pikepdf using the pkg package manager on FreeBSD. This method may provide a version that lags behind PyPI. ```bash pkg install py311-pikepdf ``` -------------------------------- ### Standard Attribute Access Example Source: https://pikepdf.readthedocs.io/en/latest/topics/namepath.html Demonstrates standard attribute access for simple, shallow access where keys are known to exist. ```python >>> page.Type # Standard attribute access >>> page.Contents # Direct key on the page ``` -------------------------------- ### Install and Use py-spy for Profiling Source: https://pikepdf.readthedocs.io/en/latest/references/debugging.html Install py-spy and speedscope for profiling pikepdf code, including C++ execution. Generate speedscope files for analysis. ```bash # From a virtual environment with pikepdf installed... # Install pip install py-spy npm install -g speedscope # may need sudo to install this # Run profile on a script that executes some pikepdf code we want to profile py-spy record --native --format speedscope -o profile.speedscope -- python some_script.py # View results (this will open a browser window) speedscope profile.speedscope ``` -------------------------------- ### NamePath Construction Syntax Examples Source: https://pikepdf.readthedocs.io/en/latest/topics/namepath.html Illustrates various ways to construct NamePath objects, including shorthand, array indices, canonical syntax for non-Python identifiers, and chained construction. ```python >>> # Shorthand syntax (most common) >>> path = NamePath.Resources.Font.F1 >>> repr(path) 'NamePath.Resources.Font.F1' ``` ```python >>> # With array indices >>> path = NamePath.Pages.Kids[0].MediaBox >>> repr(path) 'NamePath.Pages.Kids[0].MediaBox' ``` ```python >>> # Canonical syntax (for non-Python-identifier names) >>> path = NamePath('/Resources', '/Weird-Name') >>> repr(path) 'NamePath.Resources.Weird-Name' ``` ```python >>> # Using Name objects >>> path = NamePath(Name.Resources, Name.Font) >>> repr(path) 'NamePath.Resources.Font' ``` ```python >>> # Chained construction >>> path = NamePath('/A')('/B').C[0] >>> repr(path) 'NamePath.A.B.C[0]' ``` -------------------------------- ### Install pikepdf for current user Source: https://pikepdf.readthedocs.io/en/latest/installation.html Install the pikepdf package for the current user only. This is useful when you do not have administrative privileges or want to avoid installing into a global environment. ```bash pip install --user pikepdf ``` -------------------------------- ### Install pikepdf on Alpine Linux Source: https://pikepdf.readthedocs.io/en/latest/installation.html Install pikepdf using the apk package manager on Alpine Linux. This method may provide a version that lags behind PyPI. ```bash apk add py3-pikepdf ``` -------------------------------- ### Install pikepdf on Debian/Ubuntu Source: https://pikepdf.readthedocs.io/en/latest/installation.html Install pikepdf using the apt package manager on Debian, Ubuntu, and other APT-based distributions. This method may provide a version that lags behind PyPI. ```bash apt install pikepdf ``` -------------------------------- ### PDF Content Stream Example Source: https://pikepdf.readthedocs.io/en/latest/topics/content_streams.html A typical PDF content stream demonstrating graphics stack manipulation and drawing commands. The pattern 'q, cm, , Q' is common. ```pdf q % 1. Push graphics stack. 100 0 0 100 0 0 cm % 2. The 6 numbers are the operands, followed by cm operator. % This configures the current transformation matrix. /Image1 Do % 3. Draw the object named /Image1 from the /Resources % dictionary. Q % 4. Pop graphics stack. ``` -------------------------------- ### Set up Visual Studio Environment for Pikepdf Build on Windows Source: https://pikepdf.readthedocs.io/en/latest/source_build.html These commands set up the necessary environment variables to use Visual Studio 2015 for building pikepdf on Windows. This is required before running the pip install command. ```batch %VS140COMNTOOLS%\..\..\VC\vcvarsall.bat" x64 set DISTUTILS_USE_SDK=1 set MSSdk=1 ``` -------------------------------- ### Build Pikepdf with Custom qpdf Location Source: https://pikepdf.readthedocs.io/en/latest/source_build.html Use this command to build pikepdf when qpdf headers and libraries are installed in a custom location like /usr/local. Ensure qpdf is built and installed prior to running this command. ```bash env CXXFLAGS=-I/usr/local/include/libqpdf LDFLAGS=-L/usr/local/lib \ uv pip install . ``` -------------------------------- ### Handling Missing Keys with NamePath.get() Source: https://pikepdf.readthedocs.io/en/latest/topics/namepath.html Illustrates using the `get()` method with NamePath to safely retrieve values, returning `None` or a custom default if the path does not exist or encounters type mismatches. This is useful for accessing potentially missing intermediate dictionaries. ```python >>> pdf = Pdf.new() >>> # Returns None when path doesn't exist >>> pdf.Root.get(NamePath.Missing.Path) is None True >>> # Returns custom default >>> pdf.Root.get(NamePath.Missing.Path, "not found") 'not found' ``` ```python >>> # Safe access - returns default if any part of path is missing >>> font = page.get(NamePath.Resources.Font.F1, None) >>> if font is not None: ... # Process the font ``` -------------------------------- ### Track Current Transformation Matrix (CTM) Source: https://pikepdf.readthedocs.io/en/latest/api/filters.html Manages the CTM in a PDF content stream, starting with an initial matrix and updating it via 'cm' operators. The 'q' and 'Q' operators save and restore the CTM to a stack. ```python import pikepdf # The MatrixStack class is used internally to track CTM. # Example usage would involve interacting with content stream parsing or manipulation. # For direct instantiation: # from pikepdf.models.ctm import MatrixStack # matrix_stack = MatrixStack() ``` -------------------------------- ### Create a Job instance Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Instantiate a Job object with command-line arguments for the qpdf program. The first argument should be the program name, typically 'pikepdf'. ```python job = Job([‘pikepdf’, ‘–check’, ‘input.pdf’]) job.run() ``` -------------------------------- ### Build libqpdf from source Source: https://pikepdf.readthedocs.io/en/latest/source_build.html Builds the libqpdf library from its source code. Ensure QPDF_SOURCE_TREE and PIKEPDF_SOURCE_TREE environment variables are set. ```bash # Build libqpdf from source cd $QPDF_SOURCE_TREE cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_SHARED_LIBS=ON cmake --build build --parallel --target libqpdf QPDF_BUILD_LIBDIR=$PWD/build/libqpdf ``` -------------------------------- ### Install pikepdf with pip Source: https://pikepdf.readthedocs.io/en/latest/installation.html Use pip to install pikepdf in your current Python environment. This is the recommended method for most users on Linux, macOS, and Windows x64 systems. ```bash pip install pikepdf ``` -------------------------------- ### run(_*_ , _validate =True_) Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Builds and runs the job, with an option to validate the configuration first. ```APIDOC ## run(_*_ , _validate =True_) ### Description Build and run the job. ### Method (Not specified, likely a method call on a JobBuilder object) ### Parameters #### Path Parameters - **validate** (bool) - Optional - If True (default), call `check_configuration()` before running to fail fast on invalid configurations. ### Endpoint (Not applicable, this is an SDK method) ### Returns The `pikepdf.Job` after running, so callers can inspect `exit_code`, `has_warnings` and `encryption_status`. ### Return type pikepdf._core.Job ``` -------------------------------- ### Object Construction Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Demonstrates the parameters required for object construction. ```APIDOC ## Object construction Parameters: **possible_owner** (_Pdf_) Return type: bool ``` -------------------------------- ### new Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Creates a new, empty PDF document. This is recommended for constructing PDFs from scratch. ```APIDOC ## classmethod new() ### Description Create a new, empty PDF. This is best when you are constructing a PDF from scratch. In most cases, if you are working from an existing PDF, you should open the PDF using `pikepdf.Pdf.open()` and transform it, instead of a creating a new one, to preserve metadata and structural information. For example, if you want to split a PDF into two parts, you should open the PDF and transform it into the desired parts, rather than creating a new PDF and copying pages into it. ### Return Type Pdf ``` -------------------------------- ### keys Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Gets the keys of the object, if it is a Dictionary or Stream. ```APIDOC ## keys() Get the keys of the object, if it is a Dictionary or Stream. Return type: set[str] ``` -------------------------------- ### Configure and Apply Sanitizer Operations Source: https://pikepdf.readthedocs.io/en/latest/api/sanitize.html Demonstrates configuring a Sanitizer instance with multiple removal operations and applying it to multiple PDF files. The Sanitizer allows for efficient reuse across many documents. ```python scrubber = ( pikepdf.sanitize.Sanitizer() .remove_javascript() .remove_external_access() .remove_attachments() ) for path in untrusted_paths: with pikepdf.open(path) as pdf: scrubber.apply(pdf).save(out_dir / path.name) ``` -------------------------------- ### Initialize PDF and Access Nested Value with NamePath Source: https://pikepdf.readthedocs.io/en/latest/topics/namepath.html Demonstrates initializing a new PDF, setting nested dictionary structures, and then accessing a value using NamePath. Requires importing Pdf, Dictionary, Array, Name, and NamePath. ```python >>> from pikepdf import Pdf, Dictionary, Array, Name, NamePath >>> pdf = Pdf.new() >>> pdf.Root.Resources = Dictionary( ... Font=Dictionary(F1=Name.Helvetica), ... XObject=Dictionary() ... ) >>> # Access nested value with NamePath >>> pdf.Root[NamePath.Resources.Font.F1] pikepdf.Name("/Helvetica") ``` -------------------------------- ### unscaled_char_width(_char_) Source: https://pikepdf.readthedocs.io/en/latest/api/canvas.html Gets the unscaled width of a character in glyph-space units. ```APIDOC ## unscaled_char_width(_char_) ### Description 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 ``` -------------------------------- ### Basic JobBuilder Usage Source: https://pikepdf.readthedocs.io/en/latest/topics/jobs.html Demonstrates the basic chaining of input, output, and processing operations using JobBuilder. This is equivalent to running `qpdf --linearize in.pdf out.pdf`. ```APIDOC ## Basic JobBuilder Usage This example shows how to create a new job, specify input and output files, apply an operation like linearization, and then run the job. ### Method ```python JobBuilder().input('in.pdf').output('out.pdf').linearize().run() ``` ### Description - `input(filename)`: Sets the input PDF file. - `output(filename)`: Sets the output PDF file. - `linearize()`: Applies PDF linearization to the output file. - `run()`: Executes the defined job. ``` -------------------------------- ### Get Number of Pages Source: https://pikepdf.readthedocs.io/en/latest/tutorial.html Checks the current number of pages in the PDF document after modifications. ```python >>> len(pdf.pages) 2 ``` -------------------------------- ### Get the number of pages in a PDF Source: https://pikepdf.readthedocs.io/en/latest/tutorial.html Retrieves the total number of pages in an opened PDF document. ```python len(pdf.pages) ``` -------------------------------- ### is_linearized Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Determines if the PDF document is linearized. Returns True if the file starts with a linearization parameter dictionary. ```APIDOC ## property is_linearized: bool ### Description Returns True if the PDF is linearized. Specifically returns True iff the file starts with a linearization parameter dictionary. Does no additional validation. ### Return Type bool ``` -------------------------------- ### Generate Job JSON Specification Source: https://pikepdf.readthedocs.io/en/latest/topics/jobs.html Use `to_json()` to get a dictionary representation of the job specification, useful for debugging or caching. ```python >>> JobBuilder().input('in.pdf').output('out.pdf').linearize().to_json() {'inputFile': 'in.pdf', 'outputFile': 'out.pdf', 'linearize': ''} ``` -------------------------------- ### Build pikepdf._core Against Local qpdf Source: https://pikepdf.readthedocs.io/en/latest/references/debugging.html Build the pikepdf C++ extension against a locally compiled qpdf source tree. Set QPDF_SOURCE_TREE and QPDF_BUILD_LIBDIR environment variables. ```bash env QPDF_SOURCE_TREE= \ QPDF_BUILD_LIBDIR= \ python setup.py build_ext --inplace ``` -------------------------------- ### Create a PDF Matrix Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Initialize a 2D affine matrix for PDF transformations. Matrices are used to transform document coordinates. ```python matrix = pikepdf.Matrix() ``` -------------------------------- ### Get Matrix Elements Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Access individual elements of a PDF transformation matrix. These elements represent scaling, skewing, and translation factors. ```python a = matrix.a b = matrix.b c = matrix.c d = matrix.d e = matrix.e f = matrix.f ``` -------------------------------- ### Create and Linearize a PDF Job Source: https://pikepdf.readthedocs.io/en/latest/topics/jobs.html Chains methods to create a new PDF job, specify input and output files, linearize the PDF, and run the job. Equivalent to `qpdf --linearize in.pdf out.pdf`. ```python from pikepdf import JobBuilder JobBuilder().input('in.pdf').output('out.pdf').linearize().run() ``` -------------------------------- ### Update PDF Metadata Source: https://pikepdf.readthedocs.io/en/latest/api/models.html Use a with block to open and update PDF metadata. This example shows how to change the 'dc:title' field. ```python with pdf.open_metadata() as records: records['dc:title'] = 'New Title' ``` -------------------------------- ### Convert Matrix to NumPy Array Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Convert a pikepdf.Matrix object to a NumPy ndarray. This requires the NumPy library to be installed. A copy is made by default. ```python numpy_array = matrix.__array__(copy=True) ``` -------------------------------- ### Accessing and Inspecting a Name Tree Source: https://pikepdf.readthedocs.io/en/latest/topics/nametrees.html Demonstrates how to open a PDF, instantiate a NameTree object from a PDF root entry, and iterate through its keys and values. This is useful for understanding the structure of named elements within a PDF. ```python from pikepdf import Pdf, NameTree pdf = Pdf.open('../tests/resources/outlines.pdf') nt = NameTree(pdf.Root.Names.Dests) print([k for k in nt.keys()]) nt['2'][0].objgen, nt['2'][1], nt['2'][2] ``` -------------------------------- ### Get Page Rotation Source: https://pikepdf.readthedocs.io/en/latest/topics/page.html Retrieves the effective rotation of a page, resolving inherited values and normalizing to [0, 360). Returns 0 if no rotation is set. ```python >>> page1.rotation 0 ``` -------------------------------- ### Merge PDFs (Basic) Source: https://pikepdf.readthedocs.io/en/latest/topics/pages.html Concatenates multiple PDF files into a single PDF document. This basic example merges pages from all PDFs in the current directory. ```python from glob import glob pdf = Pdf.new() for file in glob('*.pdf'): src = Pdf.open(file) pdf.pages.extend(src.pages) pdf.save('merged.pdf') ``` -------------------------------- ### Initialize Form with Appearance Stream Generator Source: https://pikepdf.readthedocs.io/en/latest/topics/interactive_forms.html Instantiate a Form object, optionally providing a class for generating appearance streams. If no generator is provided, appearance streams are not generated by default. ```python from pikepdf.form import Form, DefaultAppearanceStreamGenerator form = Form(pdf, DefaultAppearanceStreamGenerator) ``` -------------------------------- ### Get Matrix Shorthand Tuple Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Retrieve the six elements of the matrix as a tuple (a, b, c, d, e, f). This provides a convenient way to access all matrix parameters at once. ```python shorthand_tuple = matrix.shorthand ``` -------------------------------- ### Get Objects with Current Transformation Matrix (CTM) Source: https://pikepdf.readthedocs.io/en/latest/api/filters.html Determines the CTM for each drawn object on a page and filters out objects with an invalid CTM. Useful for analyzing graphical elements and their transformations. ```python import pikepdf # with pikepdf.Pdf.open("../tests/resources/pal-1bit-trivial.pdf") as pdf: # page = pdf.pages[0] # objects_with_ctm = pikepdf.get_objects_with_ctm(page) # for obj_data, ctm in objects_with_ctm: # print(f"Object: {obj_data}, CTM: {ctm}") ``` -------------------------------- ### Open PDF using a context manager Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Use a 'with' statement to ensure the PDF file is properly closed after operations. This is the recommended way to open files. ```python with Pdf.open("test.pdf") as pdf: pass ``` -------------------------------- ### Setting Nested Values with NamePath Source: https://pikepdf.readthedocs.io/en/latest/topics/namepath.html Demonstrates setting nested values using NamePath. The parent path must already exist for the operation to succeed. ```python >>> pdf = Pdf.new() >>> pdf.Root.Info = Dictionary() >>> pdf.Root[NamePath.Info.Author] = pikepdf.String("Alice") >>> pdf.Root.Info.Author pikepdf.String("Alice") ``` -------------------------------- ### Replacing Input File Source: https://pikepdf.readthedocs.io/en/latest/topics/jobs.html Shows how to use `replace_input()` to modify the input file in place, analogous to qpdf's in-place editing. ```APIDOC ## Replacing Input File The `replace_input()` method allows you to modify the input PDF directly, overwriting the original file with the processed output. ### Method ```python JobBuilder().replace_input('document.pdf').linearize().run() ``` ### Description - `replace_input(filename)`: Sets the input file to be modified in place. - `linearize()`: Applies linearization to the file. - `run()`: Executes the operation, overwriting the original input file. ``` -------------------------------- ### Accessing Nested PDF Objects Source: https://pikepdf.readthedocs.io/en/latest/topics/namepath.html Examples of accessing nested PDF objects using attribute notation. This is suitable for known keys but can be cumbersome for optional or deeply nested values. ```python >>> page.Resources.XObject['/Im0'] # Accessing an image >>> pdf.Root.Pages.Kids[0].MediaBox # Accessing a page's media box ``` -------------------------------- ### Inspect Image Properties with PdfImage Source: https://pikepdf.readthedocs.io/en/latest/topics/images.html Demonstrates how to open a PDF, access an image object, and inspect its properties such as colorspace and dimensions using the `PdfImage` class. Ensure the PDF file exists at the specified path. ```python from pikepdf import Pdf, PdfImage, Name example = Pdf.open('../tests/resources/congress.pdf') page1 = example.pages[0] list(page1.get_images().keys()) rawimage = page1.get_images()['/Im0'] # The raw object/dictionary pdfimage = PdfImage(rawimage) type(pdfimage) pdfimage.colorspace pdfimage.width, pdfimage.height ``` -------------------------------- ### Auto-generate Outlines for Merged PDFs Source: https://pikepdf.readthedocs.io/en/latest/topics/outlines.html Automatically creates outline entries for each PDF file when merging them into a single document. This requires glob to be installed and PDF files to be present in the current directory. ```python >>> from glob import glob >>> pdf = Pdf.new() >>> page_count = 0 >>> with pdf.open_outline() as outline: ... for file in glob('*.pdf'): ... src = Pdf.open(file) ... oi = OutlineItem(file, page_count) ... outline.root.append(oi) ... page_count += len(src.pages) ... pdf.pages.extend(src.pages) >>> pdf.save('merged.pdf') ``` -------------------------------- ### Run Pikepdf Job with argv List Source: https://pikepdf.readthedocs.io/en/latest/topics/jobs.html Instantiate and run a Pikepdf Job directly using a list of arguments, mimicking a qpdf command-line invocation. The first element of the list is ignored. ```python from pikepdf import Job Job(['pikepdf', '--linearize', 'in.pdf', 'out.pdf']).run() ``` -------------------------------- ### Verbose Error Handling Without NamePath Source: https://pikepdf.readthedocs.io/en/latest/topics/namepath.html Illustrates the verbose and error-prone traditional method of accessing nested PDF object properties using try-except blocks or multiple get() calls. ```python # Verbose and error-prone try: font = page.Resources.Font.F1 except (KeyError, AttributeError): font = None # Or with multiple get() calls resources = page.get(Name.Resources) if resources: font_dict = resources.get(Name.Font) if font_dict: font = font_dict.get('/F1') ``` -------------------------------- ### show Source: https://pikepdf.readthedocs.io/en/latest/api/models.html Displays the image using PIL's default image viewing mechanism. This is useful for quick visual inspection of the image content. ```APIDOC ## show ### Description Show the image however PIL wants to. ### Method `show()` ### Parameters None ### Returns None ### Return type None ``` -------------------------------- ### Interact with Radio Button Groups Source: https://pikepdf.readthedocs.io/en/latest/topics/interactive_forms.html Manage radio button selections. Use the `states` property to see available options, `value` to get the currently selected option, and `selected` to set the selection. ```python radio_group = form['MyRadioButtonGroup'] radio_group.states radio_group.value radio_group.value = pikepdf.Name("/1") radio_group.options[0].checked radio_group.options[1].on_value radio_group.options[1].states radio_group.selected = radio_group.options[1] radio_group.value radio_group.options[2].select() radio_group.value ``` -------------------------------- ### Encrypting a PDF Source: https://pikepdf.readthedocs.io/en/latest/topics/jobs.html Demonstrates how to encrypt a PDF file using `JobBuilder`, specifying owner and user passwords, and setting permissions. ```APIDOC ## Encrypting a PDF Encrypt PDF files using the `encrypt()` method, which accepts passwords and a `Permissions` object to control access. ### Method ```python from pikepdf import JobBuilder, Permissions JobBuilder().input('in.pdf').output('out.pdf').encrypt( owner_password='secret', user_password='', allow=Permissions(extract=False, modify_annotation=False), ).run() ``` ### Description - `encrypt(...)`: Configures encryption settings for the PDF. - `owner_password`: The password for the document owner. - `user_password`: The password for general users. - `allow`: A `Permissions` object specifying allowed actions (e.g., `extract`, `modify_annotation`). - `run()`: Applies the encryption and saves the output. ``` -------------------------------- ### Get Images from a PDF Page Source: https://pikepdf.readthedocs.io/en/latest/topics/images.html Use `page.get_images()` to retrieve a mapping of resource names to image objects directly referenced by the page. This method can optionally recurse into Form XObjects to find nested images. ```python >>> page = pdf.pages[0] >>> images = page.get_images() # {'/Im0': , ...} ``` -------------------------------- ### Download and unpack qpdf external libraries Source: https://pikepdf.readthedocs.io/en/latest/source_build.html Downloads and extracts pre-compiled external libraries for qpdf. Replace '$version' with the desired qpdf version. ```powershell wget https://github.com/qpdf/external-libs/releases/download/release-$version/qpdf-external-libs-bin.zip -Outfile libs.zip expand-archive -path libs.zip -destinationpath . ``` -------------------------------- ### Create a New NameTree Source: https://pikepdf.readthedocs.io/en/latest/api/models.html Use `NameTree.new` to create a new name tree in a PDF. You will typically need to insert the new name tree into the PDF's catalog, for example, under `/Root /Names /Dests`. ```python nt = NameTree.new(pdf) pdf.Root.Names.Dests = nt.obj ``` -------------------------------- ### Array Index Support with NamePath Source: https://pikepdf.readthedocs.io/en/latest/topics/namepath.html Shows how NamePath handles both positive and negative array indices for accessing elements. ```python >>> pdf = Pdf.new() >>> pdf.Root.Items = Array([10, 20, 30]) >>> int(pdf.Root[NamePath.Items[0]]) 10 >>> int(pdf.Root[NamePath.Items[-1]]) # Last element 30 ``` -------------------------------- ### Create PDF Outlines Source: https://pikepdf.readthedocs.io/en/latest/topics/outlines.html Adds outline entries to an existing PDF document, referencing specific pages. Ensure the PDF file exists and is accessible. ```python >>> from pikepdf import Pdf, OutlineItem >>> pdf = Pdf.open('document.pdf') >>> with pdf.open_outline() as outline: ... outline.root.extend([ ... # Page counts are zero-based ... OutlineItem('Section One', 0), ... OutlineItem('Section Two', 2), ... OutlineItem('Section Three', 8) ... ]) >>> pdf.save('document_with_outline.pdf') ``` -------------------------------- ### Color and Line Settings Source: https://pikepdf.readthedocs.io/en/latest/api/canvas.html Methods for setting fill and stroke colors, and line width. ```APIDOC ## set_dashes(_array =None_, _phase =0_) ### Description Set dashes for lines. ### Method N/A (Method of Canvas object) ## set_fill_color(_r_ , _g_ , _b_) ### Description Set the RGB fill color for shapes. ### Parameters #### Path Parameters - **r** (float) - Required - Red component of the color. - **g** (float) - Required - Green component of the color. - **b** (float) - Required - Blue component of the color. ### Method N/A (Method of Canvas object) ## set_line_width(_width_) ### Description Set the width of lines. ### Parameters #### Path Parameters - **width** (float) - Required - The line width. ### Method N/A (Method of Canvas object) ## set_stroke_color(_r_ , _g_ , _b_) ### Description Set the RGB stroke color for shapes. ### Parameters #### Path Parameters - **r** (float) - Required - Red component of the color. - **g** (float) - Required - Green component of the color. - **b** (float) - Required - Blue component of the color. ### Method N/A (Method of Canvas object) ``` -------------------------------- ### Extracting Raw Image Samples vs. Presentation Image Source: https://pikepdf.readthedocs.io/en/latest/topics/images.html Use `apply_decode_array=False` to get the raw stored sample values, ignoring the /Decode array. The default behavior matches what a PDF viewer would render. ```python >>> raw = pdfimage.as_pil_image(apply_decode_array=False) # stored samples, /Decode ignored >>> shown = pdfimage.as_pil_image() # default: matches a PDF viewer ``` -------------------------------- ### qdf() Source: https://pikepdf.readthedocs.io/en/latest/api/main.html Produces QDF output suitable for inspection in a text editor. ```APIDOC ## qdf() ### Description Produces QDF output suitable for inspection in a text editor. ### Method (Not specified, likely a method call on a JobBuilder object) ### Endpoint (Not applicable, this is an SDK method) ### Return type JobBuilder ``` -------------------------------- ### Build qpdf from source on Windows Source: https://pikepdf.readthedocs.io/en/latest/source_build.html Compiles qpdf from its source code using CMake on Windows. Ensure you are in the qpdf source directory. ```powershell cd $qpdf cmake -S . -B build cmake --build build --config Release ``` -------------------------------- ### Constructing Attached File Spec from Memory Source: https://pikepdf.readthedocs.io/en/latest/api/models.html Illustrates how to create an attached file specification directly from in-memory bytes data. This is useful when the file content is available as a byte string. ```python fs = AttachedFileSpec(pdf, b'binary data', filename='test.pdf', description='A test file') pdf.attachments['test.pdf'] = fs ``` -------------------------------- ### Run qpdf Command Line via Job Source: https://pikepdf.readthedocs.io/en/latest/tutorial.html Executes a qpdf command-line operation using the pikepdf Job class with a list of arguments. ```python >>> from pikepdf import Job >>> Job(['pikepdf', '--check', '../tests/resources/fourpages.pdf']) ``` -------------------------------- ### Set Advanced qpdf Options with JobBuilder Source: https://pikepdf.readthedocs.io/en/latest/topics/jobs.html Use the `set()` method to configure advanced or less common qpdf options not directly exposed as JobBuilder methods. Boolean `True` enables a flag; other values are stringified. Invalid option names will raise a ValueError. ```python JobBuilder().input('in.pdf').output('out.pdf') \ .set(no_warn=True, keep_files_open=False) \ .run() ``` -------------------------------- ### Access XMP Metadata Source: https://pikepdf.readthedocs.io/en/latest/topics/metadata.html Read the 'xmp:CreatorTool' field from a PDF's XMP metadata. If no XMP metadata exists, an empty container is created. ```python pdf = pikepdf.open('../tests/resources/sandwich.pdf') meta = pdf.open_metadata() meta['xmp:CreatorTool'] 'ocrmypdf 5.3.3 / Tesseract OCR-PDF 3.05.01' ```