Last active
April 25, 2026 11:41
-
-
Save rougier/86f816293413dcc16c27d9370d8c82db to your computer and use it in GitHub Desktop.
Python script to add random small black squares on each page of a PDF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env python | |
| """ | |
| Copyright (c) 2026 N.Rougier | |
| Permission is hereby granted, free of charge, to any person obtaining a copy | |
| of this software and associated documentation files (the "Software"), to deal | |
| in the Software without restriction, including without limitation the rights | |
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| copies of the Software, and to permit persons to whom the Software is | |
| furnished to do so, subject to the following conditions: | |
| The above copyright notice and this permission notice shall be included in all | |
| copies or substantial portions of the Software. | |
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| SOFTWARE. | |
| """ | |
| import os, sys, io, random, argparse, os | |
| from pypdf import PdfReader, PdfWriter | |
| from reportlab.pdfgen import canvas | |
| from reportlab.lib.pagesizes import A4 | |
| from reportlab.lib.units import mm | |
| def add_squares(input_path, ratio, size_mm, output_path): | |
| """ | |
| Overlay random black squares onto a PDF aligned to a grid of square size. | |
| Parameters | |
| ---------- | |
| input_path : str | |
| The file system path to the source PDF file. | |
| ratio : float | |
| The desired percentage of the page surface area to be covered by | |
| black squares (e.g., 10.0 for 10% coverage). | |
| size_mm : int | |
| The side length of the squares in millimeters (1 to 10). | |
| output_path : str | |
| The file system path where the modified PDF will be saved. | |
| Raises | |
| ------ | |
| FileNotFoundError | |
| If the input_path does not point to an existing file. | |
| """ | |
| if not os.path.exists(input_path): | |
| print(f"Error: The file '{input_path}' was not found.") | |
| sys.exit(1) | |
| try: | |
| reader = PdfReader(input_path) | |
| writer = PdfWriter() | |
| # A4 Dimensions | |
| A4_WIDTH_MM = 210 | |
| A4_HEIGHT_MM = 297 | |
| # Grid Logic: Calculate how many columns and rows fit on the page | |
| cols = A4_WIDTH_MM // size_mm | |
| rows = A4_HEIGHT_MM // size_mm | |
| # Area Calculation | |
| A4_AREA_MM2 = A4_WIDTH_MM * A4_HEIGHT_MM | |
| square_area_mm2 = size_mm ** 2 | |
| num_squares = int((A4_AREA_MM2 * (ratio / 100)) / square_area_mm2) | |
| # Total possible grid slots | |
| total_slots = cols * rows | |
| if num_squares > total_slots: | |
| num_squares = total_slots | |
| print(f"Warning: Requested ratio exceeds grid capacity. Using max: {num_squares} squares.") | |
| print(f"\n--- PDF Square Overlay Tool (Grid-Aligned) ---") | |
| print(f"Input: {input_path}") | |
| print(f"Grid: {cols} cols x {rows} rows ({size_mm}mm steps)") | |
| print(f"Ratio: {ratio}% ({num_squares} squares per page)") | |
| for page_num in range(len(reader.pages)): | |
| packet = io.BytesIO() | |
| can = canvas.Canvas(packet, pagesize=A4) | |
| can.setFillColorRGB(0, 0, 0) | |
| # Create a list of all possible (col, row) indices and pick N unique ones | |
| # This ensures NO overlapping, making the 10% surface area mathematically perfect. | |
| all_possible_indices = [(c, r) for c in range(cols) for r in range(rows)] | |
| selected_indices = random.sample(all_possible_indices, num_squares) | |
| for c_idx, r_idx in selected_indices: | |
| x_pts = (c_idx * size_mm) * mm | |
| y_pts = (r_idx * size_mm) * mm | |
| can.rect(x_pts, y_pts, size_mm * mm, size_mm * mm, fill=1, stroke=0) | |
| can.save() | |
| packet.seek(0) | |
| overlay_pdf = PdfReader(packet) | |
| existing_page = reader.pages[page_num] | |
| existing_page.merge_page(overlay_pdf.pages[0]) | |
| writer.add_page(existing_page) | |
| with open(output_path, "wb") as output_file: | |
| writer.write(output_file) | |
| print(f"Output: {output_path}") | |
| print(f"Status: Success\n") | |
| except Exception as e: | |
| print(f"An error occurred: {e}") | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Add grid-aligned random squares to a PDF.") | |
| parser.add_argument("input", nargs='?', help="Path to the source PDF file") | |
| parser.add_argument("-r", "--ratio", type=float, default=10.0, | |
| help="Percentage of page coverage (default: 10)") | |
| parser.add_argument("-s", "--size", type=int, default=1, | |
| help="Square size in mm (integer), between 1 and 10 (default: 1)") | |
| parser.add_argument("-o", "--output", help="Output file name (optional)") | |
| args = parser.parse_args() | |
| if not args.input: | |
| args.input = input("Please enter the path to the input PDF: ").strip() | |
| if not args.input: | |
| sys.exit(1) | |
| if not (1 <= args.size <= 10): | |
| print("Error: Square size must be an integer between 1 and 10 mm.") | |
| sys.exit(1) | |
| if not args.output: | |
| base_name = os.path.splitext(args.input)[0] | |
| args.output = f"{base_name}-{args.ratio}pct-{args.size}mm-grid.pdf" | |
| add_squares(args.input, args.ratio, args.size, args.output) |
Author
rougier
commented
Apr 25, 2026
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment