### Bash Script for Running pdfrw Tests Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst This bash script demonstrates the steps required to set up and run the tests for the pdfrw library. It includes installing necessary dependencies, cloning a PDF repository, and executing tests using pytest. ```bash # Install necessary packages pip install pytest pip install reportlab # Navigate to the tests directory cd <...>/pdfrw/tests # Clone the static PDF repository git clone https://github.com/pmaupin/static_pdfs # Create a symbolic link to the pdfrw library ln -s ../pdfrw # Run all tests using pytest pytest ``` -------------------------------- ### Find Specific PDF Objects (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Details the utility of the pdfrw.findobjs module for locating specific types of objects within a PDF file. The extract.py example uses this to place images and Form XObjects onto individual pages. ```python # Assuming findobjs module is imported # objects = findobjs.find_objects(pdf_reader, type='Image') # This module is key for extracting and reusing specific PDF elements. ``` -------------------------------- ### Manipulate PDF Objects Directly with pdfrw Source: https://context7.com/pmaupin/pdfrw/llms.txt This example shows how to access and modify PDF dictionary and array objects programmatically using `pdfrw`. It covers attribute and index-based access, type checking, creating new PDF objects, setting private attributes, marking objects as indirect, and modifying PDF metadata. It utilizes `PdfReader`, `PdfWriter`, `PdfDict`, `PdfArray`, `PdfName`, and `PdfObject`. ```python from pdfrw import PdfReader, PdfWriter, PdfDict, PdfArray, PdfName, PdfObject # Read PDF and access objects pdf = PdfReader('document.pdf') # Dictionary access (two methods) page = pdf.pages[0] print(page.MediaBox) # Attribute access for standard names print(page['/MediaBox']) # Index access for any name # Check object types from pdfrw.objects import PdfDict, PdfArray print(isinstance(page, PdfDict)) # True print(isinstance(page.MediaBox, PdfArray)) # True # Create new PDF objects new_dict = PdfDict() new_dict.Type = PdfName.Page new_dict.MediaBox = PdfArray([0, 0, 612, 792]) # Letter size new_dict.Rotate = PdfObject('90') # Set private attributes (not written to PDF) page.private.my_custom_data = 'internal use only' print(page.my_custom_data) # Access without 'private' # Mark objects as indirect for cross-referencing new_dict.indirect = True # Modify metadata if pdf.Info: pdf.Info.Title = 'New Title' pdf.Info.Author = 'New Author' pdf.Info.Keywords = 'pdf, python, pdfrw' # Write modified PDF writer = PdfWriter() writer.trailer = pdf writer.write('modified.pdf') ``` -------------------------------- ### Instantiate PdfWriter for PDF File Creation (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Demonstrates the instantiation of the PdfWriter class from the pdfrw.pdfwriter module for creating PDF files. Pages can be added from various sources before writing to a file. ```python # Assuming pdfwriter module is imported as PdfWriter # writer = PdfWriter() # writer.addpage(page_object) # writer.write('output.pdf') ``` -------------------------------- ### Read PDF Document and Access Properties using PdfReader Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Demonstrates how to use the PdfReader class to open a PDF file and access its top-level objects like Info, Size, and Root. It also shows how to access the list of pages and their content streams. ```python from pdfrw import PdfReader x = PdfReader('source.pdf') print(x.keys()) print(x.Info) print(x.Root.keys()) print(len(x.pages)) print(x.pages[0].Contents.stream) ``` -------------------------------- ### Python 2/3 Compatibility Utilities Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst This script contains code designed to manage differences between Python 2 and Python 3 environments. It helps in writing code that can be compatible with both versions. ```python # py23_diffs.py # Contains code to manage differences between Python 2 and Python 3. import sys if sys.version_info[0] < 3: # Python 2 specific code def print_function(msg): print msg else: # Python 3 specific code def print_function(msg): print(msg) ``` -------------------------------- ### Compare Pickled Test Results with Python Source: https://github.com/pmaupin/pdfrw/blob/master/tests/Render Bitmap.ipynb Compares 'result.pickle' and 'expected.pickle' files by loading, rasterizing, and displaying their contents using `pickle.load`, `rasterizer`, and `pyplot.imshow`. This utility is designed to visually verify the output of test cases. ```python # # After running any of these tests (pytest -k test_flate_png_alt_file), # two files are produced: tests/result.pickle and tests/expected.pickle. # These files contain buffers that can be rendered # Both rendered buffers must be identical import pickle with open('./result.pickle', 'rb') as f: result = pickle.load(f) print len(raster) print len(raster[0]) res = rasterizer(result, 96, 3, 2) # Assuming rasterizer is defined elsewhere print len(res) print len(res[0]) pyplot.imshow(res) pyplot.show() with open('./expected.pickle', 'rb') as f: expected = pickle.load(f) print len(expected) res = rasterizer(expected, 96, 3, 2) # Assuming rasterizer is defined elsewhere print len(res) print len(res[0]) pyplot.imshow(res) pyplot.show() ``` -------------------------------- ### Build Form XObjects from PDF Pages (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Shows the usage of functions from the pdfrw.buildxobj module to create Form XObjects from PDF pages or rectangles. These XObjects can be reused in new PDFs like images, with caching to ensure uniqueness. ```python # Assuming buildxobj module is imported # xobj = buildxobj.pagexobj(page_object) # This function helps in creating reusable PDF content. ``` -------------------------------- ### PdfName Object Creation and Usage in Python Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Demonstrates how to create and use PdfName objects for PDF name representation. PdfName objects are specifically designed for use as keys in PdfDict objects, ensuring correct PDF naming conventions. ```python from pdfrw.objects import PdfName, PdfObject # Example usage of PdfName objects # PdfName.Rotate is an instance of BasePdfName # PdfName('Rotate') also returns a BasePdfName instance # PdfObject('/Rotate') returns a PdfObject instance # Comparing different ways to get a PdfName object print(PdfName.Rotate == PdfName('Rotate')) print(PdfName.Rotate == PdfObject('/Rotate')) # PdfName objects are used as keys in PdfDict # Example: pdf_dict = PdfDict() # pdf_dict[PdfName.Key] = 'Value' ``` -------------------------------- ### Create New Pages by Merging/Overlaying Rectangles (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Describes the functionality of classes in the pdfrw.pagemerge module, which build upon buildxobj. These classes allow creating new pages or overlaying existing ones using specified rectangles from other pages, supporting features like watermarking and multi-up layouts. ```python # Assuming pagemerge module is imported # merger = pagemerge.PDFMerger() # merger.merge(output_page, input_page, rectangle) # This is useful for tasks like watermarking or creating 4-up layouts. ``` -------------------------------- ### Translate pdfrw Objects for ReportLab (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Illustrates the use of the makerl function from the pdfrw.toreportlab module. This function translates pdfrw objects into a format compatible with the ReportLab library, often used with buildxobj. ```python # Assuming toreportlab module is imported # rl_compatible_object = toreportlab.makerl(pdfrw_object) # This enables using parts of existing PDFs within ReportLab documents. ``` -------------------------------- ### Instantiate PdfReader for PDF File Parsing (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Illustrates the instantiation of the PdfReader class from the pdfrw.pdfreader module. PdfReader can parse a PDF file, a file object, or a string. It allows for decompression options, though current support is limited. ```python # Assuming pdfreader module is imported as PdfReader # reader = PdfReader(open('input.pdf', 'rb')) # Or reader = PdfReader('input.pdf') # The PdfReader instance is a PdfDict representing the trailer. ``` -------------------------------- ### Writing PDF Document with PdfWriter Source: https://github.com/pmaupin/pdfrw/wiki/ObjectModel Shows the basic usage of PdfWriter to create a new PDF file. It involves instantiating PdfWriter, adding pages from an existing document, and writing the output to a file. ```python from pdfrw import PdfWriter y = PdfWriter() y.addpage(x.pages[0]) y.write('result.pdf') ``` -------------------------------- ### Visualize PNG Log Files with Python Source: https://github.com/pmaupin/pdfrw/blob/master/tests/Render Bitmap.ipynb Loads and displays raster data from PNG log files using the `load_png_log` function and `pyplot.imshow`. This is useful for visually inspecting the contents of PNG log files. ```python (raster, raster2), (data, expected), (width, bit_depth, channels, color_type, pixel_depth, rowbytes, filter) \ = load_png_log('./basn2c08.png.log') pyplot.imshow(raster) pyplot.show() ``` ```python (raster, raster2), (data, expected), (width, bit_depth, channels, color_type, pixel_depth, rowbytes, filter) \ = load_png_log('./basn0g08.png.log') pyplot.imshow(raster) pyplot.show() ``` ```python (raster, raster2), (data, expected), (width, bit_depth, channels, color_type, pixel_depth, rowbytes, filter) \ = load_png_log('./f01n2c08.png.log') pyplot.imshow(raster) pyplot.show() ``` ```python (raster, raster2), (data, expected), (width, bit_depth, channels, color_type, pixel_depth, rowbytes, filter) \ = load_png_log('./f02n2c08.png.log') pyplot.imshow(raster) pyplot.show() ``` ```python (raster, raster2), (data, expected), (width, bit_depth, channels, color_type, pixel_depth, rowbytes, filter) \ = load_png_log('./f03n2c08.png.log') pyplot.imshow(raster) pyplot.show() ``` ```python (raster, raster2), (data, expected), (width, bit_depth, channels, color_type, pixel_depth, rowbytes, filter) \ = load_png_log('./f04n2c08.png.log') pyplot.imshow(raster) pyplot.show() ``` -------------------------------- ### Writing PDF Files with PdfWriter Source: https://context7.com/pmaupin/pdfrw/llms.txt Shows how to create new PDF files from existing pages or build documents from scratch using PdfWriter. Supports adding pages individually or in batches and writing to a file. ```APIDOC ## Writing PDF Files with PdfWriter ### Description Create new PDF files from pages or build documents from scratch using `PdfWriter`. Supports adding pages individually or in batches and writing to a file. Can also preserve original structure when modifying existing PDFs. ### Method `PdfWriter(filename, trailer=None)` ### Endpoint N/A (Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pdfrw import PdfReader, PdfWriter # Create a new PDF writer writer = PdfWriter() # Read source document source = PdfReader('input.pdf') # Add pages individually writer.addpage(source.pages[0]) writer.addpage(source.pages[2]) # Or add multiple pages at once writer.addpages(source.pages[3:7]) # Write to file writer.write('output.pdf') # Alternative: preserve original structure # Useful when modifying existing PDFs to maintain navigation, bookmarks, etc. trailer = PdfReader('input.pdf') writer = PdfWriter('output.pdf', trailer=trailer) writer.write() ``` ### Response #### Success Response (200) Writes the PDF content to the specified output file. #### Response Example File 'output.pdf' is created with the specified pages. ``` -------------------------------- ### Reading PDF Files with PdfReader Source: https://context7.com/pmaupin/pdfrw/llms.txt Demonstrates how to load and parse PDF files into memory using PdfReader, access trailer information, page count, page dimensions, resources, rotation, and content streams. ```APIDOC ## Reading PDF Files with PdfReader ### Description Load and parse PDF files into memory with automatic page tree resolution. Access trailer information, page count, page dimensions, resources, rotation, and content streams. ### Method `PdfReader(filename)` ### Endpoint N/A (Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pdfrw import PdfReader # Read a PDF file pdf = PdfReader('source.pdf') # Access trailer information print(pdf.Info.Title) # PDF title print(pdf.Info.Author) # PDF author print(pdf.Size) # Number of objects print(pdf.Root.Type) # Should be '/Catalog' # Access all pages as a flat list print(f"Total pages: {len(pdf.pages)}") # Access page contents page = pdf.pages[0] print(page.MediaBox) # Page dimensions [x1, y1, x2, y2] print(page.Resources.keys()) # Available resources print(page.Rotate) # Page rotation (0, 90, 180, 270) # Access content stream if page.Contents: print(page.Contents.stream[:100]) # First 100 chars of content # Use inheritable attributes (searches parent hierarchy) mediabox = page.inheritable.MediaBox ``` ### Response #### Success Response (200) Returns a `PdfReader` object representing the parsed PDF. #### Response Example ```json { "Info": { "Title": "Example Document", "Author": "John Doe" }, "Size": 12345, "Root": { "Type": "/Catalog" }, "pages": [ { "MediaBox": [0, 0, 612, 792], "Rotate": 0, "Resources": {}, "Contents": {"stream": "..."} } ] } ``` ``` -------------------------------- ### Bash Script for Running a Single pdfrw Test Case Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst This bash command shows how to execute a specific test case within the pdfrw test suite using pytest. It allows targeting a single test file and a particular test function. ```bash # Run a specific test case pytest test_roundtrip.py -k "test_compress_9f98322c243fe67726d56ccfa8e0885b.pdf" ``` -------------------------------- ### Reading PDF Document with PdfReader Source: https://github.com/pmaupin/pdfrw/wiki/ObjectModel Demonstrates how to use PdfReader to load a PDF file and access its main components like Info, Size, Root, and pages. It shows accessing document metadata and the list of pages within the PDF. ```python from pdfrw import PdfReader x = PdfReader('source.pdf') x.keys() x.Info len(x.pages) x.pages[0] ``` -------------------------------- ### Python Compression and Decompression Functions Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst These scripts provide basic compression and decompression functionalities for PDF files. Currently, support for filters is limited, and external tools like pdftk may be necessary for full decompression or decryption capabilities. ```python # compress.py # Contains compression functions. def compress_pdf(data): # Implementation for PDF compression pass # uncompress.py # Contains decompression functions. def decompress_pdf(data): # Implementation for PDF decompression pass ``` -------------------------------- ### Access Inheritable PDF Page Attributes (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Shows how to access 'inheritable' attributes of PDF pages. Inheritable attributes can be defined in parent dictionaries and are easily discoverable using the '.inheritable' attribute. ```python mediabox = mypage.inheritable.MediaBox ``` -------------------------------- ### Pixel Data Conversion for Image Rendering (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/tests/Render Bitmap.ipynb Converts raw byte data into a list of RGB color values based on the specified color type. Supports grayscale (0) and truecolor (2) formats, normalizing pixel values to a 0-1 range for rendering. It expects specific byte lengths for each color type and raises an error for unsupported types. ```python import matplotlib.pyplot as pyplot import array import ast def pixel(bytes, color_type): if color_type == 0: assert len(bytes) == 1, "expected 1 but got %d" % len(bytes) #print bytes bytes = [bytes[0]/255.0, bytes[0]/255.0, bytes[0]/255.0] elif color_type == 2: assert len(bytes) == 3, "expected 3 but got %d" % len(bytes) #print bytes bytes = [bytes[0]/255.0, bytes[1]/255.0, bytes[2]/255.0] elif color_type == 'rgb': assert len(bytes) == 3, "expected 3 but got %d" % len(bytes) bytes = [(int)(bytes[0] * 255) % 256, (int)(bytes[1] * 255.0) % 256, (int)(bytes[2] * 255.0) % 256] else: raise ValueError("Unsupported color_type %d" % color_type) return bytes ``` -------------------------------- ### Loading and Processing PNG Log Files (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/tests/Render Bitmap.ipynb Parses a `.png.log` file to extract image buffer information, including dimensions, color properties, and raw pixel data. It then utilizes the `rasterizer` function to convert both the 'expected' and 'data' buffers into a 2D raster format. Includes extensive assertions to validate data integrity. ```python def load_png_log(png_log): ''' Lifted from test_flate_png.py :: util_test_flate_png_alt_from_png_log_file Reads xxxxx.png.log and produces a raster of both expected and data ''' with open(png_log) as f: data = array.array('B') expected = array.array('B') width = 0 bit_depth = 0 channels = 0 color_type = 0 pixel_depth = 0 rowbytes = 0 filter = 0 nrows = 0 for l in f.readlines(): if l.startswith("PASS:"): break l = l.split(' = ') var = l[0] val = l[1] if var == 'width': width = int(val) elif var == 'bit_depth': bit_depth = int(val) elif var == 'channels': channels = int(val) elif var == 'color_type': color_type = int(val) elif var == 'pixel_depth': pixel_depth = int(val) elif var == 'rowbytes': rowbytes = int(val) elif var == 'filter': filter = int(val) elif var == 'data': d = ast.literal_eval(val) data.append(filter) data.extend(d) elif var == 'expected': e = ast.literal_eval(val) expected.extend(e) nrows += 1 print("width: %d" % width) print("bit_depth: %d" % bit_depth) print("channels: %d" % channels) print("color_type: %d" % color_type) print("pixel_depth: %d" % pixel_depth) print("rowbytes: %d" % rowbytes) print("filter: %d" % filter) print("expected: %d" % len(expected)) print("data: %d" % len(data)) print("nrows: %d" % nrows) assert color_type in [ 0, # Grayscale (Y) 2, # Truecolor (RGB) # 3 Indexed is not supported (Palette) 4, # Grayscale with alpha (YA) 6, # Truecolor with alpha (RGBA) ] assert filter in [0, 1, 2, 3, 4] assert channels * bit_depth == pixel_depth assert (pixel_depth // 8) * width == rowbytes bytes_per_pixel = pixel_depth // 8 assert 0 == pixel_depth % 8 # can't support pixels with bit_depth < 8 assert 8 == bit_depth # ideally, we should test bit_depth 16 also assert nrows * (1 + width * bytes_per_pixel) == len(data) # 1 filter byte preceeding each row assert nrows * width * bytes_per_pixel == len(expected) ### Rasterize each buffer raster = rasterizer(expected, rowbytes, bytes_per_pixel, color_type) raster2 = rasterizer(data, rowbytes, bytes_per_pixel, color_type, filter_included=True) return (raster, raster2), (data, expected), (width, bit_depth, channels, color_type, pixel_depth, rowbytes, filter) ``` -------------------------------- ### Scale and Position Overlay on PDF Pages with PageMerge Source: https://context7.com/pmaupin/pdfrw/llms.txt This function demonstrates how to use `PageMerge` to place a scaled overlay PDF onto each page of a background PDF. It allows precise control over the scale, X, and Y positioning of the overlay, and writes the result to a new PDF file. Dependencies include `pdfrw.PdfReader`, `pdfrw.PageMerge`, and `pdfrw.PdfWriter`. ```python from pdfrw import PdfReader, PageMerge def create_scaled_overlay(background_pdf, overlay_pdf, output_pdf, scale=0.5, x_pos=100, y_pos=100): """ Place a scaled overlay at specific coordinates on each page. Args: background_pdf: Path to background document overlay_pdf: Path to overlay content output_pdf: Path to output scale: Scale factor for overlay (1.0 = 100%) x_pos: X position from left in points y_pos: Y position from bottom in points """ # Load documents background = PdfReader(background_pdf) overlay_page = PdfReader(overlay_pdf).pages[0] # Process each page for page in background.pages: # Create page merger merger = PageMerge(page) # Add overlay as Form XObject overlay_obj = merger.add(overlay_page)[0] # Position and scale overlay_obj.scale(scale) overlay_obj.x = x_pos overlay_obj.y = y_pos # Render changes back to page merger.render() # Write output from pdfrw import PdfWriter PdfWriter(output_pdf, trailer=background).write() # Add logo at 50% scale at position (100, 100) create_scaled_overlay('report.pdf', 'logo.pdf', 'branded_report.pdf', scale=0.5, x_pos=100, y_pos=100) ``` -------------------------------- ### Set Private Attributes on PDF Dictionaries (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/README.rst Demonstrates how to set private attributes on a PdfDict object. These attributes are not written to the output PDF file. Private attributes are accessed and set using the '.private' attribute of the dictionary. ```python mydict.private.foo = 1 foo = mydict.foo ``` -------------------------------- ### Create Booklet with Padding using pdfrw Source: https://context7.com/pmaupin/pdfrw/llms.txt Demonstrates how to create a booklet from a PDF file with added padding. This function likely handles the arrangement of pages to form a booklet layout, suitable for printing or digital distribution. ```python from pdfrw import PdfReader, PdfWriter def create_booklet(input_pdf, output_pdf, padding=False): # Implementation details for creating a booklet with optional padding would go here. # This is a placeholder function call from the project description. pass create_booklet('manual.pdf', 'booklet_manual.pdf', padding=True) ``` -------------------------------- ### Create 4-Up Layouts with pdfrw Source: https://context7.com/pmaupin/pdfrw/llms.txt Arranges four source PDF pages onto a single output page, scaling each source page to 50% and positioning them in a 2x2 grid. This is useful for creating 4-up print layouts. ```python from pdfrw import PdfReader, PdfWriter, PageMerge def create_4up(input_file, output_file): """ Create 4-up layout with 4 source pages per output page. Each source page is scaled to 50% and arranged in 2x2 grid. """ def get4(srcpages): scale = 0.5 srcpages = PageMerge() + srcpages x_increment, y_increment = (scale * i for i in srcpages.xobj_box[2:]) # Position pages: top-left, top-right, bottom-left, bottom-right for i, page in enumerate(srcpages): page.scale(scale) page.x = x_increment if i & 1 else 0 page.y = 0 if i & 2 else y_increment return srcpages.render() pages = PdfReader(input_file).pages writer = PdfWriter(output_file) # Process in chunks of 4 for index in range(0, len(pages), 4): writer.addpage(get4(pages[index:index + 4])) writer.write() # Create 4-up layout create_4up('presentation.pdf', '4up_presentation.pdf') ``` -------------------------------- ### Write PDF Files with PdfWriter in Python Source: https://context7.com/pmaupin/pdfrw/llms.txt Create new PDF files from existing pages or build documents from scratch using PdfWriter. Pages can be added individually or in batches. An alternative method preserves the original structure when modifying existing PDFs, maintaining navigation and bookmarks. ```python from pdfrw import PdfReader, PdfWriter # Create a new PDF writer writer = PdfWriter() # Read source document source = PdfReader('input.pdf') # Add pages individually writer.addpage(source.pages[0]) writer.addpage(source.pages[2]) # Or add multiple pages at once writer.addpages(source.pages[3:7]) # Write to file writer.write('output.pdf') # Alternative: preserve original structure # Useful when modifying existing PDFs to maintain navigation, bookmarks, etc. trailer = PdfReader('input.pdf') writer = PdfWriter('output.pdf', trailer=trailer) writer.write() ``` -------------------------------- ### Image Rasterization from Raw Data (Python) Source: https://github.com/pmaupin/pdfrw/blob/master/tests/Render Bitmap.ipynb Transforms a flat array of image data into a 2D raster representation (list of lists). It iterates through the data, extracting pixel information based on row bytes, bytes per pixel, and color type. Optionally handles filter bytes preceding each row. ```python def rasterizer(data, rowbytes, bytes_per_pixel, color_type, filter_included=False): raster = [] first_pixel = 0 if filter_included: rowbytes += 1 first_pixel = 1 for r in xrange(0, len(data), rowbytes): row = data[r : r + rowbytes] #print "row", row, len(row) raster_row = [] for c in xrange(first_pixel, rowbytes, bytes_per_pixel): #print c, bytes_per_pixel, row[c : c + bytes_per_pixel] p = pixel(row[c : c + bytes_per_pixel], color_type) #print p raster_row.append(p) raster.append(raster_row) return raster ``` -------------------------------- ### Accessing Page Contents and Stream Data Source: https://github.com/pmaupin/pdfrw/wiki/ObjectModel Illustrates digging into a specific page of a PDF document using the PdfReader object. It shows how to access the '/Contents' dictionary of a page and retrieve the associated stream data. ```python x.pages[0].Contents x.pages[0].Contents.stream ``` -------------------------------- ### Embed Existing PDF Page in ReportLab Document using Python Source: https://context7.com/pmaupin/pdfrw/llms.txt This function demonstrates how to embed a page from an existing PDF into a new PDF document created with reportlab. It reads the existing PDF, converts a page to a Form XObject, and then draws it onto the reportlab canvas with specified scaling and positioning. Dependencies include reportlab and pdfrw. It takes the paths to the existing and output PDFs as input. ```python from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from pdfrw import PdfReader from pdfrw.buildxobj import pagexobj from pdfrw.toreportlab import makerl def embed_pdf_in_reportlab(existing_pdf, output_pdf): """ Create a new PDF with reportlab that includes pages from existing PDF. """ # Create reportlab canvas c = canvas.Canvas(output_pdf, pagesize=letter) width, height = letter # Load existing PDF existing = PdfReader(existing_pdf) # Convert first page to Form XObject xobj_page = pagexobj(existing.pages[0]) # Convert to reportlab format rl_obj = makerl(c, xobj_page) # Draw on canvas with scaling scale = 0.5 x_pos = width * 0.25 y_pos = height * 0.25 c.saveState() c.translate(x_pos, y_pos) c.scale(scale, scale) c.doForm(rl_obj) c.restoreState() # Add reportlab content c.setFont("Helvetica", 24) c.drawString(100, height - 50, "New Content with Embedded PDF") c.showPage() c.save() embed_pdf_in_reportlab('existing.pdf', 'combined_with_reportlab.pdf') ``` -------------------------------- ### Create Booklets with pdfrw Source: https://context7.com/pmaupin/pdfrw/llms.txt Arranges PDF pages for booklet printing, suitable for folding and stapling. It pairs pages correctly for double-sided printing to ensure the final booklet is in the correct order. Optionally pads with blank pages to ensure correct multiples. ```python from pdfrw import PdfReader, PdfWriter, PageMerge def create_booklet(input_file, output_file, padding=False): """ Create booklet layout suitable for folding and stapling. Pages are arranged so that printing double-sided produces correct order. Args: input_file: Path to source PDF output_file: Path to output PDF padding: If True, pad to 4-page increments; else 2-page """ def fixpage(*pages): # Place pages side by side result = PageMerge() + (x for x in pages if x is not None) result[-1].x += result[0].w # Position second page to the right return result.render() ipages = PdfReader(input_file).pages # Add blank pages to ensure correct multiple pad_to = 4 if padding else 2 ipages += [None] * (-len(ipages) % pad_to) opages = [] # Arrange pages: last+first, second+second-to-last, etc. while len(ipages) > 2: opages.append(fixpage(ipages.pop(), ipages.pop(0))) opages.append(fixpage(ipages.pop(0), ipages.pop())) opages += ipages # Add any remaining center pages PdfWriter(output_file).addpages(opages).write() ``` -------------------------------- ### Read PDF Files with PdfReader in Python Source: https://context7.com/pmaupin/pdfrw/llms.txt Load and parse PDF files into memory using PdfReader. Access trailer information (Info, Size), page counts, page dimensions (MediaBox), resources, rotation, and content streams. It supports inheritable attributes for accessing PDF object properties. ```python from pdfrw import PdfReader # Read a PDF file pdf = PdfReader('source.pdf') # Access trailer information print(pdf.Info.Title) # PDF title print(pdf.Info.Author) # PDF author print(pdf.Size) # Number of objects print(pdf.Root.Type) # Should be '/Catalog' # Access all pages as a flat list print(f"Total pages: {len(pdf.pages)}") # Access page contents page = pdf.pages[0] print(page.MediaBox) # Page dimensions [x1, y1, x2, y2] print(page.Resources.keys()) # Available resources print(page.Rotate) # Page rotation (0, 90, 180, 270) # Access content stream if page.Contents: print(page.Contents.stream[:100]) # First 100 chars of content # Use inheritable attributes (searches parent hierarchy) mediabox = page.inheritable.MediaBox ```