### Set up Virtual Environment and Install ilovepdf-python Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/INSTALL.md Demonstrates how to create and activate a Python virtual environment, then install the ilovepdf-python library within it. This is a recommended practice for managing project dependencies. ```bash python -m venv venv source venv/bin/activate # Linux/Mac # or virtualenv\Scripts\activate # Windows pip install ilovepdf ``` -------------------------------- ### Install ilovepdf-python from Source Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/INSTALL.md Installs the latest version of the ilovepdf-python library directly from its GitHub repository. This is useful for developers who want to use the most recent code. ```bash pip install -U git+https://github.com/ilovepdf/ilovepdf-python.git@main#egg=ilovepdf ``` -------------------------------- ### Install ilovepdf-python Pre-release Versions Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/INSTALL.md Installs pre-release versions of the ilovepdf-python library from TestPyPI. This allows testing upcoming features but requires an extra index URL for dependencies. ```bash pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ ilovepdf ``` -------------------------------- ### Install iLovePDF Python Library Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/README.md Installs the iLovePDF Python library using pip. This is the primary method for adding the library to your Python environment. ```bash pip install ilovepdf ``` -------------------------------- ### Convert PDF to PDF/A Format with Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This example demonstrates converting standard PDF files to the PDF/A archival format using the PdfToPdfATask. It allows specifying different conformance levels (e.g., pdfa-2b, pdfa-3u) and includes an option to allow downgrading if the requested conformance cannot be met. This is crucial for long-term document preservation. ```python from ilovepdf import PdfToPdfATask task = PdfToPdfATask( public_key="your_public_key", secret_key="your_secret_key" ) task.add_file("/path/to/document.pdf") task.conformance = "pdfa-2b" task.allow_downgrade = True task.execute() task.set_output_filename("document_pdfa.pdf") task.download("/path/to/output/folder") ``` -------------------------------- ### Quick Start: Compress PDF using iLovePDF Python Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/README.md Demonstrates how to use the iLovePDF Python library to compress a PDF file. It requires API keys and specifies the input file and output destination. ```python from ilovepdf import CompressTask task = CompressTask(public_key="your_public_key", secret_key="your_secret_key") task.add_file("document.pdf") task.execute() task.download("output_folder") ``` -------------------------------- ### Perform OCR on PDF with Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This example shows how to perform Optical Character Recognition (OCR) on scanned or image-based PDF documents using the PdfOcrTask. It allows specifying one or multiple OCR languages for text extraction and saves the result as a searchable PDF. Common language codes are provided for reference. ```python from ilovepdf import PdfOcrTask task = PdfOcrTask( public_key="your_public_key", secret_key="your_secret_key" ) file = task.add_file("/path/to/scanned_document.pdf") file.ocr_languages = "eng" task.execute() task.set_output_filename("searchable_document.pdf") task.download("/path/to/output/folder") ``` -------------------------------- ### Extract Text from PDF with Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This code example demonstrates how to extract text content from PDF files using the ExtractTask. It offers a simple text extraction mode and a detailed mode that includes positional and font information for each extracted text element. The extracted text is saved to a file. ```python from ilovepdf import ExtractTask task = ExtractTask( public_key="your_public_key", secret_key="your_secret_key" ) task.add_file("/path/to/document.pdf") task.detailed = False task.execute() task.set_output_filename("extracted_text.txt") task.download("/path/to/output/folder") ``` -------------------------------- ### Edit PDF Elements with iLovePDF Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This example shows how to edit a PDF document using the iLovePDF Python SDK. It demonstrates adding text and image elements to specific pages with precise positioning, dimensions, styling (font, color, alignment), and stacking order. The task is then executed, and the edited PDF is saved. ```python from ilovepdf import EditPdfTask from ilovepdf.editpdf_task import Element # Initialize edit task task = EditPdfTask( public_key="your_public_key", secret_key="your_secret_key" ) # Add PDF file task.add_file("/path/to/document.pdf") # Create and configure a text element text_element = task.add_element() text_element.type = "text" text_element.text = "APPROVED" text_element.pages = "1" # Apply to specific pages: "1", "1-3", "all" text_element.zindex = 1 # Stacking order text_element.coordinates = {"x": 100.0, "y": 700.0} # Position (floats) text_element.dimensions = {"w": 200.0, "h": 50.0} # Size (floats) text_element.rotation = 0 # 0-360 degrees text_element.opacity = 100 # 1-100 # Text styling text_element.font_family = "Arial Unicode MS" text_element.font_size = 24 text_element.font_style = "Bold" # Options: "Regular", "Bold", "Italic", "Bold italic" text_element.font_color = "#008000" # Hex color or "transparent" text_element.text_align = "center" # Options: "left", "center", "right" text_element.letter_spacing = 0 # Create an image element image_element = task.add_element() image_element.type = "image" image_element.pages = "all" image_element.zindex = 2 image_element.coordinates = {"x": 400.0, "y": 50.0} image_element.dimensions = {"w": 100.0, "h": 100.0} image_element.set_image("/path/to/stamp.png") # Supports: png, jpg, jpeg, gif # Execute and download task.execute() task.set_output_filename("edited_document.pdf") task.download("/path/to/output/folder") ``` -------------------------------- ### Add Page Numbers to PDF with Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This snippet illustrates how to add customizable page numbers to PDF documents using the PageNumbersTask. It covers configuring the position, format (including placeholders like {page_number} and {total_pages}), starting number, font styles, colors, and page selection. The task supports various appearance and layer options. ```python from ilovepdf import PageNumbersTask task = PageNumbersTask( public_key="your_public_key", secret_key="your_secret_key" ) task.add_file("/path/to/document.pdf") task.position = "bottom_center" task.format = "Page {page_number} of {total_pages}" task.start_number = 1 task.font_family = "Arial Unicode MS" task.font_style = "Regular" task.font_size = 12 task.font_color = "#000000" task.transparency = 100 task.layer = "above" task.pages = "all" task.show_on_cover = False task.execute() task.download("/path/to/output/folder") ``` -------------------------------- ### Manage Digital Signature Workflow with iLovePDF Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This code snippet illustrates setting up a digital signature workflow using the iLovePDF Python SDK. It initializes a SignTask, adds PDF files, configures multiple signers with their roles and file assignments, sets signature request options like subject, message, language, and expiration, and finally executes the request. ```python from ilovepdf import SignTask from ilovepdf.sign import Signer # Initialize signature task task = SignTask( public_key="your_public_key", secret_key="your_secret_key" ) # Add PDF document to sign (max 5 files) file = task.add_file("/path/to/contract.pdf") # Create and configure first signer signer1 = Signer(name="John Doe", email="john.doe@example.com") signer1.type = "signer" # Options: "signer", "validator", "viewer" signer1.add_file(file) task.add_signer(signer1) # Add additional signers if needed signer2 = Signer(name="Jane Smith", email="jane.smith@example.com") signer2.add_file(file) task.add_signer(signer2) # Configure signature request options task.subject_signer = "Contract Signature Required" task.message_signer = "Please review and sign the attached contract." task.language = "en-US" # Supports many languages: es, fr, de, it, pt, ja, etc. task.expiration_days = 30 # Days until request expires task.lock_order = False # Require signers to sign in order task.signer_reminders = True # Send reminder emails task.signer_reminder_days_cycle = 3 # Days between reminders task.uuid_visible = True # Show signature UUID task.verify_enabled = True # Enable verification # Optional branding # task.brand_name = "Your Company" # task.brand_logo = "https://example.com/logo.png" # Execute (sends signature requests to signers) result = task.execute().result print(f"Signature request created: {result}") # Note: SignTask does not support download() - signed documents # are delivered via email or retrieved through the API ``` -------------------------------- ### Python: Configure iLovePDF with Environment Variables Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Shows how to configure the iLovePDF Python library using environment variables for API credentials and other settings. This approach avoids hardcoding sensitive information directly in the script, enhancing security and flexibility. ```python import os from ilovepdf import CompressTask # Set environment variables (typically in .env file or system environment) os.environ["ILOVEPDF_PUBLIC_KEY"] = "your_public_key" os.environ["ILOVEPDF_SECRET_KEY"] = "your_secret_key" # Optional configuration os.environ["DEFAULT_TIMEOUT_SECONDS"] = "120" os.environ["START_SERVER_URL"] = "https://api.ilovepdf.com" os.environ["PYTHONLOGLEVEL"] = "DEBUG" # Enable debug logging os.environ["PYTHONLOGFILE"] = "/var/log/ilovepdf.log" # Log to file # Initialize task without explicit credentials task = CompressTask() # Uses environment variables automatically task.add_file("/path/to/document.pdf") task.execute() task.download("/path/to/output") ``` -------------------------------- ### Execute Tests with Pytest Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/tests/README.md Commands to run unit, integration, or all tests within the project using the pytest framework. These commands assume the environment is properly configured. ```bash pytest tests/unit pytest tests/integration pytest tests ``` -------------------------------- ### Convert Images to PDF using iLovePDF Python SDK Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This task converts various image formats like JPG, PNG, and GIF into a single PDF document. It provides options for page orientation, size, and margin adjustments. ```python from ilovepdf import ImagePdfTask task = ImagePdfTask(public_key="your_public_key", secret_key="your_secret_key") task.add_file("/path/to/image1.jpg") task.merge_after = True task.execute() task.download("/path/to/output/folder") ``` -------------------------------- ### Validate Integers with IntValidator Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Shows how to validate integer parameters using type checks, positivity constraints, range boundaries, and allowed option sets. ```python from ilovepdf.validators import IntValidator # Validate type IntValidator.validate_type(5) IntValidator.validate_type("5") # Validate positive IntValidator.validate_positive(10, "width") IntValidator.validate_positive(0, "width") # Validate range IntValidator.validate_range(50, 1, 100, "quality") IntValidator.validate_range(150, 1, 100, "quality") # Validate options IntValidator.validate_options(90, {0, 90, 180, 270}, "rotation") IntValidator.validate_options(45, {0, 90, 180, 270}, "rotation") ``` -------------------------------- ### Convert Office Documents to PDF with Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This snippet demonstrates how to convert Microsoft Office documents (like DOCX, XLSX, PPTX) to PDF format using the OfficePdfTask. It requires specifying input files and an output path for the converted PDF. Supported formats include doc, docx, ppt, pptx, xls, xlsx, odt, odp, ods. ```python from ilovepdf import OfficePdfTask task = OfficePdfTask( public_key="your_public_key", secret_key="your_secret_key" ) task.add_file("/path/to/document.docx") task.execute() task.set_output_filename("document.pdf") task.download("/path/to/output/folder") ``` -------------------------------- ### Convert Office Documents to PDF using iLovePDF Python SDK Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This task converts Microsoft Office and OpenDocument formats such as DOCX, XLSX, and PPTX into PDF files. ```python from ilovepdf import OfficePdfTask task = OfficePdfTask(public_key="your_public_key", secret_key="your_secret_key") task.add_file("/path/to/document.docx") task.execute() task.download("/path/to/output/folder") ``` -------------------------------- ### Run Tests in Docker Containers Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/tests/README.md Commands to execute the test suite in isolated environments using Docker Compose for specific Python versions. This ensures compatibility across different runtime versions. ```bash docker-compose -f .docker/docker-compose.yml run python310 docker-compose -f .docker/docker-compose.yml run python311 ``` -------------------------------- ### Python: Handle iLovePDF Exceptions Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Demonstrates how to handle specific exceptions raised by the iLovePDF Python library during task operations. This allows for precise error management based on the type of failure, such as authentication issues, file upload errors, or processing failures. ```python from ilovepdf import CompressTask from ilovepdf.exceptions import ( AuthException, StartException, UploadException, ProcessException, DownloadException, PathException, FileExtensionNotAllowed, FileTooLargeError, InvalidChoiceError, ) try: task = CompressTask( public_key="your_public_key", secret_key="your_secret_key" ) task.add_file("/path/to/document.pdf") task.compression_level = "extreme" task.execute() task.download("/path/to/output") except AuthException as e: print(f"Authentication failed: {e}") # Invalid or missing API credentials except StartException as e: print(f"Failed to start task: {e}") # Server assignment or task initialization failed except FileExtensionNotAllowed as e: print(f"Invalid file type: {e}") # File extension not supported for this task except FileTooLargeError as e: print(f"File too large: {e}") # File exceeds 100MB limit except UploadException as e: print(f"Upload failed: {e}") # File upload to server failed except InvalidChoiceError as e: print(f"Invalid option: {e}") # Invalid value for configuration option except ProcessException as e: print(f"Processing failed: {e}") # Task execution failed on server except DownloadException as e: print(f"Download failed: {e}") # Failed to download processed file except PathException as e: print(f"Invalid path: {e}") # Invalid download destination path ``` -------------------------------- ### Validate Strings with StringValidator Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Demonstrates how to use StringValidator to ensure inputs are strings and not empty. It covers type checking, emptiness checks, and combined validation. ```python from ilovepdf.validators import StringValidator # Validate type only StringValidator.validate_type("filename.pdf", "file_name") StringValidator.validate_type(123, "file_name") # Validate not empty only StringValidator.validate_not_empty("filename.pdf", "file_name") StringValidator.validate_not_empty("", "file_name") # Validate both type and not empty StringValidator.validate("filename.pdf", "file_name") StringValidator.validate("", "file_name") StringValidator.validate(123, "file_name") ``` -------------------------------- ### Convert HTML or URL to PDF using iLovePDF Python SDK Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This task converts web pages or raw HTML content into PDF format. It includes features for viewport control, ad blocking, and popup removal. ```python from ilovepdf import HtmlToPdfTask task = HtmlToPdfTask(public_key="your_public_key", secret_key="your_secret_key") task.add_file_from_url("https://example.com/page.html") task.block_ads = True task.execute() task.download("/path/to/output/folder") ``` -------------------------------- ### PdfToPdfATask - Convert to PDF/A Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Converts standard PDFs to PDF/A archival format. ```APIDOC ## POST /pdf-to-pdfa ### Description Converts a PDF to a specific PDF/A conformance level. ### Method POST ### Endpoint /pdf-to-pdfa ### Parameters #### Request Body - **conformance** (string) - Required - Conformance level (e.g., "pdfa-2b") ### Request Example { "conformance": "pdfa-2b" } ### Response #### Success Response (200) - **status** (string) - Conversion status ``` -------------------------------- ### Validate Floats with FloatValidator Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Illustrates how to validate float values, including type verification, positivity, range constraints, and membership in allowed sets. ```python from ilovepdf.validators import FloatValidator # Validate type FloatValidator.validate_type(5.0) FloatValidator.validate_type("5.0") # Validate positive FloatValidator.validate_positive(10.5, "scale") FloatValidator.validate_positive(0.0, "scale") # Validate range FloatValidator.validate_range(0.75, 0.5, 1.0, "quality") FloatValidator.validate_range(1.5, 0.5, 1.0, "quality") # Validate options FloatValidator.validate_options(0.5, {0.5, 0.75, 1.0}, "quality") FloatValidator.validate_options(0.6, {0.5, 0.75, 1.0}, "quality") ``` -------------------------------- ### Validate Dates with DateValidator Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Shows how to validate date strings against predefined formats and check if they fall within a specified date range. ```python from ilovepdf.validators import DateValidator # Validate format DateValidator.validate_format("31-12-2024") DateValidator.validate_format("2024/12/31") DateValidator.validate_format("31/13/2024") DateValidator.validate_format("2024-31-12") ``` -------------------------------- ### Office to PDF Conversion Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Converts various office document formats (docx, pptx, xlsx, etc.) into PDF files. ```APIDOC ## POST /office-to-pdf ### Description Converts Microsoft Office and OpenOffice documents into PDF format. ### Method POST ### Endpoint /office-to-pdf ### Parameters #### Request Body - **public_key** (string) - Required - API public key - **secret_key** (string) - Required - API secret key - **file** (binary) - Required - The office document to convert ### Request Example { "file": "/path/to/document.docx" } ### Response #### Success Response (200) - **file_url** (string) - URL to download the converted PDF #### Response Example { "file_url": "https://api.ilovepdf.com/v1/download/xyz" } ``` -------------------------------- ### Compress PDF Files using Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Compresses a PDF file using the iLovePDF Python library. Supports different compression levels and custom output filenames. Requires API credentials and the path to the input PDF. ```python from ilovepdf import CompressTask # Initialize with API credentials task = CompressTask( public_key="your_public_key", secret_key="your_secret_key" ) # Add PDF file to compress file = task.add_file("/path/to/document.pdf") # Configure compression level (optional, default is "recommended") task.compression_level = "extreme" # Options: "low", "recommended", "extreme" # Set custom output filename (optional) task.set_output_filename("compressed_document.pdf") # Execute compression task.execute() # Download result to specified folder task.download("/path/to/output/folder") # Access task status after execution print(f"Status: {task.status}") print(f"Remaining credits: {task.remaining_credits}") ``` -------------------------------- ### Split PDF Files using Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Splits a PDF file into multiple parts using various modes like page ranges, fixed intervals, page removal, or file size limits. The result is typically downloaded as a ZIP file. Requires API credentials. ```python from ilovepdf import SplitTask # Initialize split task task = SplitTask( public_key="your_public_key", secret_key="your_secret_key" ) # Add PDF to split task.add_file("/path/to/document.pdf") # Split by page ranges (creates separate PDFs for each range) task.ranges = "1-3,4-6,7-10" # Creates 3 PDFs: pages 1-3, 4-6, 7-10 task.merge_after = True # Optionally merge ranges into single PDF # Alternative: Split every N pages # task.fixed_range = 2 # Split every 2 pages # Alternative: Remove specific pages # task.remove_pages = "1,5,10" # Remove pages 1, 5, and 10 # Alternative: Split by file size (in bytes) # task.filesize = 1024 * 500 # Split into chunks of max 500KB # Execute and download (result is a ZIP file) task.execute() task.set_output_filename("split_result.zip") task.download("/path/to/output/folder") ``` -------------------------------- ### SignTask - Digital Signature Workflow Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This API allows you to create and manage digital signature requests for PDF documents, enabling multiple signers to sign electronically. ```APIDOC ## POST /sign/send ### Description Initiates a digital signature workflow, sending signature requests to specified signers for a given PDF document. ### Method POST ### Endpoint /sign/send ### Parameters #### Request Body - **files** (array of file objects) - Required - The PDF files to be signed (max 5 files). - **signers** (array of signer objects) - Required - A list of signers with their details and assigned files. - **name** (string) - Required - The name of the signer. - **email** (string) - Required - The email address of the signer. - **type** (string) - Optional - The role of the signer ('signer', 'validator', 'viewer'). Defaults to 'signer'. - **files** (array of file objects) - Required - The files assigned to this signer. - **subject_signer** (string) - Optional - The subject line for the signature request email. - **message_signer** (string) - Optional - The message body for the signature request email. - **language** (string) - Optional - The language for the signature request (e.g., 'en-US'). Defaults to 'en-US'. - **expiration_days** (integer) - Optional - Number of days until the signature request expires. Defaults to 7. - **lock_order** (boolean) - Optional - Whether signers must sign in the specified order. Defaults to false. - **signer_reminders** (boolean) - Optional - Whether to send reminder emails to signers. Defaults to false. - **signer_reminder_days_cycle** (integer) - Optional - The interval in days between reminder emails. Defaults to 3. - **uuid_visible** (boolean) - Optional - Whether to display the signature UUID on the document. Defaults to false. - **verify_enabled** (boolean) - Optional - Whether to enable signature verification. Defaults to false. - **brand_name** (string) - Optional - Custom brand name for the signature request. - **brand_logo** (string) - Optional - URL to a custom logo for the signature request. ### Request Example ```python from ilovepdf import SignTask from ilovepdf.sign import Signer task = SignTask(public_key="your_public_key", secret_key="your_secret_key") file = task.add_file("/path/to/contract.pdf") signer1 = Signer(name="John Doe", email="john.doe@example.com") signer1.add_file(file) task.add_signer(signer1) signer2 = Signer(name="Jane Smith", email="jane.smith@example.com") signer2.add_file(file) task.add_signer(signer2) task.subject_signer = "Contract Signature Required" task.message_signer = "Please review and sign the attached contract." task.language = "en-US" task.expiration_days = 30 task.lock_order = False task.signer_reminders = True task.signer_reminder_days_cycle = 3 task.uuid_visible = True task.verify_enabled = True result = task.execute().result print(f"Signature request created: {result}") ``` ### Response #### Success Response (200) - **result** (object) - Information about the created signature request. #### Response Example ```json { "result": { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "status": "sent" } } ``` ``` -------------------------------- ### Run Validator Unit Tests Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Commands to execute unit tests for various validators using pytest. This includes tests for StringValidator, IntValidator, BoolValidator, and ChoiceValidator. ```bash pytest tests/unit/test_string_validator.py -v pytest tests/unit/test_int_validator.py -v pytest tests/unit/test_bool_validator.py -v pytest tests/unit/test_choice_validator.py -v # To execute all validator tests in a single command: pytest tests/unit/test_string_validator.py tests/unit/test_int_validator.py tests/unit/test_bool_validator.py tests/unit/test_choice_validator.py -v ``` -------------------------------- ### Validate PDF Conformance with iLovePDF Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This snippet demonstrates how to validate a PDF file against a specified conformance level using the iLovePDF Python SDK. It configures the task with the file, conformance level, and allows downgrading if necessary, then executes the validation and prints the result. ```python from ilovepdf import ILovePdfClient client = ILovePdfClient("your_public_key", "your_secret_key") task = client.validation_task() # Add PDF file to validate task.add_file("/path/to/document.pdf") # Configure conformance level to validate against task.conformance = "pdfa-2b" task.allow_downgrade = True # Execute validation task.execute() # Check validation result result = task.validation_result if result: print(f"Status: {result.get('status')}") # "Conformant" or "NonConformant" print(f"Details: {result}") ``` -------------------------------- ### Validate PDF/A Compliance with Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This snippet shows how to validate if a PDF file complies with PDF/A archival standards using the ValidatePdfATask. The task takes a PDF file as input and checks its adherence to the specified PDF/A conformance levels. This is essential for ensuring documents meet archival requirements. ```python from ilovepdf import ValidatePdfATask task = ValidatePdfATask( public_key="your_public_key", secret_key="your_secret_key" ) # Add PDF file to validate task.add_file("/path/to/document.pdf") # Execute validation task.execute() # Download validation report (optional) task.download("/path/to/output/folder") ``` -------------------------------- ### Password Protect PDF using Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Adds password protection to a PDF file using the iLovePDF Python library. Requires API credentials, the input PDF path, and a password. ```python from ilovepdf import ProtectTask # Initialize protect task task = ProtectTask( public_key="your_public_key", secret_key="your_secret_key" ) # Add PDF to protect task.add_file("/path/to/document.pdf") # Set password (required) task.password = "secure_password_123" # Execute protection task.execute() # Download protected PDF task.set_output_filename("protected_document.pdf") task.download("/path/to/output/folder") ``` -------------------------------- ### Convert PDF to JPG using iLovePDF Python SDK Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This task converts PDF pages into individual JPG images or extracts embedded images from the PDF. The output is typically provided as a ZIP archive. ```python from ilovepdf import PdfToJpgTask task = PdfToJpgTask(public_key="your_public_key", secret_key="your_secret_key") task.add_file("/path/to/document.pdf") task.pdfjpg_mode = "pages" task.execute() task.download("/path/to/output/folder") ``` -------------------------------- ### Validate Booleans with BoolValidator Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Demonstrates strict boolean validation to ensure input is exactly True or False. ```python from ilovepdf.validators import BoolValidator BoolValidator.validate(True, "flatten") BoolValidator.validate("true", "flatten") ``` -------------------------------- ### Repair Corrupted PDF Files with Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This snippet shows how to repair corrupted or damaged PDF files using the RepairTask. The task takes a single corrupted PDF file as input, attempts to fix it, and saves the repaired version to a specified output location. This is useful for recovering data from damaged documents. ```python from ilovepdf import RepairTask task = RepairTask( public_key="your_public_key", secret_key="your_secret_key" ) task.add_file("/path/to/corrupted_document.pdf") task.execute() task.set_output_filename("repaired_document.pdf") task.download("/path/to/output/folder") ``` -------------------------------- ### Merge Multiple PDFs using Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Merges multiple PDF files into a single document using the iLovePDF Python library. Files are merged in the order they are added. Requires API credentials and paths to the input PDFs. ```python from ilovepdf import MergeTask # Initialize merge task task = MergeTask( public_key="your_public_key", secret_key="your_secret_key" ) # Add multiple PDF files in desired order task.add_file("/path/to/document1.pdf") task.add_file("/path/to/document2.pdf") task.add_file("/path/to/document3.pdf") # Execute the merge operation task.execute() # Set output filename and download task.set_output_filename("merged_document.pdf") task.download("/path/to/output/folder") ``` -------------------------------- ### RepairTask - Repair Corrupted PDF Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Attempts to recover data from corrupted or damaged PDF files. ```APIDOC ## POST /repair ### Description Attempts to fix structural issues in a corrupted PDF file. ### Method POST ### Endpoint /repair ### Request Example { "file": "corrupted.pdf" } ### Response #### Success Response (200) - **status** (string) - Success message ``` -------------------------------- ### Add Watermarks to PDF using iLovePDF Python SDK Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This task allows users to add text or image watermarks to PDF files. It supports extensive customization including font settings, transparency, rotation, and positioning. ```python from ilovepdf import WatermarkTask task = WatermarkTask(public_key="your_public_key", secret_key="your_secret_key") task.add_file("/path/to/document.pdf") task.mode = "text" task.text = "CONFIDENTIAL" task.font_size = 48 task.rotation = 45 task.execute() task.download("/path/to/output/folder") ``` -------------------------------- ### PDF Validation API Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This section details how to use the PDF validation task to check if a PDF document conforms to specific standards like PDF/A. ```APIDOC ## POST /pdf/validate ### Description Validates a PDF file against a specified conformance level (e.g., PDF/A). ### Method POST ### Endpoint /pdf/validate ### Parameters #### Request Body - **file** (file) - Required - The PDF file to validate. - **conformance** (string) - Optional - The conformance level to validate against (e.g., "pdfa-2b"). Defaults to "pdfa-1b". - **allow_downgrade** (boolean) - Optional - Whether to allow downgrading the PDF version if necessary. Defaults to false. ### Request Example ```python from ilovepdf import ILovePDFClient client = ILovePDFClient(public_key="your_public_key", secret_key="your_secret_key") task = client.new_task('validate') task.add_file("/path/to/document.pdf") task.conformance = "pdfa-2b" task.allow_downgrade = True task.execute() result = task.validation_result print(result) ``` ### Response #### Success Response (200) - **status** (string) - The validation status (e.g., "Conformant", "NonConformant"). - **details** (object) - Detailed information about the validation result. #### Response Example ```json { "status": "Conformant", "details": { "message": "The document is conformant to PDF/A-2b." } } ``` ``` -------------------------------- ### PdfOcrTask - Perform OCR Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Performs Optical Character Recognition on scanned PDFs to extract searchable text. ```APIDOC ## POST /ocr ### Description Extracts text from image-based or scanned PDFs using OCR. ### Method POST ### Endpoint /ocr ### Parameters #### Request Body - **ocr_languages** (string/array) - Optional - Language codes for OCR (e.g., "eng", "fra") ### Request Example { "ocr_languages": "eng" } ### Response #### Success Response (200) - **status** (string) - Task completion status ``` -------------------------------- ### Remove PDF Password Protection using Python Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Removes password protection from a PDF file using the iLovePDF Python library, provided authorization is granted. Requires API credentials and the path to the protected PDF. ```python from ilovepdf import UnlockTask # Initialize unlock task task = UnlockTask( public_key="your_public_key", secret_key="your_secret_key" ) # Add password-protected PDF task.add_file("/path/to/protected_document.pdf") # Execute unlock operation task.execute() # Download unlocked PDF task.set_output_filename("unlocked_document.pdf") task.download("/path/to/output/folder") ``` -------------------------------- ### ExtractTask - Extract Text Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Extracts raw text content from PDF files. ```APIDOC ## POST /extract ### Description Extracts text content from a PDF file, with options for detailed metadata. ### Method POST ### Endpoint /extract ### Parameters #### Request Body - **detailed** (boolean) - Optional - If true, includes position and font info ### Request Example { "detailed": false } ### Response #### Success Response (200) - **text** (string) - Extracted content ``` -------------------------------- ### Rotate PDF Pages using iLovePDF Python SDK Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This task rotates pages within a PDF document by 90, 180, or 270 degrees. It allows for individual file rotation settings before execution. ```python from ilovepdf import RotateTask task = RotateTask(public_key="your_public_key", secret_key="your_secret_key") task.add_file("/path/to/document.pdf", rotate=90) task.execute() task.download("/path/to/output/folder") ``` -------------------------------- ### PageNumbersTask - Add Page Numbers Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt Adds customizable page numbers to existing PDF documents. ```APIDOC ## POST /page-numbers ### Description Appends page numbers to a PDF with configurable typography and positioning. ### Method POST ### Endpoint /page-numbers ### Parameters #### Request Body - **position** (string) - Required - Placement of the page number - **format** (string) - Required - String template for page numbering - **font_size** (integer) - Required - Font size in points ### Request Example { "position": "bottom_center", "format": "Page {page_number} of {total_pages}" } ### Response #### Success Response (200) - **status** (string) - Task completion status ``` -------------------------------- ### EditPdfTask - Edit PDF Elements Source: https://context7.com/ilovepdf/ilovepdf-python/llms.txt This API enables you to add, modify, and style various elements such as text, images, and SVGs directly onto PDF pages. ```APIDOC ## POST /edit/add_elements ### Description Adds custom elements (text, images, SVGs) to specific pages of a PDF document with precise control over positioning, styling, and layering. ### Method POST ### Endpoint /edit/add_elements ### Parameters #### Request Body - **file** (file) - Required - The PDF file to edit. - **elements** (array of element objects) - Required - A list of elements to add to the PDF. - **type** (string) - Required - The type of element ('text', 'image', 'svg'). - **pages** (string) - Required - The page(s) to apply the element to (e.g., '1', '1-3', 'all'). - **zindex** (integer) - Optional - The stacking order of the element. Higher values are on top. Defaults to 0. - **coordinates** (object) - Required - The X and Y coordinates for the element's position. - **x** (float) - Required - The X-coordinate. - **y** (float) - Required - The Y-coordinate. - **dimensions** (object) - Optional - The width and height of the element. - **w** (float) - Optional - The width. - **h** (float) - Optional - The height. - **rotation** (integer) - Optional - The rotation angle in degrees (0-360). Defaults to 0. - **opacity** (integer) - Optional - The opacity level (1-100). Defaults to 100. - **text** (string) - Required if type is 'text' - The text content. - **font_family** (string) - Optional if type is 'text' - The font family (e.g., 'Arial Unicode MS'). - **font_size** (integer) - Optional if type is 'text' - The font size. - **font_style** (string) - Optional if type is 'text' - The font style ('Regular', 'Bold', 'Italic', 'Bold italic'). - **font_color** (string) - Optional if type is 'text' - The font color in hex format (e.g., '#008000') or 'transparent'. - **text_align** (string) - Optional if type is 'text' - Text alignment ('left', 'center', 'right'). - **letter_spacing** (integer) - Optional if type is 'text' - Spacing between letters. - **image** (string) - Required if type is 'image' - Base64 encoded image data or a URL to the image. - **svg** (string) - Required if type is 'svg' - The SVG content as a string. ### Request Example ```python from ilovepdf import EditPdfTask task = EditPdfTask(public_key="your_public_key", secret_key="your_secret_key") task.add_file("/path/to/document.pdf") # Add text element text_element = task.add_element() text_element.type = "text" text_element.text = "APPROVED" text_element.pages = "1" text_element.coordinates = {"x": 100.0, "y": 700.0} text_element.font_family = "Arial Unicode MS" text_element.font_size = 24 text_element.font_color = "#008000" # Add image element image_element = task.add_element() image_element.type = "image" image_element.pages = "all" image_element.coordinates = {"x": 400.0, "y": 50.0} image_element.set_image("/path/to/stamp.png") task.execute() task.set_output_filename("edited_document.pdf") task.download("/path/to/output/folder") ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### ChoiceValidator: Validate Allowed Choices Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Ensures that a given value is present within a set of allowed choices. This validator can raise a default InvalidChoiceError or a custom exception class specified by the user. It's useful for validating parameters like file formats or rotation angles. ```python from ilovepdf.validators import ChoiceValidator from ilovepdf.exceptions import InvalidChoiceError # Validate with default error ChoiceValidator.validate("jpg", ["jpg", "png", "gif"], "format") # OK ChoiceValidator.validate("bmp", ["jpg", "png", "gif"], "format") # Raises InvalidChoiceError # Validate with custom error from ilovepdf.exceptions import IntNotInAllowedSetError ChoiceValidator.validate( 90, {0, 90, 180, 270}, "rotation", cls_error=IntNotInAllowedSetError ) # OK or raises IntNotInAllowedSetError ``` -------------------------------- ### StringValidator: Validate String Properties Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Validates string inputs, ensuring they are not empty and are of the correct type. This validator is often used in setters for task parameters to enforce data integrity before processing. ```python from ilovepdf.validators import StringValidator # Example of using StringValidator in a setter class ExampleTask: @property def file_name(self) -> str: """Gets the file name.""" return self._file_name @file_name.setter def file_name(self, value: str): """ Sets the file name. Args: value (str): Must be a non-empty string. Raises: TypeError: If value is not a string. ValueError: If value is an empty string. """ StringValidator.validate(value, "file_name") self._file_name = value ``` -------------------------------- ### DateValidator: Validate Date Range Source: https://github.com/ilovepdf/ilovepdf-python/blob/dev/ilovepdf/validators/README.md Validates if a given date string falls within a specified minimum and maximum date. It raises a ValueError if the date is out of range or in an invalid format. It also handles TypeError if the input is not a string. ```python from ilovepdf.validators import DateValidator DateValidator.validate_in_range("31-12-2024", min_date="01-01-2024", max_date="31-12-2024") # OK DateValidator.validate_in_range("01-01-2023", min_date="01-01-2024", max_date="31-12-2024") # Raises ValueError (out of range) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.