### Full pypandoc Setup and Usage Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Installs pypandoc with its binary, verifies the installation, and performs a basic document conversion. ```bash # Install pypandoc with binary pip install pypandoc_binary # Verify installation pypandoc version # Use pypandoc for conversions pypandoc pandoc document.md -o document.html ``` -------------------------------- ### CI/CD Pipeline Setup and Conversion Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Automates the installation of pypandoc and pandoc, verifies the installation, and converts documentation files within a CI/CD environment. ```bash #!/bin/bash set -e # Install pypandoc and pandoc pip install pypandoc_binary # Verify installation pypandoc version # Convert documentation pypandoc pandoc docs/*.md -o docs.html # Or use Python API python -c "import pypandoc; pypandoc.convert_file('README.md', 'html')" ``` -------------------------------- ### Output Mode Examples Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Illustrates how to get output as a string or write it directly to a file using the `outputfile` argument. ```python # Return as string (default) output = pypandoc.convert_text('# Hello', 'html', format='md') ``` ```python # Write to file (required for binary formats) pypandoc.convert_file('doc.md', 'docx', outputfile='doc.docx') ``` -------------------------------- ### Docker Setup for pypandoc Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Configures a Docker image with pypandoc, including options for installing with a bundled pandoc or downloading pandoc separately. Includes verification and setting the working directory. ```dockerfile FROM python:3.11 # Install pypandoc with bundled pandoc RUN pip install pypandoc_binary # Or install pypandoc and download pandoc RUN pip install pypandoc && \ pypandoc download --target /usr/local/bin # Verify RUN pypandoc version WORKDIR /app COPY . . # Use in entrypoint CMD ["python", "script.py"] ``` -------------------------------- ### Typical Documentation Build Workflow Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/usage-patterns.md A comprehensive example demonstrating a typical documentation build process. It includes checking pandoc availability, downloading if necessary, getting format information, creating an output directory, and converting Markdown files to HTML with extra arguments and filters. ```python import pypandoc from pathlib import Path def build_documentation(): # Check pandoc availability try: pypandoc.get_pandoc_path() except OSError: print("Installing pandoc...") pypandoc.download_pandoc() # Get format info input_formats, output_formats = pypandoc.get_pandoc_formats() print(f"Pandoc version: {pypandoc.get_pandoc_version()}") # Create output directory output_dir = Path('docs/html') output_dir.mkdir(parents=True, exist_ok=True) # Convert all markdown files for md_file in Path('docs/source').glob('*.md'): html_file = output_dir / md_file.with_suffix('.html').name print(f"Converting {md_file}...") try: pypandoc.convert_file( md_file, 'html5', outputfile=html_file, extra_args=['--toc', '--css', 'style.css'], filters=['pandoc-citeproc'] ) print(f" -> {html_file}") except RuntimeError as e: print(f" ERROR: {e}") print("Build complete!") if __name__ == '__main__': build_documentation() ``` -------------------------------- ### pypandoc CLI Subcommands Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md These examples demonstrate how to use pypandoc's subcommands for version checking, passing arguments directly to pandoc, and downloading pandoc. Ensure pandoc is installed or use the download command. ```bash # Show versions pypandoc version # Output: pypandoc X.Y, pandoc X.Y.Z, pytinytex (if installed) ``` ```bash # Pass arguments to pandoc pypandoc pandoc # Example: pypandoc pandoc input.md -o output.html ``` ```bash # Download pandoc pypandoc download [--version VERSION] [--target FOLDER] [--url URL] [--delete-installer] [--download-folder FOLDER] ``` -------------------------------- ### Handle Linux pandoc installation Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md Extracts a .deb installer and installs pandoc on Linux systems. ```python def _handle_linux(filename: str, targetfolder: str) -> None: """Extract .deb installer and install pandoc on Linux.""" ``` -------------------------------- ### Handle Windows pandoc installation Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md Extracts an .msi installer and installs pandoc on Windows systems. ```python def _handle_win32(filename: str, targetfolder: str) -> None: """Extract .msi installer and install pandoc on Windows.""" ``` -------------------------------- ### Handle macOS pandoc installation Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md Extracts a .pkg installer and installs pandoc on macOS. ```python def _handle_darwin(filename: str, targetfolder: str) -> None: """Extract .pkg installer and install pandoc on macOS.""" ``` -------------------------------- ### Use sandbox mode (pandoc >= 2.15) Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-info.md This example demonstrates how to enable sandbox mode for pandoc conversion, which is available starting from pandoc version 2.15. Sandbox mode enhances security by isolating pandoc's operations. ```python if pypandoc.ensure_pandoc_minimal_version(2, 15): output = pypandoc.convert_text( '# Hello', 'html', format='md', sandbox=True ) ``` -------------------------------- ### Install Pandoc System-Wide Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md Instructions for installing Pandoc on different operating systems. This is a common solution when pypandoc cannot locate the Pandoc executable. ```bash # Ubuntu/Debian sudo apt-get install pandoc # macOS brew install pandoc # Windows - download from https://pandoc.org/installing.html ``` -------------------------------- ### Format String Examples Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Demonstrates how to use format extensions with '+' to enable features or '-' to disable them. ```python 'markdown+strikethrough' # Enable strikethrough ``` ```python 'markdown-pipe_tables' # Disable pipe tables ``` ```python 'rst+raw_html' # Enable raw HTML in RST ``` -------------------------------- ### Installation Functions Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Functions for downloading and ensuring pandoc is installed. ```APIDOC ## download_pandoc ### Description Downloads a specific version of pandoc. ### Parameters - **url** (Union[str, None]) - Optional - The direct download URL for pandoc. If None, a default URL is used. - **targetfolder** (Union[str, None]) - Optional - The folder to extract pandoc to. If None, a default location is used. - **version** (str) - Optional - The pandoc version to download. Defaults to "latest". - **delete_installer** (bool) - Optional - Whether to delete the installer after extraction. Defaults to False. - **download_folder** (Union[str, None]) - Optional - The folder to temporarily store the downloaded installer. If None, a default location is used. ### Returns - None ``` ```APIDOC ## ensure_pandoc_installed ### Description Ensures that pandoc is installed, downloading it if necessary. ### Parameters - **url** (Union[str, None]) - Optional - The direct download URL for pandoc. If None, a default URL is used. - **targetfolder** (Union[str, None]) - Optional - The folder to extract pandoc to. If None, a default location is used. - **version** (str) - Optional - The pandoc version to ensure is installed. Defaults to "latest". - **delete_installer** (bool) - Optional - Whether to delete the installer after extraction. Defaults to False. ### Returns - None ``` -------------------------------- ### Installation & Verification Functions Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md Functions for downloading, installing, and verifying pandoc. ```APIDOC ## download_pandoc ### Description Downloads a specific version of pandoc. ### Signature ```python download_pandoc(url=None, targetfolder=None, version="latest", delete_installer=False, download_folder=None) ``` ### Parameters - **url** (str, optional) - The URL to download pandoc from. Defaults to None. - **targetfolder** (str, optional) - The folder to install pandoc into. Defaults to None. - **version** (str, optional) - The version of pandoc to download. Defaults to "latest". - **delete_installer** (bool, optional) - Whether to delete the installer after installation. Defaults to False. - **download_folder** (str, optional) - The folder to download the installer to. Defaults to None. ### Returns - None ``` ```APIDOC ## ensure_pandoc_installed ### Description Ensures that pandoc is installed, downloading it if necessary. ### Signature ```python ensure_pandoc_installed(url=None, targetfolder=None, version="latest", delete_installer=False) ``` ### Parameters - **url** (str, optional) - The URL to download pandoc from. Defaults to None. - **targetfolder** (str, optional) - The folder to install pandoc into. Defaults to None. - **version** (str, optional) - The version of pandoc to download. Defaults to "latest". - **delete_installer** (bool, optional) - Whether to delete the installer after installation. Defaults to False. ### Returns - None ``` ```APIDOC ## ensure_pandoc_minimal_version ### Description Ensures that the installed pandoc meets a minimum version requirement. ### Signature ```python ensure_pandoc_minimal_version(major: int, minor: int = 0) ``` ### Parameters - **major** (int) - The major version number. - **minor** (int, optional) - The minor version number. Defaults to 0. ### Returns - bool: True if the pandoc version meets the requirement, False otherwise. ``` ```APIDOC ## ensure_pandoc_maximal_version ### Description Ensures that the installed pandoc does not exceed a maximum version. ### Signature ```python ensure_pandoc_maximal_version(major: int, minor: int = 9999) ``` ### Parameters - **major** (int) - The major version number. - **minor** (int, optional) - The minor version number. Defaults to 9999. ### Returns - bool: True if the pandoc version does not exceed the maximum, False otherwise. ``` -------------------------------- ### Download Pandoc via pypandoc Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md Use pypandoc's built-in function to download and install Pandoc. This is an alternative to system-wide installation. ```python import pypandoc pypandoc.download_pandoc() ``` -------------------------------- ### Show pypandoc, pandoc, and pytinytex Versions Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Use the 'version' command to quickly verify that pypandoc, pandoc, and pytinytex are installed and to check their respective versions. ```bash pypandoc version ``` -------------------------------- ### Install Pandoc using pypandoc-binary Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md If you encounter a 'Pandoc not found' error, you can install pandoc using the pypandoc-binary package. Alternatively, use the pypandoc download CLI command. ```bash pip install pypandoc_binary # Includes pandoc # OR pypandoc download # CLI command ``` -------------------------------- ### Download Pandoc and Delete Installer Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Downloads a specific pandoc version, installs it, and then deletes the installer file to save disk space. This is useful for automated installations. ```bash pypandoc download --version 3.1.2 --delete-installer ``` -------------------------------- ### Get Supported Pandoc Formats Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/README.md Retrieves the input and output formats supported by the installed Pandoc version. This is useful for validating conversion capabilities. ```python import pypandoc input_fmt, output_fmt = pypandoc.get_pandoc_formats() print(f"Can convert to: {', '.join(output_fmt)}") ``` -------------------------------- ### ensure_pandoc_installed Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md Attempts to install pandoc if it is not already installed. If pandoc is found on the system PATH, this function does nothing. Otherwise, it downloads and installs pandoc using the provided parameters. ```APIDOC ## ensure_pandoc_installed ### Description Attempts to install pandoc if it is not already installed. If pandoc is found on the system PATH, this function does nothing. Otherwise, it downloads and installs pandoc using the provided parameters. ### Signature ```python def ensure_pandoc_installed( url: Union[str, None] = None, targetfolder: Union[str, None] = None, version: str = "latest", delete_installer: bool = False, ) -> None ``` ### Parameters #### Path Parameters - **url** (str | None) - Optional - URL to pandoc binary. Passed to `download_pandoc()` - **targetfolder** (str | None) - Optional - Installation folder. Passed to `download_pandoc()`. Also appended to PATH - **version** (str) - Optional - Pandoc version to download. Passed to `download_pandoc()`. Default: 'latest' - **delete_installer** (bool) - Optional - Delete installer after extraction. Passed to `download_pandoc()`. Default: False ### Return Value Returns `None`. Raises on error. ### Exceptions - `OSError`: If pandoc cannot be installed and is not already available ### Examples #### Ensure pandoc is installed ```python import pypandoc pypandoc.ensure_pandoc_installed() ``` #### Install to custom location if needed ```python pypandoc.ensure_pandoc_installed( targetfolder='~/.local/bin', version='3.1.2' ) ``` ``` -------------------------------- ### Install pypandoc via pip Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Use this command to install the pypandoc package if you plan to manage pandoc installation separately. ```bash pip install pypandoc ``` -------------------------------- ### Install pypandoc with pandoc binary via pip Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Install the pypandoc_binary package to include pandoc directly with the pypandoc installation. This is convenient for immediate use. ```bash pip install pypandoc_binary ``` -------------------------------- ### pypandoc convert_file Examples Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/types.md Shows various ways to specify source files for `convert_file`, including string paths, glob patterns, Path objects, lists, and iterators. ```python import pypandoc from pathlib import Path # String path pypandoc.convert_file('doc.md', 'rst') # String glob pattern pypandoc.convert_file('*.md', 'rst') # pathlib.Path pypandoc.convert_file(Path('doc.md'), 'rst') # List of paths pypandoc.convert_file(['ch1.md', 'ch2.md'], 'rst') # Pathlib glob iterator pypandoc.convert_file(Path('.').glob('*.md'), 'rst') ``` -------------------------------- ### Specify Custom Installation Folder Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md Customize the installation directory by providing a path to the `targetfolder` parameter. This allows for flexible installation locations outside of default system paths. ```python pypandoc.download_pandoc(targetfolder='/opt/pandoc') ``` -------------------------------- ### Get Pandoc Version and Path Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Retrieve the installed Pandoc version, its executable path, and supported formats using utility functions. Useful for system checks and debugging. ```python print(pypandoc.get_pandoc_version()) print(pypandoc.get_pandoc_path()) print(pypandoc.get_pandoc_formats()) ``` -------------------------------- ### Download to Temporary Folder Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md Specify a temporary directory for downloading the installer using the `download_folder` parameter. This is useful for managing temporary files, especially on systems with limited space in the current directory. ```python pypandoc.download_pandoc( version='3.1', targetfolder='~/.local/bin', download_folder='/tmp' ) ``` -------------------------------- ### Download Pandoc to Custom Location Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Installs the latest pandoc to a specified custom directory, such as '/usr/local/bin'. This allows for flexible installation paths. ```bash pypandoc download --target /usr/local/bin ``` -------------------------------- ### Input Source Examples for convert_file Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Shows various ways to specify input files for the `convert_file` function, including single files, glob patterns, lists, and iterators. ```python pypandoc.convert_file('file.md', 'html') # Single file ``` ```python pypandoc.convert_file('*.md', 'html') # Glob pattern ``` ```python pypandoc.convert_file(['ch1.md', 'ch2.md'], 'html') # List of files ``` ```python pypandoc.convert_file(Path('.').glob('*.md'), 'html') # pathlib iterator ``` -------------------------------- ### Troubleshoot Download to Specific Target Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Demonstrates how to specify a target directory for pandoc downloads to resolve permission issues or customize installation location. ```bash # Use home directory pypandoc download --target ~/ # Or use sudo (if appropriate) sudo pypandoc download --target /usr/local/bin ``` -------------------------------- ### Download and Delete Installer Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md To save disk space after installation, set `delete_installer` to `True`. This will remove the downloaded installer file once pandoc has been successfully extracted and installed. ```python pypandoc.download_pandoc(version='latest', delete_installer=True) ``` -------------------------------- ### Handle Missing Pandoc Installation Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/usage-patterns.md Catch OSError if Pandoc is not found and attempt to download it using pypandoc.download_pandoc. After downloading, retry the conversion. ```python import pypandoc try: output = pypandoc.convert_file('document.md', 'rst') except OSError: # Pandoc not found, try to install it pypandoc.download_pandoc(version='latest') # Retry conversion output = pypandoc.convert_file('document.md', 'rst') ``` -------------------------------- ### Install Pypandoc with TinyTeX Support Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/configuration.md Install pypandoc with optional TinyTeX support for automatic LaTeX package management during PDF conversions. This also triggers the download of TinyTeX. ```bash pip install pypandoc[tinytex] pytinytex download ``` -------------------------------- ### Install pypandoc via conda Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Install pypandoc using conda, which also installs pandoc. Ensure the conda-forge channel is added for availability. ```bash conda install -c conda-forge pypandoc ``` -------------------------------- ### Ensure Pandoc is Installed Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md This snippet ensures that pandoc is installed and available on the system's PATH. It's a basic usage that relies on default settings. ```python import pypandoc pypandoc.ensure_pandoc_installed() ``` -------------------------------- ### download_pandoc Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md Downloads and installs pandoc binaries for the current platform. It supports specifying a custom URL, installation folder, pandoc version, and whether to delete the installer after extraction. ```APIDOC ## Function: download_pandoc ### Description Downloads and installs pandoc binaries for the current platform. It supports specifying a custom URL, installation folder, pandoc version, and whether to delete the installer after extraction. ### Signature ```python def download_pandoc( url: Union[str, None] = None, targetfolder: Union[str, None] = None, version: str = "latest", delete_installer: bool = False, download_folder: Union[str, None] = None, ) -> None ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **url** (str | None) - Optional - URL to pandoc binary distribution. Defaults to fetching from GitHub API. - **targetfolder** (str | None) - Optional - Directory for pandoc binary installation. Defaults to platform-specific locations. - **version** (str) - Optional - Pandoc version to download (e.g., '3.1', '2.19.2') or 'latest'. Defaults to 'latest'. - **delete_installer** (bool) - Optional - Whether to delete the installer file after extraction. Defaults to False. - **download_folder** (str | None) - Optional - Temporary folder for downloading the installer. Defaults to the current directory. ### Request Example ```python import pypandoc pypandoc.download_pandoc() ``` ### Response #### Success Response (None) Returns None upon successful execution. #### Response Example None ### Exceptions - `RuntimeError`: If the specified version is invalid, the platform is unsupported, or the system architecture is not 64-bit. - `OSError`: If the target folder cannot be created or files cannot be written. ``` -------------------------------- ### Install Pandoc to Custom Location and Specific Version Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md This snippet installs pandoc to a specified target folder and a particular version if it's not already installed. The target folder is added to the system's PATH. ```python pypandoc.ensure_pandoc_installed( targetfolder='~/.local/bin', version='3.1.2' ) ``` -------------------------------- ### Environment Setup for Pandoc Execution Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/architecture.md Describes the environment variables and configurations prepared by `_convert_input()` to ensure pandoc and its dependencies (like pandoc-citeproc and TinyTeX) are accessible. ```python _convert_input() prepares environment: new_env = os.environ.copy() Add to PATH: - pypandoc/files (for pandoc-citeproc) - TinyTeX bin directory (if PDF conversion) Other env setup: - Set HOME to temp dir (if not set) for pandoc - Create with flag 0x08000000 on Windows (no console) These ensure: - pandoc-citeproc is discoverable - LaTeX engines are available - Process doesn't spawn console window ``` -------------------------------- ### Check Pandoc Format Support Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Retrieve supported input and output formats from Pandoc. This example checks if PDF conversion is available. ```python import pypandoc input_formats, output_formats = pypandoc.get_pandoc_formats() if 'pdf' in output_formats: print("PDF conversion is available") ``` -------------------------------- ### Check pypandoc Version Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Use this command to check the installed version of pypandoc. ```bash python -m pypandoc version ``` -------------------------------- ### Default pandoc target folders Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md Defines default installation directories for pandoc binaries based on the operating system. ```python DEFAULT_TARGET_FOLDER = { "win32": "~\\AppData\\Local\\Pandoc", "linux": "~/bin", "darwin": "~/Applications/pandoc", } ``` -------------------------------- ### Download Latest Pandoc Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Downloads the latest pandoc release to the default platform-specific location. This is the simplest way to install pandoc using pypandoc. ```bash pypandoc download ``` -------------------------------- ### Get Supported Pandoc Formats Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-info.md Retrieves and prints the first 5 input and output formats supported by pandoc. Requires importing the pypandoc library. ```python import pypandoc input_formats, output_formats = pypandoc.get_pandoc_formats() print("Input formats:", input_formats[:5]) print("Output formats:", output_formats[:5]) ``` -------------------------------- ### Download Pandoc from Custom URL Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/cli-reference.md Downloads pandoc from a custom URL, which is useful in corporate environments or when using specific builds. The URL should point directly to the installer file. ```bash pypandoc download --url https://example.com/custom-pandoc-3.1.2.deb ``` -------------------------------- ### Check Minimum Pandoc Version Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-info.md Compares the installed pandoc version against a minimum requirement. This snippet demonstrates a direct version string comparison. ```python version = pypandoc.get_pandoc_version() if version >= "2.19": print("Pandoc 2.19 or later is installed") ``` -------------------------------- ### Conversion Error with LaTeX Hints (pytinytex installed) Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md Example of a RuntimeError during PDF conversion when pytinytex is installed but cannot auto-install missing LaTeX packages. ```text RuntimeError: Pandoc died with exitcode "43" during conversion: {stderr} Hint: pytinytex is installed but could not resolve the missing LaTeX packages. You may need to install them manually with pytinytex.install(''). ``` -------------------------------- ### Download Specific Pandoc Version Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md To install a particular version of pandoc, provide the version string to the `version` parameter. This is useful for ensuring compatibility with specific project requirements. ```python pypandoc.download_pandoc(version='3.1.2') ``` -------------------------------- ### Set PYPANDOC_PANDOC Environment Variable Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md Configure the PYPANDOC_PANDOC environment variable to point to the Pandoc executable. This is useful if Pandoc is installed in a non-standard location. ```python import os os.environ['PYPANDOC_PANDOC'] = '/path/to/pandoc' ``` -------------------------------- ### Conversion Error with LaTeX Hints (without pytinytex) Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md Example of a RuntimeError during PDF conversion when pytinytex is not installed, suggesting installation for automatic LaTeX package management. ```text RuntimeError: Pandoc died with exitcode "43" during conversion: {stderr} Hint: Install pypandoc[tinytex] for automatic LaTeX package management: pip install pypandoc[tinytex] ``` -------------------------------- ### Convert Markdown to PDF with TinyTeX Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Perform PDF conversion after installing pypandoc with TinyTeX support. pypandoc automatically handles LaTeX engine setup and package installation. ```python import pypandoc pypandoc.convert_file('document.md', 'pdf', outputfile='document.pdf') ``` -------------------------------- ### Check Pandoc Availability with Python Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/usage-patterns.md Use this snippet to verify if Pandoc is installed and accessible. It prints the Pandoc path if found, otherwise, it catches an OSError. ```python import pypandoc try: path = pypandoc.get_pandoc_path() print(f"Using pandoc at: {path}") except OSError as e: print(f"Pandoc not found: {e}") # Handle missing pandoc ``` -------------------------------- ### Get Pandoc Version API Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Retrieve the installed Pandoc version as a string using `get_pandoc_version`. ```python def get_pandoc_version() -> str ``` -------------------------------- ### Using pathlib.Path for Input/Output Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md Demonstrates using `pathlib.Path` objects for specifying input and output files. This approach leverages modern Python file path handling. ```python from pathlib import Path input_file = Path('document.md') output_file = input_file.with_suffix('.docx') pypandoc.convert_file(input_file, 'docx', outputfile=output_file) ``` -------------------------------- ### TinyTeX Integration for PDF Conversion Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/architecture.md Describes how pypandoc integrates with TinyTeX for PDF/LaTeX conversions. It covers pre-execution setup, post-execution error parsing, automatic package installation, retries, and helpful error messaging. ```python If converting to PDF/LaTeX and pytinytex available: Before execution: - Call _try_setup_tinytex(): Add TinyTeX to PATH After execution (if failed): - Parse stderr with pytinytex.parse_log() - Install each missing package - Retry pandoc (up to 3 attempts total) - Log installed packages After final failure: - Provide helpful hint in error message ``` -------------------------------- ### Get Pandoc Version Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-info.md Retrieves the installed pandoc version string. This function caches its result after the first call for performance. It uses the `pandoc --version` command and parses the output to extract the semantic version. ```python import pypandoc version = pypandoc.get_pandoc_version() print(f"Pandoc version: {version}") # e.g., "2.19.2" ``` -------------------------------- ### Convert File and Text with pypandoc Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Demonstrates basic file and text conversion using pypandoc. The input format can be inferred from the filename or specified explicitly. ```python import pypandoc # With an input file: it will infer the input format from the filename output = pypandoc.convert_file('somefile.md', 'rst') # ...but you can overwrite the format via the `format` argument: output = pypandoc.convert_file('somefile.txt', 'rst', format='md') # alternatively you could just pass some string. In this case you need to # define the input format: output = pypandoc.convert_text('# some title', 'rst', format='md') # output == 'some title\r\n==========\r\n\r\n' ``` -------------------------------- ### Convert Files Using pathlib with pypandoc Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Demonstrates using Python's pathlib module for specifying input and output files, including glob patterns for multiple files. ```python import pypandoc from pathlib import Path # single file input = Path('somefile.md') output = input.with_suffix('.docx') pypandoc.convert_file(input, 'docx', outputfile=output) # convert all markdown files in a chapters/ subdirectory. pypandoc.convert_file(Path('chapters').glob('*.md'), 'docx', outputfile="somefile.docx") # convert all markdown files in the book1 and book2 directories. pypandoc.convert_file([*Path('book1').glob('*.md'), *Path('book2').glob('*.md')], 'docx', outputfile="somefile.docx") # pathlib globs must be unpacked if they are inside lists. ``` -------------------------------- ### Convert File and Text with pypandoc Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/README.md Demonstrates basic file and text conversion using pypandoc. Ensure input files exist and output formats are supported by Pandoc. ```python import pypandoc # Convert file pypandoc.convert_file('input.md', 'rst') # Convert text pypandoc.convert_text('# Hello', 'html', format='md') ``` -------------------------------- ### Work with pathlib.Path Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Use `pathlib.Path` objects for input and output file paths when performing conversions. ```python import pypandoc from pathlib import Path input_file = Path('document.md') output_file = input_file.with_suffix('.html') pypandoc.convert_file(input_file, 'html', outputfile=output_file) ``` -------------------------------- ### pypandoc_binary CLI Main Entry Point Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md The main function for the pypandoc_binary package entry point. It locates the bundled pandoc binary and forwards all arguments, ensuring pandoc-citeproc is discoverable. ```python def main() -> None: """Entry point for pypandoc_binary command-line wrapper. Locates bundled pandoc binary and forwards all arguments to it. Sets up PATH so pandoc-citeproc can be discovered. """ ``` -------------------------------- ### Convert Multiple Input Files with pypandoc Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Illustrates converting multiple input files, including those specified with wildcards or from different locations, to a single output file. ```python import pypandoc # convert all markdown files in a chapters/ subdirectory. pypandoc.convert_file('chapters/*.md', 'docx', outputfile="somefile.docx") # convert all markdown files in the book1 and book2 directories. pypandoc.convert_file(['book1/*.md', 'book2/*.md'], 'docx', outputfile="somefile.docx") # convert the front from another drive, and all markdown files in the chapter directory. pypandoc.convert_file(['D:/book_front.md', 'book2/*.md'], 'docx', outputfile="somefile.docx") ``` -------------------------------- ### Standard User Import of pypandoc Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md Demonstrates the most common way to use pypandoc by importing the entire library. This makes all public functions directly accessible. ```python import pypandoc # All public functions are available output = pypandoc.convert_file('input.md', 'rst') version = pypandoc.get_pandoc_version() ``` -------------------------------- ### PDF Conversion with TinyTeX Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/usage-patterns.md Enables PDF conversion with automatic package installation using TinyTeX. Ensure TinyTeX is installed and downloaded. ```python import pypandoc # Install TinyTeX first: pip install pypandoc[tinytex] # Then: pytinytex download # PDF conversion now works with automatic package installation pypandoc.convert_file('document.md', 'pdf', outputfile='document.pdf') ``` -------------------------------- ### pypandoc_binary CLI Entry Point Configuration Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md This indicates the console_scripts entry point in the pyproject.toml for the pypandoc_binary package, which calls the main function. ```toml # In pypandoc/binary/pyproject.toml (inferred) # console_scripts entry that calls this main() ``` -------------------------------- ### pypandoc CLI Entry Point Configuration Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/modules.md This snippet shows how to configure the pypandoc command-line entry point in a pyproject.toml file. It also illustrates an alternative way to call the CLI using `python -m pypandoc`. ```toml # In pyproject.toml [project.scripts] pypandoc = "pypandoc.cli:main" ``` ```bash python -m pypandoc ``` -------------------------------- ### Building Pandoc Command Arguments Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/architecture.md Shows how pypandoc constructs the pandoc command-line arguments, including input/output formats, files, and optional arguments like sandbox, filters, and extra arguments. ```python _convert_input() builds pandoc command: args = [ __pandoc_path, f"--from={format}", f"--to={to}", ...input_files, ] Optional args: - --output= (if outputfile) - --sandbox (if sandbox and pandoc >= 2.15) - extra_args (user-provided) - --filter= (for each filter) Special handling: - Lua filters use --lua-filter= instead - Filter names with .lua extension detected automatically - Arguments must be separate list items (not combined strings) ``` -------------------------------- ### ensure_pandoc_minimal_version Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-info.md Checks if the installed pandoc meets a minimum version requirement. It compares the major and minor version numbers of the installed pandoc against the provided values. ```APIDOC ## ensure_pandoc_minimal_version ### Description Checks if the installed pandoc meets a minimum version requirement. It compares the major and minor version numbers of the installed pandoc against the provided values. ### Signature ```python def ensure_pandoc_minimal_version(major: int, minor: int = 0) -> bool ``` ### Parameters #### Parameters - **major** (int) - Required - Major version number (e.g., `2` or `3`) - **minor** (int) - Optional - Default: `0` - Minor version number (e.g., `19`, `15`) ### Return Value Returns `True` if the installed pandoc version is greater than or equal to the specified version; `False` otherwise. **Return type:** `bool` ### Exceptions - `OSError`: If pandoc is not found - `RuntimeError`: If pandoc version cannot be determined ### Notes - Only checks major and minor version numbers; patch version is ignored - For example, `ensure_pandoc_minimal_version(2, 19)` returns `True` for versions `2.19.0`, `2.19.5`, `2.20`, `3.0`, etc. - Returns `True` if major version is higher (e.g., checking for 1.x when 2.x is installed) ### Examples #### Check for pandoc 2.19 or later ```python import pypandoc if pypandoc.ensure_pandoc_minimal_version(2, 19): print("Pandoc 2.19+ is available") else: print("Pandoc is too old") ``` #### Use sandbox mode (pandoc >= 2.15) ```python if pypandoc.ensure_pandoc_minimal_version(2, 15): output = pypandoc.convert_text( '# Hello', 'html', format='md', sandbox=True ) ``` #### Conditional feature usage ```python if pypandoc.ensure_pandoc_minimal_version(3, 0): # Use features only available in pandoc 3.x pass else: # Fallback for pandoc 2.x pass ``` ``` -------------------------------- ### Ensure Pandoc Installed API Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Ensure Pandoc is installed, downloading it if necessary using `ensure_pandoc_installed`. This function can take a URL, target folder, and version. ```python def ensure_pandoc_installed( url: Union[str, None] = None, targetfolder: Union[str, None] = None, version: str = "latest", delete_installer: bool = False, ) -> None ``` -------------------------------- ### Version Type Handling Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/types.md Demonstrates how version strings are stored as strings and parsed into lists of integers for comparison. Includes internal parsing logic. ```python # Versions are stored as strings and parsed to lists of ints version_string = "2.19.2" # Type: str version_list = [2, 19, 2] # Type: list[int] # Parsing (internal, line 823) version = [int(x) for x in get_pandoc_version().split(".")] ``` -------------------------------- ### Check for pandoc 2.x or earlier Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-info.md Use this snippet to verify if the installed pandoc version is 2.x or an earlier major version. This is useful for ensuring compatibility with older pandoc installations. ```python import pypandoc if pypandoc.ensure_pandoc_maximal_version(2): print("Pandoc is version 2.x or earlier") ``` -------------------------------- ### Download Pandoc to a Specific Folder Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/usage-patterns.md Download a specific version of Pandoc to a target folder and optionally delete the installer after extraction. This is useful for managing Pandoc installations in controlled environments. ```python import pypandoc pypandoc.download_pandoc( version='3.1.2', targetfolder='/usr/local/bin', delete_installer=True ) ``` -------------------------------- ### Get Pandoc Path API Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Obtain the file system path to the Pandoc executable using `get_pandoc_path`. ```python def get_pandoc_path() -> str ``` -------------------------------- ### Verify File Existence Before Conversion Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md Demonstrates how to check if a file exists using pathlib before attempting conversion with pypandoc to prevent 'Invalid Source Path' errors. ```python import pypandoc from pathlib import Path # Verify file exists file_path = Path('document.md') if file_path.exists(): output = pypandoc.convert_file(file_path, 'rst') else: print(f"File not found: {file_path}") ``` -------------------------------- ### get_pandoc_version Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-info.md Retrieves the version string of the installed pandoc binary. The result is cached internally after the first call for performance. ```APIDOC ## get_pandoc_version ### Description Gets the version string of the installed pandoc binary. ### Signature ```python def get_pandoc_version() -> str ``` ### Parameters None. ### Return Value Returns the version string of the installed pandoc in semantic versioning format. **Return type:** `str` **Examples of return values:** `"2.19.2"`, `"3.1"`, `"3.1.4"` ### Exceptions | Exception | Condition | |-----------|-----------| | `RuntimeError` | If pandoc cannot be called or does not return version information | | `OSError` | If pandoc is not found; ensure it has been installed and is available at path | ### Notes - Caches the result internally after the first call for performance - Uses `pandoc --version` command to retrieve version - Version string is parsed to extract only the semantic version (major.minor.patch format) - To refresh the cached version, call `clean_version_cache()` - Respects `PYPANDOC_PANDOC` environment variable if set ### Examples #### Get pandoc version ```python import pypandoc version = pypandoc.get_pandoc_version() print(f"Pandoc version: {version}") # e.g., "2.19.2" ``` #### Check minimum version requirement ```python version = pypandoc.get_pandoc_version() if version >= "2.19": print("Pandoc 2.19 or later is installed") ``` #### Use ensure_pandoc_minimal_version for version checking ```python # Better approach: use version checking function if pypandoc.ensure_pandoc_minimal_version(2, 19): print("Pandoc meets minimum version requirement") ``` ``` -------------------------------- ### Download pandoc using pypandoc CLI Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Utilize the pypandoc command-line interface to download pandoc to the default path or a specified version. ```bash # install latest pandoc to default path pypandoc download # Download a specific version pypandoc download --version 3.6 ``` -------------------------------- ### Example RuntimeError Message Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md Illustrates a typical RuntimeError message when Pandoc fails during conversion due to a missing filter. ```text RuntimeError: Pandoc died with exitcode "1" during conversion: [ERROR] Could not find filter `missing-filter` ``` -------------------------------- ### Use Pandoc Filters with pypandoc Source: https://github.com/jessicategner/pypandoc/blob/master/README.md Demonstrates how to apply pandoc filters, such as pandoc-citeproc, and other arguments during file conversion. ```python filters = ['pandoc-citeproc'] pdoc_args = ['--mathjax', '--smart'] output = pypandoc.convert_file(filename, to='html5', format='md', extra_args=pdoc_args, filters=filters) ``` -------------------------------- ### Download Pandoc from Custom URL Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md If pandoc binaries are hosted elsewhere or you have a direct link, use the `url` parameter to specify the download source. Ensure the URL points to a compatible binary distribution for your platform. ```python pypandoc.download_pandoc(url='https://example.com/pandoc-3.1.2-linux-x86_64.tar.gz') ``` -------------------------------- ### Basic Text Conversion Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-convert.md Converts a markdown string to reStructuredText. Ensure pypandoc is installed and pandoc is accessible in your system's PATH. ```python import pypandoc output = pypandoc.convert_text('# Some title', 'rst', format='md') print(output) # 'some title\r\n==========\r\n\r\n' ``` -------------------------------- ### Advanced Conversion with Filters and Arguments Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/README.md Illustrates advanced conversion options, including applying Pandoc filters and passing extra command-line arguments for more complex transformations like table of contents generation or math rendering. ```python import pypandoc # Apply filters, add arguments pypandoc.convert_file( 'input.md', 'pdf', outputfile='output.pdf', filters=['pandoc-citeproc'], extra_args=['--toc', '--mathjax'] ) ``` -------------------------------- ### Get Pandoc Path Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/api-reference-info.md Retrieves the path to the pandoc executable used by pypandoc. This function caches the result internally after the first call. ```python import pypandoc path = pypandoc.get_pandoc_path() print(f"Using pandoc at: {path}") ``` -------------------------------- ### Create Output Directory with pathlib Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/usage-patterns.md Ensure the output directory exists before conversion using `pathlib.Path.mkdir`. Construct the output file path within the specified directory. ```python import pypandoc from pathlib import Path output_dir = Path('output') output_dir.mkdir(exist_ok=True) input_file = Path('document.md') output_file = output_dir / input_file.with_suffix('.html').name pypandoc.convert_file(input_file, 'html', outputfile=output_file) ``` -------------------------------- ### Get Pandoc Formats API Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/index.md Fetch a tuple containing lists of supported Pandoc input and output formats using `get_pandoc_formats`. ```python def get_pandoc_formats() -> tuple[list[str], list[str]] ``` -------------------------------- ### Output Binary Formats using outputfile Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/errors.md Binary formats like DOCX cannot be returned as string values. Use the outputfile parameter to specify a file path for saving the converted document. ```python # Must use outputfile for binary formats pypandoc.convert_file('doc.md', 'docx', outputfile='doc.docx') ``` -------------------------------- ### convert_file Conversion Flow Source: https://github.com/jessicategner/pypandoc/blob/master/_autodocs/architecture.md Illustrates the step-by-step process for converting a file from one format to another using pypandoc. This includes path resolution, format detection and validation, command building, execution, error handling, and result retrieval. ```text User calls: convert_file('document.md', 'rst') ↓ 1. Path Resolution ├── Convert str/Path/Iterator to Path objects ├── Expand glob patterns └── Resolve relative paths to cworkdir ↓ 2. Format Detection ├── If format=None: extract from file extension └── Normalize format name (e.g., 'md' -> 'markdown') ↓ 3. Format Validation (if verify_format=True) ├── Call _ensure_pandoc_path() [find pandoc] ├── Call get_pandoc_formats() ├── Check input format in valid list ├── Check output format in valid list └── Check binary format constraints ↓ 4. Conversion Execution ├── Build pandoc command: │ ├── pandoc binary path │ ├── --from= │ ├── --to= │ ├── input file(s) │ ├── --output= (if specified) │ ├── extra_args │ └── --filter= (for each filter) ├── Spawn subprocess with new environment ├── Add package bin directory to PATH (for pandoc-citeproc) └── Add TinyTeX to PATH (if converting to PDF) ↓ 5. Execution & Error Handling ├── Send input to stdin (if needed) ├── Read stdout, stderr ├── Check return code └── Classify pandoc logging output ↓ 6. TinyTeX Package Installation (PDF only) ├── Parse stderr for missing packages ├── Auto-install via pytinytex (up to 3 attempts) └── Retry conversion if packages installed ↓ 7. Return Result ├── If outputfile: return "" (written to file) └── If no outputfile: return converted string ```