<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aspose-PDF-Python on Medium]]></title>
        <description><![CDATA[Stories by Aspose-PDF-Python on Medium]]></description>
        <link>https://medium.com/@pdf-python?source=rss-d3aa36435255------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ocWPj9cQMlpUw4r_Mu0Pzw.png</url>
            <title>Stories by Aspose-PDF-Python on Medium</title>
            <link>https://medium.com/@pdf-python?source=rss-d3aa36435255------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:06:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pdf-python/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[How to Add Watermarks to PDF Files with Python]]></title>
            <link>https://medium.com/asposepdf/how-to-add-watermarks-to-pdf-files-with-python-042bf5f7472f?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/042bf5f7472f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 12:09:44 GMT</pubDate>
            <atom:updated>2026-11-16T12:09:44.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjOu9uHYxVYF6a8tycfRvA.png" /></figure><p><strong><em>Mark draft reports consistently with text or a logo watermark.</em></strong></p><p>Adding a DRAFT label to a PDF is easy enough until the report changes, and you have to do it again. Then there are the details: does every page have the label? Is it covering a table? Should the logo appear everywhere, or just on the first and last pages?</p><p>In this tutorial, I’ll use Aspose.PDF for Python via .NET to add text and logo watermarks WatermarkArtifact. The script saves a separate PDF, checks that page sizes and rotation haven’t changed, and creates PNG previews so you can inspect the result.</p><p>A DRAFT label tells readers which version they’re looking at. It won’t stop someone from copying or changing the PDF.</p><p><strong>The example report</strong></p><p>The sample report has three pages: one portrait, one landscape, and one portrait page rotated by 90 degrees. Each has a REPORT PAGE marker and three paragraphs generated with lorem-text. The different orientations make placement problems easier to spot.</p><p>The script follows this sequence:</p><pre>Inspect input → Validate policy → Apply artifacts → Stage PDF<br>             → Reopen and render → Publish PDF and previews</pre><p>The original file stays untouched. After the script finishes, check the previews: the labels should appear on the pages you selected, the report should remain readable, and the logo should fit on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*dtpHdmeQcR5KofBieWNFCQ.png" /><figcaption>Portrait report with three paragraphs, a diagonal DRAFT watermark, and a logo near the bottom</figcaption></figure><p><em>The first page of the updated fixture, rendered at 90 DPI. This screenshot was generated using a valid license.</em></p><p><strong>Set up the project</strong></p><p>The examples were tested on Windows with Python 3.11.15, Aspose.PDF 26.10.0, and lorem-text 3.0. Use Python 3.11 or newer for this script’s type annotations.</p><p>For a quick installation:</p><pre>pip install aspose-pdf<br>pip install lorem-text</pre><pre>pip install -r requirements.txt</pre><p>Aspose handles the PDFs and renders the previews. `lorem-text` supplies the sample paragraphs, and Python’s standard library creates the transparent PNG logo. You don’t need Acrobat installed. Before using a different platform, check the <a href="https://docs.aspose.com/pdf/python-net/system-requirements/">official system requirements</a>, including Linux native dependencies.</p><p>Without a license, Aspose adds evaluation labels and restricts access to four collection elements. A three-page document does not automatically avoid every collection limit. See the <a href="https://docs.aspose.com/pdf/python-net/installation/">installation and evaluation documentation</a>.</p><p>Set a license in PowerShell before running the examples:</p><pre>$env:ASPOSE_PDF_LICENSE = &#39;C:\Path\Aspose.PDF.Python.lic&#39;<br>python pdf_watermark.py demo</pre><p>Alternatively, put -license` before the subcommand:</p><pre>python pdf_watermark.py - license &quot;C:/Path/Aspose.PDF.Python.lic&quot; demo</pre><p>The loader expands ~, resolves relative paths against the working directory, and removes matching surrounding quotes accidentally stored in an environment value. It checks that the path names a file before calling set_license(). Keep the returned license object alive during processing, following the script’s main(). The <a href="https://docs.aspose.com/pdf/python-net/licensing/">licensing guide</a> describes file-based activation.</p><p><strong>Define a watermark policy</strong></p><p>Keeping the watermark settings in one small dataclass:</p><pre>@dataclass(frozen=True)<br>class Policy:<br>    text: str = &quot;DRAFT&quot;<br>    pages: tuple[int, ...] | None = None<br>    logo: Path | None = None<br>    logo_pages: tuple[int, ...] = (1, 3)<br>    opacity: float = 0.18<br>    angle: float = 45.0<br>    background: bool = False</pre><p>Page numbering starts at 1. Leave pageas None to add text to every page. The logo has its own page selection, so you can place it on pages without a text watermark.</p><p>The script checks the settings before saving. It rejects empty or duplicate page selections, page numbers that don’t exist, blank labels or labels longer than 80 characters, opacity outside 0–1, and angles that aren’t finite numbers.</p><p><strong>Add text to one page</strong></p><p>The <a href="https://docs.aspose.com/pdf/python-net/add-watermarks/">official watermark tutorial</a> configures a text state, assigns it to a watermark artifact, and appends that artifact to a page. The helper below follows that pattern:</p><pre>def text_watermark(page: pdf.Page, policy: Policy) -&gt; pdf.WatermarkArtifact:<br>    state = pdf.text.TextState()<br>    state.font = pdf.text.FontRepository.find_font(&quot;Helvetica&quot;)<br>    width, height = page.rect.width, page.rect.height<br>    state.font_size = min(<br>        80.0, min(width, height) * 0.55 / max(len(policy.text), 1)<br>    )<br>    state.foreground_color = pdf.Color.gray<br><br>    artifact = pdf.WatermarkArtifact()<br>    artifact.set_text_and_state(policy.text, state)<br>    artifact.artifact_horizontal_alignment = pdf.HorizontalAlignment.CENTER<br>    artifact.artifact_vertical_alignment = pdf.VerticalAlignment.CENTER<br>    artifact.rotation = policy.angle % 360<br>    artifact.opacity = policy.opacity<br>    artifact.is_background = policy.background<br>    return artifact</pre><p>The font size is an estimate based on the page size and label length; it doesn’t measure each letter&#39;s width. Check the preview if you use a long label. For characters Helvetica doesn’t support, choose another installed font.</p><p>Attach the result with page.artifacts.append(text_watermark(page, policy)). The command-line interface wraps that operation with validation and output checks:</p><pre>python pdf_watermark.py stamp input/synthetic-report.pdf output/one-page.pdf --pages 1</pre><p>The command remains named stamp for compatibility; its implementation uses watermark artifacts.</p><p><strong>Apply the policy across pages</strong></p><p>Omit -pages to mark every page:</p><pre>python pdf_watermark.py stamp input/synthetic-report.pdf output/all-pages.pdf</pre><p>Or select pages explicitly:</p><pre>python pdf_watermark.py stamp input/synthetic-report.pdf output/selected.pdf --pages 1,3 --angle 30</pre><p>The script creates a new artifact for each page, using that page’s dimensions. It visits any page selected for either text or a logo.</p><figure><img alt="Landscape report with a DRAFT watermark and no logo" src="https://cdn-images-1.medium.com/max/1024/1*ut9KUP0eGyaW6NCfqczQ2w.png" /><figcaption><em>Page 2 receives text but no logo under the default logo selection.</em></figcaption></figure><p>Pay particular attention to the rotated page:</p><figure><img alt="Rotated third page with sideways report content, diagonal DRAFT text, and an upright logo" src="https://cdn-images-1.medium.com/max/1024/1*jYzaAzw2qy3S3qjm6MJ5gA.png" /></figure><p><em>The fixture intentionally rotates its original content. The watermark remains diagonal and the logo upright in this rendered result.</em></p><p>The script keeps the existing page rotation. If your PDFs use unusual crop boxes, check those separately; these examples don’t cover every page layout.</p><h4><strong>Add a logo with set_image()</strong></h4><p>WatermarkArtifact.set_image()accepts an image filename directly. Its <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf/watermarkartifact/">API reference</a> also documents a stream overload. You don&#39;t need to build an intermediate PDF page for this example.</p><pre>def add_logo(page: pdf.Page, path: Path, policy: Policy) -&gt; None:<br>    artifact = pdf.WatermarkArtifact()<br>    artifact.set_image(str(path.resolve()))<br>    artifact.artifact_horizontal_alignment = pdf.HorizontalAlignment.CENTER<br>    artifact.artifact_vertical_alignment = pdf.VerticalAlignment.BOTTOM<br>    artifact.bottom_margin = 60<br>    artifact.rotation = 0<br>    artifact.opacity = min(1.0, policy.opacity * 2)<br>    artifact.is_background = policy.background<br>    page.artifacts.append(artifact)</pre><p>This helper uses the image’s default size rather than scaling it to the page. Resize your PNG beforehand, keeping its proportions, then check how large it appears in the PDF. In the SDK version used here, the artifact rectangle is read-only.</p><p>The script checks the PNG signature, IHDR header, and nonzero dimensions. Aspose performs the actual decoding; the header check alone cannot prove that the entire file is valid. Transparent pixels let report content show through, while artifact opacity controls the mark as a whole.</p><pre>python pdf_watermark.py stamp input/synthetic-report.pdf output/branded.pdf --logo input/logo.png --logo-pages 1,3</pre><p>Here, the logo is twice as opaque as the text, up to a maximum of 1. It sits at the bottom centre with a 60-point margin. If your report has a footer, you may need to adjust that margin.</p><h4><strong>Compare foreground and background placement</strong></h4><p>Foreground placement is the default. For a faint background label:</p><pre>python pdf_watermark.py stamp input/synthetic-report.pdf output/faint.pdf --background --opacity 0.1</pre><figure><img alt="Portrait report with a faint background DRAFT watermark" src="https://cdn-images-1.medium.com/max/743/1*7Rh4Hq0wZ0henA_Rq3HFZg.png" /><figcaption><em>The same fixture with background placement and opacity 0.10; this policy has no logo.</em></figcaption></figure><p>A lower opacity makes the mark fainter; background placement puts it behind the page content. That distinction matters with scans: a full-page image can hide a background watermark completely. Try foreground placement for those files and check the contrast. The sample PDFs here are generated documents, so they don’t test that case.</p><p>A large logo can also increase the PDF’s file size. The command prints the input and output sizes so you can compare them using your own assets. It doesn’t optimise images or change compression settings.</p><h4><strong>Run the complete example</strong></h4><p>The complete script appears in the appendix and is also available as pdf_watermark.py. The sample generator adds three separate text fragments per page:</p><pre>from lorem_text import lorem<br><br>for _ in range(3):<br>    paragraph = pdf.text.TextFragment(lorem.paragraph())<br>    paragraph.text_state.font_size = 10<br>    paragraph.margin = pdf.MarginInfo(0, 10, 0, 0)<br>    page.paragraphs.add(paragraph)</pre><p>The paragraphs are random, so your generated report won’t match the screenshots word for word. The API is described in the <a href="https://lorem-text.readthedocs.io/en/latest/usage/">Lorem Text usage guide</a>.</p><p>If you haven’t generated the sample files yet, run:</p><pre>python pdf_watermark.py fixtures<br>python pdf_watermark.py demo<br>python check_examples.py</pre><p>If fixtures already exist, the generator refuses to replace them. To regenerate, move synthetic-report.pdfand logo.pngto a backup location first. Preserve the separately supplied report.pdf. Likewise, move existing demo PDFs and their preview directories before rerunning the demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29uhub9Q5vzBrjIBy6Ee3Q.png" /></figure><p>Each PDF has a sibling directory such as 03-text-and-logo.previews/ containing page-1.pngthrough page-3.png. Successful execution prints Published, the destination, and a dictionary with pages, input_bytes, output_bytes, and seconds. Timing and file sizes will vary based on the generated text and your machine.</p><h4><strong>Check the saved PDF</strong></h4><p>After saving a staged PDF, the script reopens it, compares page count, dimensions, and rotation, then renders every page with PngDeviceat 90 DPI. Open the previews and look for clipped text, labels that are too dark or too faint, and logos on the wrong pages. The REPORT PAGE markers should still be readable.</p><p>The accompanying checker uses SHA-256 hashes to check that the input and any existing destination file stay unchanged. It also checks temporary-file cleanup and seven failure cases. You can try two of those yourself:</p><pre>python pdf_watermark.py stamp input/invalid.pdf output/invalid-result.pdf<br>python pdf_watermark.py stamp input/synthetic-report.pdf output/bad-page.pdf --pages 99</pre><p>Both should exit with status 1 and a FAILED (stamp)message. No output PDF should be published. Missing logos, invalid opacity, destination collisions, and identical source/destination paths are also rejected.</p><p>These checks catch changes to page geometry and failures to render. They don’t compare every text fragment, link, annotation, or form field. If those matter for your documents, add checks for them too.</p><h4><strong>A few things to watch for</strong></h4><p>The script first saves to a temporary location beside the destination. It then uses os.link()to create the final PDF without replacing an existing file, even if another process creates one while the script is running. This requires a filesystem that supports hard links.</p><p>The previews move into place afterwards. If that move raises an error, the script removes the final PDF. A crash between those steps can still leave a PDF without its previews. If you put this into a batch job, handle failures such as a full disk, missing fonts, or corrupt input files.</p><p>The script calls free_memory()in finallyblocks to release document caches. One cleanup issue occurred during screenshot generation on Windows: the PDFs rendered, but the logo file remained locked while the temporary directory was being removed. Test this on your deployment platform if your application deletes source images immediately after processing.</p><p>Start each run from the original PDF. Running the script on an already marked copy adds another watermark. Password-protected files, digital signatures, PDF/A requirements, accessibility tags, and complex page boxes need additional handling. In particular, changing a signed PDF can invalidate its signatures.</p><p>Before sharing the PDF, open it and check the pages you selected. For batch processing, I’d also keep a record of the source hash, watermark settings, library version, output paths, and check results. That makes an unexpected run easier to trace. The article on `reordering PDF pages` shows a similar approach to checking a saved PDF.</p><h4><strong>Appendix: complete runnable script</strong></h4><p>Save this as pdf_watermark.py, install the dependencies above, and use the commands in the tutorial. The code below is copied from the updated example.</p><pre>&quot;&quot;&quot;Text/image WatermarkArtifact examples using Aspose.PDF for Python via .NET.&quot;&quot;&quot;<br>from __future__ import annotations<br><br>import argparse<br>from dataclasses import dataclass<br>from importlib.metadata import version<br>import math<br>import os<br>from pathlib import Path<br>import struct<br>import sys<br>import tempfile<br>import time<br>import zlib<br><br>import aspose.pdf as pdf<br><br>ROOT = Path(__file__).resolve().parent<br><br><br>@dataclass(frozen=True)<br>class Policy:<br>    text: str = &quot;DRAFT&quot;<br>    pages: tuple[int, ...] | None = None  # None means all; PDF pages are one-based.<br>    logo: Path | None = None<br>    logo_pages: tuple[int, ...] = (1, 3)<br>    opacity: float = 0.18<br>    angle: float = 45.0<br>    background: bool = False<br><br><br>def load_license(path: str | Path | None = None) -&gt; pdf.License | None:<br>    &quot;&quot;&quot;Load a license file relative to the working directory, expanding ``~``.<br><br>    Use ASPOSE_PDF_LICENSE when path is None; an empty path uses evaluation mode.<br>    &quot;&quot;&quot;<br>    if path is None:<br>        path = os.environ.get(&quot;ASPOSE_PDF_LICENSE&quot;)<br>    if isinstance(path, str) and len(path) &gt;= 2 and path[0] == path[-1] and path[0] in &quot;\&quot;&#39;&quot;:<br>        path = path[1:-1]<br>    if path:<br>        license_path = Path(path).expanduser().resolve(strict=True)<br>        if not license_path.is_file():<br>            raise ValueError(f&quot;License path must be a file: {license_path}&quot;)<br>        lic = pdf.License()<br>        lic.set_license(str(license_path))<br>        return lic<br>    return None<br><br><br>def selected_pages(numbers: tuple[int, ...] | None, count: int) -&gt; tuple[int, ...]:<br>    result = tuple(range(1, count + 1)) if numbers is None else numbers<br>    if not result or len(set(result)) != len(result):<br>        raise ValueError(&quot;Page selection must be nonempty and contain no duplicates&quot;)<br>    if any(number &lt; 1 or number &gt; count for number in result):<br>        raise ValueError(f&quot;Page numbers must be in 1..{count}: {result}&quot;)<br>    return result<br><br><br>def png_size(path: Path) -&gt; tuple[int, int]:<br>    &quot;&quot;&quot;Restrict this tutorial&#39;s logo input to PNG; Aspose validates the full image.&quot;&quot;&quot;<br>    with path.open(&quot;rb&quot;) as stream:<br>        header = stream.read(24)<br>    if len(header) != 24 or header[:8] != b&quot;\x89PNG\r\n\x1a\n&quot; or header[12:16] != b&quot;IHDR&quot;:<br>        raise ValueError(f&quot;Expected a PNG logo: {path}&quot;)<br>    width, height = struct.unpack(&quot;&gt;II&quot;, header[16:24])<br>    if not width or not height:<br>        raise ValueError(f&quot;Invalid image dimensions: {path}&quot;)<br>    return width, height<br><br><br>def text_watermark(page: pdf.Page, policy: Policy) -&gt; pdf.WatermarkArtifact:<br>    state = pdf.text.TextState()<br>    state.font = pdf.text.FontRepository.find_font(&quot;Helvetica&quot;)<br>    # Bound the unrotated text inside a square that also fits when rotated.<br>    width, height = page.rect.width, page.rect.height<br>    font_size = min(80.0, min(width, height) * 0.55 / max(len(policy.text), 1))<br>    state.font_size = font_size<br>    state.foreground_color = pdf.Color.gray<br>    artifact = pdf.WatermarkArtifact()<br>    artifact.set_text_and_state(policy.text, state)<br>    artifact.artifact_horizontal_alignment = pdf.HorizontalAlignment.CENTER<br>    artifact.artifact_vertical_alignment = pdf.VerticalAlignment.CENTER<br>    artifact.rotation = policy.angle % 360<br>    artifact.opacity = policy.opacity<br>    artifact.is_background = policy.background<br>    return artifact<br><br><br>def add_logo(page: pdf.Page, path: Path, policy: Policy) -&gt; None:<br>    &quot;&quot;&quot;Add an image watermark at its default size; resize the source PNG if needed.&quot;&quot;&quot;<br>    artifact = pdf.WatermarkArtifact()<br>    artifact.set_image(str(path.resolve()))<br>    artifact.artifact_horizontal_alignment = pdf.HorizontalAlignment.CENTER<br>    artifact.artifact_vertical_alignment = pdf.VerticalAlignment.BOTTOM<br>    artifact.bottom_margin = 60<br>    artifact.rotation = 0<br>    artifact.opacity = min(1.0, policy.opacity * 2)<br>    artifact.is_background = policy.background<br>    page.artifacts.append(artifact)<br><br><br>def geometry(document: pdf.Document) -&gt; list[tuple[float, float, int]]:<br>    return [(page.rect.width, page.rect.height, int(page.rotate)) for page in document.pages]<br><br><br>def render(document: pdf.Document, directory: Path) -&gt; None:<br>    directory.mkdir()<br>    device = pdf.devices.PngDevice(pdf.devices.Resolution(90))<br>    for number in range(1, len(document.pages) + 1):<br>        device.process(document.pages[number], str(directory / f&quot;page-{number}.png&quot;))<br><br><br>def watermark(source: Path, destination: Path, policy: Policy) -&gt; dict:<br>    &quot;&quot;&quot;Stage, reopen, compare geometry, render, then publish without replacing files.&quot;&quot;&quot;<br>    source, destination = source.resolve(), destination.resolve()<br>    if source == destination:<br>        raise ValueError(&quot;Source and destination must differ&quot;)<br>    if not source.is_file():<br>        raise FileNotFoundError(f&quot;Input PDF not found: {source}&quot;)<br>    if destination.exists():<br>        raise FileExistsError(f&quot;Destination already exists: {destination}&quot;)<br>    if not policy.text.strip() or len(policy.text) &gt; 80:<br>        raise ValueError(&quot;Text must contain 1..80 characters&quot;)<br>    if not math.isfinite(policy.opacity) or not 0 &lt;= policy.opacity &lt;= 1:<br>        raise ValueError(&quot;Opacity must be in 0..1&quot;)<br>    if not math.isfinite(policy.angle):<br>        raise ValueError(&quot;Rotation angle must be finite&quot;)<br>    if policy.logo is not None:<br>        png_size(policy.logo)<br>    destination.parent.mkdir(parents=True, exist_ok=True)<br>    preview_dir = destination.with_suffix(&quot;.previews&quot;)<br>    if preview_dir.exists():<br>        raise FileExistsError(f&quot;Preview destination already exists: {preview_dir}&quot;)<br>    started = time.perf_counter()<br>    with tempfile.TemporaryDirectory(prefix=&quot;.watermark-&quot;, dir=destination.parent) as temporary:<br>        staged = Path(temporary) / &quot;staged.pdf&quot;<br>        previews = Path(temporary) / &quot;previews&quot;<br>        document = pdf.Document(str(source))<br>        try:<br>            before = geometry(document)<br>            text_pages = selected_pages(policy.pages, len(document.pages))<br>            logo_pages = selected_pages(policy.logo_pages, len(document.pages)) if policy.logo else ()<br>            for number in sorted(set(text_pages) | set(logo_pages)):<br>                try:<br>                    page = document.pages[number]<br>                    if number in text_pages:<br>                        page.artifacts.append(text_watermark(page, policy))<br>                    if number in logo_pages and policy.logo is not None:<br>                        add_logo(page, policy.logo, policy)<br>                except Exception as error:<br>                    raise RuntimeError(f&quot;Watermark failed on page {number} of {source}: {error}&quot;) from error<br>            document.save(str(staged))<br>        finally:<br>            document.free_memory()<br>        verified = pdf.Document(str(staged))<br>        try:<br>            if geometry(verified) != before:<br>                raise RuntimeError(&quot;Verification failed: page count, size or rotation changed&quot;)<br>            render(verified, previews)  # Rendering success is not a visual correctness proof.<br>        finally:<br>            verified.free_memory()<br>        # A hard link fails if the destination already exists, including a race.<br>        # It requires filesystem hard-link support; there is no overwrite fallback.<br>        os.link(staged, destination)<br>        try:<br>            previews.rename(preview_dir)<br>        except Exception:<br>            destination.unlink()<br>            raise<br>    return {<br>        &quot;pages&quot;: len(before),<br>        &quot;input_bytes&quot;: source.stat().st_size,<br>        &quot;output_bytes&quot;: destination.stat().st_size,<br>        &quot;seconds&quot;: round(time.perf_counter() - started, 3),<br>    }<br><br><br>def make_fixtures() -&gt; None:<br>    &quot;&quot;&quot;Create separate synthetic inputs; never replace the supplied report.pdf.&quot;&quot;&quot;<br>    from lorem_text import lorem<br><br>    directory = ROOT / &quot;input&quot;<br>    directory.mkdir(exist_ok=True)<br>    target, logo = directory / &quot;synthetic-report.pdf&quot;, directory / &quot;logo.png&quot;<br>    if target.exists() or logo.exists():<br>        raise FileExistsError(&quot;Synthetic fixtures already exist; keep or remove them explicitly&quot;)<br>    # A simple transparent RGBA logo made with standard-library PNG encoding.<br>    width, height = 240, 96<br>    rows = []<br>    for y in range(height):<br>        row = bytearray()<br>        for x in range(width):<br>            inside = 8 &lt; x &lt; 231 and 8 &lt; y &lt; 87<br>            stripe = 25 &lt; x &lt; 48 or 65 &lt; x &lt; 88 or 105 &lt; x &lt; 128<br>            row.extend((22, 105, 145, 255) if inside and stripe else (255, 255, 255, 0))<br>        rows.append(b&quot;\x00&quot; + bytes(row))<br><br>    def chunk(kind: bytes, data: bytes) -&gt; bytes:<br>        return struct.pack(&quot;&gt;I&quot;, len(data)) + kind + data + struct.pack(&quot;&gt;I&quot;, zlib.crc32(kind + data))<br><br>    logo.write_bytes(<br>        b&quot;\x89PNG\r\n\x1a\n&quot; + chunk(b&quot;IHDR&quot;, struct.pack(&quot;&gt;IIBBBBB&quot;, width, height, 8, 6, 0, 0, 0)) + chunk(b&quot;IDAT&quot;,<br>                                                                                                             zlib.compress(<br>                                                                                                                 b&quot;&quot;.join(<br>                                                                                                                     rows))) + chunk(<br>            b&quot;IEND&quot;, b&quot;&quot;))<br>    document = pdf.Document()<br>    try:<br>        for number, (w, h, rotation) in enumerate(<br>                [(595, 842, pdf.Rotation.NONE), (842, 595, pdf.Rotation.NONE), (595, 842, pdf.Rotation.ON90)], 1<br>        ):<br>            page = document.pages.add()<br>            page.set_page_size(w, h)<br>            page.paragraphs.add(pdf.text.TextFragment(<br>                f&quot;REPORT PAGE {number} - Synthetic quarterly report\n&quot;<br>                f&quot;Revenue: {number * 12000} USD. Internal review copy.\n&quot;<br>                &quot;Check this page marker remains visible after watermarking.&quot;<br>            ))<br>            for _ in range(3):<br>                paragraph = pdf.text.TextFragment(lorem.paragraph())<br>                paragraph.text_state.font_size = 12<br>                paragraph.margin = pdf.MarginInfo(0, 10, 0, 0)<br>                page.paragraphs.add(paragraph)<br>        document.process_paragraphs()<br>        document.pages[3].rotate = pdf.Rotation.ON90<br>        document.save(str(target))<br>    finally:<br>        document.free_memory()<br>    (directory / &quot;invalid.pdf&quot;).write_text(&quot;This is deliberately not a PDF.\n&quot;, encoding=&quot;utf-8&quot;)<br>    print(f&quot;Created {target}, {logo}, and invalid.pdf&quot;)<br><br><br>def parse_pages(value: str) -&gt; tuple[int, ...]:<br>    try:<br>        return tuple(int(part) for part in value.split(&quot;,&quot;))<br>    except ValueError as error:<br>        raise argparse.ArgumentTypeError(&quot;Use comma-separated one-based page numbers&quot;) from error<br><br><br>def main() -&gt; int:<br>    parser = argparse.ArgumentParser(description=__doc__)<br>    parser.add_argument(&quot;--license&quot;, default=os.environ.get(&quot;ASPOSE_PDF_LICENSE&quot;))<br>    sub = parser.add_subparsers(dest=&quot;command&quot;, required=True)<br>    sub.add_parser(&quot;fixtures&quot;)<br>    sub.add_parser(&quot;demo&quot;)<br>    stamp = sub.add_parser(&quot;stamp&quot;)<br>    stamp.add_argument(&quot;source&quot;, type=Path)<br>    stamp.add_argument(&quot;destination&quot;, type=Path)<br>    stamp.add_argument(&quot;--text&quot;, default=&quot;DRAFT&quot;)<br>    stamp.add_argument(&quot;--pages&quot;, type=parse_pages)<br>    stamp.add_argument(&quot;--logo&quot;, type=Path)<br>    stamp.add_argument(&quot;--logo-pages&quot;, type=parse_pages, default=(1, 3))<br>    stamp.add_argument(&quot;--opacity&quot;, type=float, default=0.18)<br>    stamp.add_argument(&quot;--angle&quot;, type=float, default=45)<br>    stamp.add_argument(&quot;--background&quot;, action=&quot;store_true&quot;)<br>    args = parser.parse_args()<br>    try:<br>        pdf_license = load_license(args.license)  # Keep alive during processing.<br>        if pdf_license is None:<br>            print(&quot;Evaluation mode: vendor watermark and collection limits apply.&quot;)<br>        print(f&quot;Python {sys.version.split()[0]}, aspose-pdf {version(&#39;aspose-pdf&#39;)}&quot;)<br>        if args.command == &quot;fixtures&quot;:<br>            make_fixtures()<br>        elif args.command == &quot;demo&quot;:<br>            source = ROOT / &quot;input&quot; / &quot;synthetic-report.pdf&quot;<br>            for name, policy in [<br>                (&quot;01-one-page.pdf&quot;, Policy(pages=(1,))),<br>                (&quot;02-all-pages.pdf&quot;, Policy()),<br>                (&quot;03-text-and-logo.pdf&quot;, Policy(logo=ROOT / &quot;input&quot; / &quot;logo.png&quot;)),<br>                (&quot;04-background.pdf&quot;, Policy(background=True, opacity=0.10)),<br>            ]:<br>                destination = ROOT / &quot;output&quot; / name<br>                print(f&quot;Published {destination}: {watermark(source, destination, policy)}&quot;)<br>        else:<br>            policy = Policy(args.text, args.pages, args.logo, args.logo_pages, args.opacity, args.angle,<br>                            args.background)<br>            print(f&quot;Published {args.destination}: {watermark(args.source, args.destination, policy)}&quot;)<br>        return 0<br>    except Exception as error:<br>        print(f&quot;FAILED ({args.command}): {error}&quot;, file=sys.stderr)<br>        return 1<br><br><br>if __name__ == &quot;__main__&quot;:<br>    raise SystemExit(main())</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=042bf5f7472f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/how-to-add-watermarks-to-pdf-files-with-python-042bf5f7472f">How to Add Watermarks to PDF Files with Python</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Headers, Footers, and Page Numbers to PDFs with Python]]></title>
            <link>https://medium.com/asposepdf/how-to-add-headers-footers-and-page-numbers-to-pdfs-with-python-f748a1b345ff?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/f748a1b345ff</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 13:28:54 GMT</pubDate>
            <atom:updated>2026-11-03T13:28:54.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_ZocuIcOlPubi8PpsHNHw.png" /></figure><h3>Give a merged report consistent labels</h3><p>A monthly report often starts as several PDFs: a portrait summary, a landscape spreadsheet, and an appendix exported with page rotation. After merging them, you still need a department name at the top and consistent page numbers at the bottom.</p><p>Doing this manually introduces small errors. A cover gets numbered accidentally. A landscape footer lands outside the visible page. A second run adds another copy of yesterday’s header.</p><p>This tutorial uses Aspose.PDF for Python via .NET to label existing pages. We exclude the cover, calculate the numbering range before processing, and check the saved result before publishing. The example preserves the original page boxes and rotation while placing the new labels at the visual top and bottom.</p><h3>Define the input and expected result</h3><p>The workflow is:</p><p><strong>Inspect input → Validate configuration → Process document → Stage output → Verify result → Publish output</strong></p><p>Use the supplied “rotations.pdf fixture” as our small report.</p><p>Its four pages contain synthetic text with markers original-1through original-4. Their rotation values are 0°, 90°, 180°, and 270°, and their CropBoxes differ from their MediaBoxes. The first page serves as the cover.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9aKUtwYdQkiZOfviQ9MyQ.png" /></figure><p>Eligible pages also receive the<strong> Finance Department | Monthly Report </strong>label. The result must retain four pages, the original text markers, page boxes, and rotation values.</p><p>This workflow is for static PDFs with space available for labels. It does not rearrange report content or create extra margins. Forms, annotations, attachments, and encrypted inputs require separate handling.</p><h3>Set up a reproducible project</h3><p>Open a terminal in that directory:</p><pre>08-pdf-add-header-footer/<br>├── pdf_header_footer.py<br>├── verify-and-render.py<br>├── test_header_footer.py<br>├── requirements.txt<br>├── input/<br>│ ├── rotations.pdf<br>│ └── not-a-pdf.pdf<br>└── output/</pre><p>Install the library:</p><pre>pip install aspose-pdf</pre><p>For the version exercised with this draft:</p><pre>pip install -r requirements.txt</pre><p>The processor, tests, and rendering helper use Aspose.PDF and the Python standard library.</p><p>The exercised environment was Windows x64, Python 3.11.15, Aspose.PDF 26.8.0, with Arial available. Other platforms were not exercised. For deployment, check the matching package wheel and <a href="https://docs.aspose.com/pdf/python-net/system-requirements/">platform prerequisites</a>. The Linux documentation lists native runtime dependencies; installing a Python package alone does not establish that every host meets them.</p><p>Supply a license file through the ASPOSE_PDF_LICENSE environment variable. The script calls license.set_license() before opening the report. It reads the environment directly and does not load a `.env` file. See the official <a href="https://docs.aspose.com/pdf/python-net/licensing/">licensing instructions</a>.</p><p>For an unlicensed demonstration, explicitly pass allow-evaluation. Aspose adds evaluation watermarks and restricts access to collection elements. Our four-page fixture worked in the exercised environment, but keeping a document to four pages does not remove other evaluation limits. A licensed run was not exercised. The <a href="https://docs.aspose.com/pdf/python-net/installation/">installation documentation</a> describes those restrictions.</p><h3>Choose stamps for existing pages</h3><p>A layout header belongs to a document-generation process, where the layout engine can reserve space. Our report already has positioned content.</p><p>We therefore add two TextStampobjects to each eligible page. A stamp overlays the page; it does not push a table downward. The official <a href="https://docs.aspose.com/pdf/python-net/text-stamps-in-the-pdf-file/">text-stamping example</a> uses Document, textStamp, Page.add_stamp(), and Document.save() for this operation.</p><p>The key consequence is that empty header and footer space becomes a requirement. Our inspection rejects extractable text in the reserved bands instead of silently drawing over it.</p><h3>Define placement and numbering rules</h3><p>The labels use 10-point Arial in dark blue. The header has a 24-point top and left margin. The footer is centered with a 24-point bottom margin. PDF dimensions use points: 72 points equal one inch.</p><p>We reserve a 60-point band at both visible edges. This gives the labels room, but it remains a policy for this example rather than a universal PDF requirement.</p><p>Numbering has three separate values:</p><p>- The physical page index identifies a page in the PDF.<br>- The displayed number starts after the cover.<br>- The denominator identifies the final displayed number.</p><p>The labels()function calculates the mapping once:</p><pre>numbering = labels(4)<br># {2: &quot;Page 1 of 3&quot;, 3: &quot;Page 2 of 3&quot;, 4: &quot;Page 3 of 3&quot;}<br>numbering = labels(4, start=7)<br># {2: &quot;Page 7 of 9&quot;, 3: &quot;Page 8 of 9&quot;, 4: &quot;Page 9 of 9&quot;}</pre><p>With an offset, “of 9” means the final displayed number. This PDF still has only three numbered pages. Choose this convention deliberately when continuing numbering across report sections.</p><h3>Add a header and footer to one page</h3><p>Start with physical page 2:</p><pre>python pdf_header_footer.py - input input/rotations.pdf - only-page 2 - output output/one-page-demo.pdf - allow-evaluation</pre><p>The output remains four pages long. Only page 2 receives our labels, including <strong>Page 1 of 3</strong>. Selecting one demonstration page does not change the report&#39;s numbering range.</p><p>The central operation is:</p><pre>stamp = pdf.TextStamp(header)<br>stamp.text_state.font = pdf.text.FontRepository.find_font(&quot;Arial&quot;)<br>stamp.text_state.font_size = 10<br>stamp.text_state.foreground_color = pdf.Color.dark_blue<br>stamp.horizontal_alignment = pdf.HorizontalAlignment.LEFT<br>stamp.vertical_alignment = pdf.VerticalAlignment.TOP<br>stamp.left_margin = 24<br>stamp.top_margin = 24<br>page.add_stamp(stamp)</pre><p>The footer uses center/bottom alignment and bottom_margin. These settings are part of the <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/">TextStamp API</a>.</p><p>A page’s MediaBox describes its page extent; the CropBox determines the visible region. A cropped page may have a nonzero origin. Hard-coding coordinates against an assumed A4 sheet ignores both that origin and the displayed orientation.</p><h3>Number every eligible page</h3><p>Remove the single-page selection:</p><pre>python pdf_header_footer.py - input input/rotations.pdf - output output/article-demo.pdf - allow-evaluation</pre><p>The reusable process function obtains the page count, builds the label mapping, inspects the document, and applies it:</p><pre>for physical, footer in numbering.items():<br> add_header_footer(document.pages[physical], header, footer)</pre><p>Aspose’s page collection uses one-based indexing here. Page 1 never enters the default mapping, so the application adds neither a department header nor a page-number footer to the cover.</p><p>Evaluation watermarks are separate: they can still appear on the cover.</p><figure><img alt="Cover after processing, without the department header or page-number footer" src="https://cdn-images-1.medium.com/max/713/1*YKF-9dCxj-JnVIrutW8MIg.png" /><figcaption>Cover after processing, without the department header or page-number footer</figcaption></figure><p><em>The cover is excluded from our stamps. Red text comes from evaluation mode</em>.</p><p>Use -include-coveronly when every physical page should participate.</p><p>Use -start 7to produce the offset sequence described earlier.</p><h3>Place labels at the visual top of rotated pages</h3><p>Landscape dimensions and page rotation are different things. A wide page can have 0 ° rotation. A portrait-shaped page can carry a 90° rotation that makes it appear landscape in a viewer.</p><p>Measure the displayed rectangle for each page:</p><pre>rectangle = page.get_page_rect(True)<br>width, height = rectangle.width, rectangle.height</pre><p>The <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf/page/">Page API</a> documents the rotation-aware rectangle. Passing True lets the size checks use the displayed width and height.</p><p>In the exercised fixtures, Aspose&#39;s stamp alignment places the header horizontally at the visual top. For 90° clockwise rotation, the original left edge becomes the visible top edge. The stamp follows that visible edge. We do not rotate the existing report content to make it upright.</p><p>Before: page rotated 90°</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*u-b9eQMx9g7qJoP2o2OHiA.png" /><figcaption>Original page with 90-degree rotation</figcaption></figure><p>After: header at the visual top</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*pibn2pqXI-v9k73fMznegA.png" /><figcaption>Rotated page with horizontal header and Page 1 of 3 footer</figcaption></figure><p>Placement checks need consistent coordinates too. During text extraction, the code temporarily sets rotation to NONE, then restores it in finally. TextAbsorbersupplies page text, and TextFragmentAbsorber supplies fragment rectangles for <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/">text inspection</a>.</p><p>The visible_rectangle() helper subtracts the CropBox origin and maps every rectangle corner into visible coordinates. If wand h are the unrotated visible dimensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qiA5ZwvNm2DLMDKN1_pDw.png" /></figure><p>This transformation checks the visible bands; it does not change saved content. The test fixtures exercise all four rotations, cropped pages, and different page dimensions.</p><h3>Check readability and repeat-run behavior</h3><p>Render the saved output:</p><pre>python verify-and-render.py - input input/rotations.pdf - output output/article-demo.pdf - preview-dir previews/article-demo</pre><p>The helper checks the original markers and expected labels, then renders each before/after pair using <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/">PngDevice </a>at 96 DPI.</p><p>Before: last report page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*DZ8PjpVp3cNGDxl_paLieQ.png" /><figcaption>Original last page with 270-degree rotation</figcaption></figure><p>After: final displayed number</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*n0HbDb0LeTD9sr0BBML0FA.png" /><figcaption>Last page with horizontal header and Page 3 of 3 footer</figcaption></figure><p><em>These article images use cover exclusion. Red watermarks come from unlicensed Aspose rendering and saving; they may appear even in the “before” render.</em></p><p>Inspect the first and last numbers, header placement, clipping, and nearby report content. Automated text checks cannot establish the appearance of every object.</p><p>Always rerun from the fresh source. The code rejects its configured header, evaluation text, and recognizable “Page X of Y” labels. That is a useful guard, not a universal detector for previously stamped PDFs; legitimate source text matching the pattern is also refused.</p><h3>Stage output and report useful failures</h3><p>Before modifying the document, process()rejects an existing destination and a destination equal to the source. It creates a temporary directory beside the intended output, saves `stamped.pdf`, reopens it, and verifies it.</p><p>Only then does os.link(staged,destination)publish the result. Hard-link creation also refuses if the destination was created during processing. This requires filesystem support for hard links. There is no fallback that overwrites an existing file, and no claim of cross-platform atomicity or crash durability.</p><p>Verification compares original word counts, CropBox and MediaBox coordinates, and rotation. It requires one expected header and footer on eligible pages, checks their visible bounds, and checks footer centering. These consistency checks run with the same PDF engine, not as an independent proof of correctness.</p><p>A failed save, verification, or publication never prints a success message. The CLI reports the input, destination, and exception; stamping errors add the physical page number. Document context managers release resources, and the temporary directory is cleaned up when processing exits.</p><h3>Complete runnable example</h3><p>The complete script below matches the implementation in <a href="https://pastebin.com/fsJB0RMy">pdf_header_footer.py</a>. Keep it beside the supplied input directory, or pass explicit paths.</p><p>The remaining helpers implement the checks described above. PageSnapshot holds original word counts and copied rectangle coordinates. Counter detects missing occurrences of words. Font.measure_string() checks label width using the actual selected font, as described by the <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf.text/font/">Font API</a>. Inspection also rejects detected encryption, form fields, embedded files, and page annotations.</p><pre>&quot;&quot;&quot;Add headers and footers with Aspose.PDF; always start from a fresh source.&quot;&quot;&quot;<br>import argparse<br>from collections import Counter<br>from dataclasses import dataclass<br>from importlib.metadata import version<br>import os<br>from pathlib import Path<br>import re<br>import sys<br>from tempfile import TemporaryDirectory<br><br>import aspose.pdf as pdf<br><br>BASE = Path(__file__).resolve().parent<br>HEADER = &quot;Finance Department | Monthly Report&quot;<br>MARGIN = 24<br>BAND = 60<br>FONT_SIZE = 10<br>PAGE_LABEL = re.compile(r&quot;\bPage\s+\d+\s+of\s+\d+\b&quot;)<br><br><br>@dataclass(frozen=True)<br>class PageSnapshot:<br>    words: Counter<br>    crop_box: tuple<br>    media_box: tuple<br>    rotation: int<br><br><br>def labels(count, skip_cover=True, start=1, only_page=None):<br>    &quot;&quot;&quot;Map physical (one-based) pages to explicit displayed labels.&quot;&quot;&quot;<br>    if type(start) is not int or start &lt; 1:<br>        raise ValueError(&quot;start must be positive&quot;)<br>    eligible = list(range(2 if skip_cover else 1, count + 1))<br>    if not eligible:<br>        raise ValueError(&quot;No eligible pages&quot;)<br>    if only_page is not None and (type(only_page) is not int or only_page not in eligible):<br>        raise ValueError(&quot;Selected page must be eligible and within the document&quot;)<br>    last = start + len(eligible) - 1<br>    return {p: f&quot;Page {start + i} of {last}&quot;<br>            for i, p in enumerate(eligible) if only_page is None or p == only_page}<br><br><br>def rectangle_values(rectangle):<br>    &quot;&quot;&quot;Copy coordinates so snapshots do not retain mutable .NET rectangles.&quot;&quot;&quot;<br>    return (rectangle.llx, rectangle.lly, rectangle.urx, rectangle.ury)<br><br><br>def page_size(page):<br>    rectangle = page.get_page_rect(True)<br>    return rectangle.width, rectangle.height<br><br><br>def extract_text(page):<br>    &quot;&quot;&quot;Read text in unrotated coordinates; restore page rotation even on failure.&quot;&quot;&quot;<br>    rotation = page.rotate<br>    try:<br>        page.rotate = pdf.Rotation.NONE<br>        absorber = pdf.text.TextAbsorber()<br>        page.accept(absorber)<br>        return absorber.text<br>    finally:<br>        page.rotate = rotation<br><br><br>def text_rectangles(page, phrase=None):<br>    &quot;&quot;&quot;Return copies of text rectangles in the original PDF coordinate system.&quot;&quot;&quot;<br>    rotation = page.rotate<br>    try:<br>        page.rotate = pdf.Rotation.NONE<br>        absorber = (pdf.text.TextFragmentAbsorber() if phrase is None<br>                    else pdf.text.TextFragmentAbsorber(phrase))<br>        page.accept(absorber)<br>        return [rectangle_values(fragment.rectangle) for fragment in absorber.text_fragments]<br>    finally:<br>        page.rotate = rotation<br><br><br>def visible_rectangle(page, rectangle):<br>    &quot;&quot;&quot;Map unrotated PDF coordinates to the viewer&#39;s bottom-left coordinate system.&quot;&quot;&quot;<br>    crop = page.rect<br>    rotation = pdf.Page.rotation_to_int(page.rotate)<br>    points = []<br>    for x, y in ((rectangle[0], rectangle[1]), (rectangle[2], rectangle[1]),<br>                 (rectangle[0], rectangle[3]), (rectangle[2], rectangle[3])):<br>        x, y = x - crop.llx, y - crop.lly<br>        if rotation == 90:<br>            x, y = y, crop.width - x<br>        elif rotation == 180:<br>            x, y = crop.width - x, crop.height - y<br>        elif rotation == 270:<br>            x, y = crop.height - y, x<br>        points.append((x, y))<br>    return (min(x for x, y in points), min(y for x, y in points),<br>            max(x for x, y in points), max(y for x, y in points))<br><br><br>def inspect_document(document, header, numbering, font):<br>    &quot;&quot;&quot;Validate static inputs without rebuilding or normalizing their pages.&quot;&quot;&quot;<br>    if document.is_encrypted:<br>        raise ValueError(&quot;Encrypted inputs require a separate workflow&quot;)<br>    if len(document.form.fields):<br>        raise ValueError(&quot;Forms and signatures are outside this static-page example&quot;)<br>    if len(document.embedded_files):<br>        raise ValueError(&quot;Attachments require a separate preservation workflow&quot;)<br>    snapshots = []<br>    for index, page in enumerate(document.pages, 1):<br>        if len(page.annotations):<br>            raise ValueError(f&quot;Page {index}: annotations/widgets/links are unsupported&quot;)<br>        text = extract_text(page)<br>        if header in text or &quot;Evaluation Only&quot; in text or PAGE_LABEL.search(text):<br>            raise ValueError(f&quot;Page {index}: input appears stamped; use fresh source&quot;)<br>        width, height = page_size(page)<br>        if min(width, height) &lt; 180:<br>            raise ValueError(f&quot;Page {index}: too small for reserved stamp bands&quot;)<br>        if index in numbering:<br>            for raw in text_rectangles(page):<br>                left, bottom, right, top = visible_rectangle(page, raw)<br>                # Ignore text wholly outside the visible CropBox.<br>                if right &lt;= 0 or left &gt;= width or top &lt;= 0 or bottom &gt;= height:<br>                    continue<br>                if bottom &lt; BAND or top &gt; height - BAND:<br>                    raise ValueError(f&quot;Page {index}: text occupies a reserved 60pt band&quot;)<br>            for value in (header, numbering[index]):<br>                if font.measure_string(value, FONT_SIZE) &gt; width - 2 * MARGIN:<br>                    raise ValueError(f&quot;Page {index}: header or footer is too wide&quot;)<br>        snapshots.append(PageSnapshot(<br>            Counter(text.split()), rectangle_values(page.crop_box),<br>            rectangle_values(page.media_box), pdf.Page.rotation_to_int(page.rotate)))<br>    return snapshots<br><br><br>def add_header_footer(page, header, footer):<br>    &quot;&quot;&quot;Aspose aligns stamps to the visible rotated page; dimensions are PDF points.&quot;&quot;&quot;<br>    font = pdf.text.FontRepository.find_font(&quot;Arial&quot;)<br>    for value, is_footer in ((header, False), (footer, True)):<br>        stamp = pdf.TextStamp(value)<br>        stamp.background = False<br>        stamp.text_state.font = font<br>        stamp.text_state.font_size = FONT_SIZE<br>        stamp.text_state.foreground_color = pdf.Color.dark_blue<br>        if is_footer:<br>            stamp.horizontal_alignment = pdf.HorizontalAlignment.CENTER<br>            stamp.vertical_alignment = pdf.VerticalAlignment.BOTTOM<br>            stamp.bottom_margin = MARGIN<br>        else:<br>            stamp.horizontal_alignment = pdf.HorizontalAlignment.LEFT<br>            stamp.vertical_alignment = pdf.VerticalAlignment.TOP<br>            stamp.left_margin = MARGIN<br>            stamp.top_margin = MARGIN<br>        page.add_stamp(stamp)<br><br><br>def verify(staged, snapshots, numbering, header):<br>    &quot;&quot;&quot;Reopen with Aspose and check text, original page boxes/rotation, and stamp placement.&quot;&quot;&quot;<br>    with pdf.Document(str(staged)) as result:<br>        if len(result.pages) != len(snapshots):<br>            raise ValueError(&quot;Saved page count changed&quot;)<br>        for index, snapshot in enumerate(snapshots, 1):<br>            page = result.pages[index]<br>            text = extract_text(page)<br>            if snapshot.words - Counter(text.split()):<br>                raise ValueError(f&quot;Page {index}: source text missing after save&quot;)<br>            geometry = rectangle_values(page.crop_box) + rectangle_values(page.media_box)<br>            expected = snapshot.crop_box + snapshot.media_box<br>            if (pdf.Page.rotation_to_int(page.rotate) != snapshot.rotation<br>                    or any(abs(a - b) &gt; .1 for a, b in zip(geometry, expected))):<br>                raise ValueError(f&quot;Page {index}: page boxes or rotation changed&quot;)<br>            if index not in numbering:<br>                if header in text or PAGE_LABEL.search(text):<br>                    raise ValueError(f&quot;Page {index}: excluded page was stamped&quot;)<br>                continue<br>            width, height = page_size(page)<br>            for value, is_footer in ((header, False), (numbering[index], True)):<br>                matches = text_rectangles(page, value)<br>                if len(matches) != 1:<br>                    raise ValueError(f&quot;Page {index}: expected exactly one {value!r}&quot;)<br>                left, bottom, right, top = visible_rectangle(page, matches[0])<br>                if left &lt; -.1 or bottom &lt; -.1 or right &gt; width + .1 or top &gt; height + .1:<br>                    raise ValueError(f&quot;Page {index}: clipped stamp&quot;)<br>                if is_footer:<br>                    if top &gt; BAND or abs((left + right) / 2 - width / 2) &gt; 1:<br>                        raise ValueError(f&quot;Page {index}: footer outside centered bottom band&quot;)<br>                elif bottom &lt; height - BAND:<br>                    raise ValueError(f&quot;Page {index}: header outside top band&quot;)<br><br><br>def process(source, destination, *, header=HEADER, skip_cover=True, start=1,<br>            only_page=None, allow_evaluation=False):<br>    source = Path(source).resolve(strict=True)<br>    destination = Path(destination).resolve()<br>    if source == destination or os.path.lexists(destination):<br>        raise FileExistsError(f&quot;Refusing destination collision: {destination}&quot;)<br>    if not header.strip() or not header.isascii() or &quot;\n&quot; in header or &quot;\r&quot; in header:<br>        raise ValueError(&quot;Header must be one nonempty ASCII line for this font example&quot;)<br>    license_object = None<br>    license_path = os.environ.get(&quot;ASPOSE_PDF_LICENSE&quot;)<br>    if license_path:<br>        license_object = pdf.License()<br>        license_object.set_license(str(Path(license_path).resolve(strict=True)))<br>    if license_object is None and not allow_evaluation:<br>        raise ValueError(&quot;Set ASPOSE_PDF_LICENSE or pass --allow-evaluation for a watermarked demo&quot;)<br><br>    with pdf.Document(str(source)) as document:<br>        page_count = len(document.pages)<br>        if license_object is None and page_count &gt; 4:<br>            raise ValueError(&quot;Evaluation demo is limited to four input pages&quot;)<br>        numbering = labels(page_count, skip_cover, start, only_page)<br>        font = pdf.text.FontRepository.find_font(&quot;Arial&quot;)<br>        snapshots = inspect_document(document, header, numbering, font)<br>        destination.parent.mkdir(parents=True, exist_ok=True)<br>        with TemporaryDirectory(prefix=&quot;.header-footer-&quot;, dir=destination.parent) as temporary:<br>            staged = Path(temporary) / &quot;stamped.pdf&quot;<br>            for physical, footer in numbering.items():<br>                try:<br>                    add_header_footer(document.pages[physical], header, footer)<br>                except Exception as exc:<br>                    raise RuntimeError(f&quot;Stamping physical page {physical}: {exc}&quot;) from exc<br>            document.save(str(staged))<br>            verify(staged, snapshots, numbering, header)<br>            # Same-filesystem, no-clobber publication; the source is never saved in place.<br>            os.link(staged, destination)<br>    return numbering<br><br><br>def main():<br>    parser = argparse.ArgumentParser(description=__doc__)<br>    parser.add_argument(&quot;--input&quot;, type=Path, default=BASE / &quot;input/monthly-report.pdf&quot;)<br>    parser.add_argument(&quot;--output&quot;, type=Path, default=BASE / &quot;output/monthly-report.pdf&quot;)<br>    parser.add_argument(&quot;--header&quot;, default=HEADER)<br>    parser.add_argument(&quot;--start&quot;, type=int, default=1)<br>    parser.add_argument(&quot;--include-cover&quot;, action=&quot;store_true&quot;)<br>    parser.add_argument(&quot;--only-page&quot;, type=int)<br>    parser.add_argument(&quot;--allow-evaluation&quot;, action=&quot;store_true&quot;)<br>    args = parser.parse_args()<br>    try:<br>        numbering = process(args.input, args.output, header=args.header,<br>                            skip_cover=not args.include_cover, start=args.start,<br>                            only_page=args.only_page, allow_evaluation=args.allow_evaluation)<br>        print(f&quot;Verified labels: {numbering}&quot;)<br>        print(f&quot;Published: {args.output}&quot;)<br>        print(f&quot;Aspose.PDF {version(&#39;aspose-pdf&#39;)}&quot;)<br>    except Exception as exc:<br>        print(f&quot;FAILED ({args.input} -&gt; {args.output}): {exc}&quot;, file=sys.stderr)<br>        return 1<br>    return 0<br><br><br>if __name__ == &quot;__main__&quot;:<br>    raise SystemExit(main())</pre><p>From the example directory, run the command in section “Number every eligible page” with a new output filename. Expected messages are:</p><pre>Verified labels: {2: &#39;Page 1 of 3&#39;, 3: &#39;Page 2 of 3&#39;, 4: &#39;Page 3 of 3&#39;}<br>Published: output/article-demo.pdf<br>Aspose.PDF 26.8.0</pre><p>Path separators may differ by platform. The verified PDF generated for this draft is article-report.pdf.</p><p>Reproduce two failure cases:</p><pre>python pdf_header_footer.py - input input/not-a-pdf.pdf - output output/invalid-demo.pdf - allow-evaluation<br>python pdf_header_footer.py - input input/rotations.pdf - start 0 - output output/invalid-number-demo.pdf - allow-evaluation</pre><p>Both commands exit with status 1 and a FAILED (input -&gt;output): message. Neither publishes a final PDF. For regression checks, run:</p><pre>python test_header_footer.py</pre><p>All six test methods passed in the exercised environment. They cover numbering, geometry, single-page selection, invalid inputs, occupied bands, destination collisions, unchanged source bytes, repeated stamping, and rejection of incorrect saved labels. Tests create temporary fixtures rather than relying on a mutable monthly report.</p><h3><strong>Limits and next steps</strong></h3><p>This workflow adds labels to static pages that already have suitable space. A scanned page, image, or vector drawing may occupy the reserved bands without producing an extractable text rectangle, so visual review remains necessary.</p><p>Tagged, certified, archival, layered, and other complex PDFs need preservation checks suited to their requirements. Keeping words, page boxes, and rotation values does not establish accessibility, signature validity, or complete visual equivalence.</p><p>For recurring reports, useful next steps are a separate global numbering total, automated before-and-after rendering, and a manifest recording the source identity and numbering settings. If pages need merging or reordering, finish that work before assigning final page numbers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f748a1b345ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/how-to-add-headers-footers-and-page-numbers-to-pdfs-with-python-f748a1b345ff">How to Add Headers, Footers, and Page Numbers to PDFs with Python</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add, Delete, and Reorder PDF Pages with Python]]></title>
            <link>https://medium.com/asposepdf/how-to-add-delete-and-reorder-pdf-pages-with-python-37fb4fb22b84?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/37fb4fb22b84</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 14:57:53 GMT</pubDate>
            <atom:updated>2026-10-29T14:57:53.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZfTBSxdvzvPFi70pK9VaA.png" /></figure><p><em>Repair a report by inserting a cover, removing an unwanted page, and moving an appendix.</em></p><p>A report is ready to share, but it&#39;s missing its cover, has a placeholder in the middle, and the appendix belongs near the front. Fixing one file in a PDF editor is straightforward. Repeating the same edits across reports introduces a less obvious problem: every insertion or deletion changes the positions of the remaining pages.</p><p>If you delete page 3 and then move page 6, does “page 6” mean the sixth page of the original file or the document you have just edited?</p><p>This tutorial makes that choice explicit. We will refer to original page identities, describe the complete final sequence, and build a separate PDF from that sequence. Before publishing it, we will reopen the saved file and check its page count, text, dimensions, and rotation.</p><p>The example uses Aspose.PDF for Python via .NET. We successfully ran a smaller evaluation example; the full six-page scenario requires a license, as explained below.</p><figure><img alt="Diagram showing the original six pages and the intended order: cover, 6, 1, 2, 4, 5" src="https://cdn-images-1.medium.com/max/1024/1*DM3iylYUeE2y4BBzGoo3sg.png" /><figcaption>Diagram showing the original six pages and the intended order: cover, 6, 1, 2, 4, 5</figcaption></figure><p><em>The plan uses original page identities, even when their output positions change.</em></p><h4><strong>What we will build</strong></h4><p>Our input is a six-page synthetic report plus a separate one-page cover. We want to remove original page 3 and move original page 6 (the appendix) immediately after the cover.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*cbyy8zh60f-kZubNUSDg8A.png" /></figure><p>Each fixture page has a visible identity marker. Page 3 represents an unwanted blank or placeholder page, but contains a marker and explanatory text so we can verify its removal. This example does not attempt automatic blank-page detection.</p><p>The final document must contain exactly six pages in this order:</p><pre>cover, original-6, original-1, original-2, original-4, original-5</pre><p>Our workflow is:</p><pre>Inspect input -&gt; Validate configuration -&gt; Process document<br>             -&gt; Stage output -&gt; Verify result -&gt; Publish output</pre><p>We will handle static, text-bearing fixtures. Forms, bookmarks, links, signatures, encryption, and scanned documents require additional decisions beyond rearranging a page collection.</p><figure><img alt="Original six-page report with visible identity markers" src="https://cdn-images-1.medium.com/max/855/1*jGq3NxEvdi1TYG8xNpN1lQ.png" /><figcaption>Original six-page report with visible identity markers</figcaption></figure><p><em>Before: the appendix is last, and the marked placeholder occupies position 3.</em></p><h4><strong>Set up the project</strong></h4><p>The example folder contains the scripts, input PDFs, plans, and previews. Use Python 3.11 or later.</p><pre>07-pdf-auto-page-reorder/<br>  pdf-page-reorder.py<br>  create-fixtures.py<br>  test_reorder.py<br>  verify-and-render.py<br>  requirements.txt<br>  requirements-dev.txt<br>  input/<br>    report.pdf<br>    report-small.pdf<br>    cover.pdf<br>    cover-landscape.pdf<br>  plans/<br>    repair.json<br>    evaluation.json<br>    invalid-duplicate.json<br>  expected/<br>    repaired-report.pdf<br>  output/<br>    evaluation-report.pdf<br>  previews/</pre><p>Install the processing dependency:</p><pre>pip install aspose-pdf</pre><p>For the version used here, run pip install-r requirements.txt from the example folder; it pins Aspose.PDF to 26.8.0. Optional development dependencies generate fixtures and independently inspect the results:</p><pre>pip install -r requirements-dev.txt</pre><p>The existing fixtures are ready to use. create-fictures.pyrefuses to overwrite them. Move the existing input and expected PDFs aside before regenerating them.</p><p>Check the <a href="https://docs.aspose.com/pdf/python-net/system-requirements/">platform requirements</a> for your deployment. This example was exercised on Windows with Python 3.11.15. Linux also needs the native dependencies described in that documentation.</p><h4>Factor in evaluation limits</h4><p>The <a href="https://docs.aspose.com/pdf/python-net/installation/">installation documentation</a> describes evaluation watermarks and a four-element collection limit. The six-page report exceeds that limit. Use a valid license or request a temporary license through the <a href="https://docs.aspose.com/pdf/python-net/licensing/">licensing documentation</a></p><p>In PowerShell, set the license path before running the full example:</p><pre>$env:ASPOSE_PDF_LICENSE = &#39;C:/licenses/Aspose.PDF.lic&#39;</pre><p>The repository does not include a license. During validation, the unlicensed full run failed. Evaluation mode can view at most 4 elements (for any collection). It did not publish a six-page output.</p><h4><strong>Describe edits using original identities</strong></h4><p>The configuration in plans/repair.json separates the deletion policy from the final order:</p><pre>{<br>  &quot;delete&quot;: [3],<br>  &quot;sequence&quot;: [<br>    &quot;cover&quot;, &quot;original-6&quot;, &quot;original-1&quot;,<br>    &quot;original-2&quot;, &quot;original-4&quot;, &quot;original-5&quot;<br>  ]<br>}</pre><p>deletecontains original, one-based physical page numbers. sequence names each retained page in its intended output position. Neither refers to printed page labels.</p><p>The validator requires exactly one cover and every undeleted original exactly once. It rejects duplicate deletions, numbers outside the source range, repeated identities, missing retained pages, and unexpected identities. For example, repeating original-4 while omitting original-5 must fail even though the list still contains six entries.</p><p>The report remains untouched while the output is assembled, so original-6 always resolves to report.pages[6].</p><p><strong>Add a blank page or insert a cover</strong></p><p>Aspose’s <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/">PageCollection API</a> provides add, insert, delete.Its page positions in this workflow are one-based.</p><p>To append a blank page, create it and set its dimensions:</p><pre>page = document.pages.add()<br>page.set_page_size(595, 842)</pre><p>Dimensions are PDF points, with 72 points per inch. These dimensions approximate portrait A4. Swapping them produces a landscape page. The complete script wraps this operation inadd_blank_page, which rejects nonpositive dimensions.</p><p>To insert the first page of a separate cover PDF at the front:</p><pre>document.pages.insert(1, cover.pages[1])</pre><p>Our insert_covert helper checks that the cover has exactly one page and that the insertion position is between 1 and the current page count plus 1. It preserves the imported page’s dimensions. A landscape cover therefore remains landscape rather than being resized to match the report.</p><p>These helpers demonstrate individual edits. Don&#39;t apply them before the rebuild operation; the rebuild already includes the cover in its final sequence.</p><h4><strong>Delete selected pages without shifting the wrong indices</strong></h4><p>When editing an original page collection directly, validate all selections first, then delete in descending order:</p><pre>for number in sorted(deleted, reverse=True):<br>    document.pages.delete(number)</pre><p>Suppose you want to remove original pages 2 and 3. Deleting page 2 first shifts original page 3 into position 2. Deleting the new page 3 then removes original page 4. Descending deletion removes original page 3 first and original page 2 second, preserving the meaning of both selections.</p><p>The script’s delete_original_pages helper demonstrates this approach. The final rebuild deletes by omitting identities from the output, so it doesn&#39;t need to mutate the report at all.</p><p><strong>Reorder by building a new document</strong></p><p>For each identity in the validated sequence, resolve the corresponding source page and append it to a new document:</p><pre>for identity in sequence:<br>    source = (<br>        cover.pages[1]<br>        if identity == &quot;cover&quot;<br>        else report.pages[int(identity[9:])]<br>    )<br>    output.pages.add(source)</pre><p>Keep both source documents open until the copied pages have been saved. The complete implementation manages their lifetimes with context managers and ExitStack, including when an exception interrupts processing.</p><figure><img alt="Expected six-page arrangement" src="https://cdn-images-1.medium.com/max/855/1*kV-hzHL0o42sPDfMinLEZw.png" /><figcaption>Expected six-page arrangement</figcaption></figure><p><em>Arrangement. This illustration was generated independently with ReportLab; it is not the output of a licensed six-page Aspose run.</em></p><h4><strong>Inspect references and interactive content</strong></h4><p>Copying pages does not establish that references to those pages remain meaningful. A bookmark might point to an omitted page. A form field might point to a page that has moved. Structural changes can invalidate a signature.</p><p>The example takes a conservative approach: it rejects encrypted documents, bookmarks, form fields, and page annotations, including links. The same checks run on the staged result. The relevant properties are documented in the <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf/document/">Document API</a> and <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf/page/">Page API</a></p><p>This inspection is a scope check, not a comprehensive detection of every PDF feature. It does not migrate or verify named destinations, document actions, attachments, tags, page labels, or metadata. Signed and interactive documents need a separate workflow with explicit preservation and validation requirements.</p><h4><strong>Verify more than the page count</strong></h4><p>Six pages can still be six wrong pages. Before saving, the script records each selected page’s normalized text, dimensions, and rotation. It also requires exactly one expected identity marker on that page.</p><p>After saving, it reopens the staged PDF and compares each output position with its recorded source. Dimensions may differ by no more than 0.01 points. Text is compared after whitespace normalization, using <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/">TextAbsorber</a>.</p><p>The function named signature in the script returns this comparison data; it is unrelated to cryptographic PDF signatures.</p><p>These checks are deliberately fixture-specific. A scanned page with no extractable marker fails. Matching text cannot prove that graphics, fonts, spacing, or reading order are correct. Rendered review remains necessary.</p><h4><strong>Stage the output before publishing it</strong></h4><figure><img alt="Six-step workflow: inspect, validate, process, stage, verify, and publish" src="https://cdn-images-1.medium.com/max/1024/1*Nuoo3PqbsfrTR0_ym5AKiQ.png" /><figcaption>Six-step workflow: inspect, validate, process, stage, verify, and publish</figcaption></figure><p><em>Reopen and verify the staged PDF before publishing to a new destination.</em></p><p>The script requires a new destination separate from both inputs. It creates a temporary directory beside that destination, saves there, and verifies the staged file before publishing.</p><p>Publication uses os.link to create a hard link to the verified file. An existing destination causes failure, including when another process creates it after the initial collision check. This requires a filesystem that supports hard links; unsupported filesystems fail rather than silently switching to overwrite behavior.</p><p>This is not a cross-platform atomicity or crash-durability guarantee. Temporary files are cleaned up, although an empty output directory can remain after a failed job.</p><p>The command reports the failed source and destination. Copying and verification errors also identify the output position. Missing inputs, unreadable PDFs, permission errors, and failed writes result in a nonzero exit status. Published appears only after the verified file has been linked successfully.</p><h4><strong>Complete runnable example</strong></h4><p>Save the following as pdf-page-reorder.py beside the supplied input/and plansdirectories. It combines the helpers discussed above, configuration loading, validation, processing, verification, and the command-line entry point.</p><pre>&quot;&quot;&quot;Rebuild a static PDF using original page identities; publish after verification.&quot;&quot;&quot;<br><br>import argparse<br>from contextlib import ExitStack<br>from importlib.metadata import version<br>import json<br>import os<br>from pathlib import Path<br>import re<br>import sys<br>from tempfile import TemporaryDirectory<br><br>import aspose.pdf as pdf<br><br>BASE = Path(__file__).resolve().parent<br>MARKER = re.compile(r&quot;\b(?:cover|original-[1-9][0-9]*)\b&quot;)<br><br><br>def validate_plan(page_count, deleted, sequence):<br>    &quot;&quot;&quot;Require every retained original exactly once, plus exactly one cover.&quot;&quot;&quot;<br>    if any(type(n) is not int or not 1 &lt;= n &lt;= page_count for n in deleted):<br>        raise ValueError(f&quot;Deleted pages must be integers in 1..{page_count}&quot;)<br>    if len(set(deleted)) != len(deleted):<br>        raise ValueError(&quot;Repeated deletion&quot;)<br>    expected = {f&quot;original-{n}&quot; for n in range(1, page_count + 1) if n not in deleted}<br>    expected.add(&quot;cover&quot;)<br>    if len(sequence) != len(set(sequence)):<br>        raise ValueError(&quot;Repeated identity in final sequence&quot;)<br>    if set(sequence) != expected:<br>        raise ValueError(f&quot;Sequence mismatch: missing={sorted(expected - set(sequence))}, &quot;<br>                         f&quot;unexpected={sorted(set(sequence) - expected)}&quot;)<br><br><br>def delete_original_pages(document, deleted):<br>    &quot;&quot;&quot;Call before inserting or moving anything; descending indices stay stable.&quot;&quot;&quot;<br>    validate_plan(len(document.pages), deleted,<br>                  [&quot;cover&quot;] + [f&quot;original-{n}&quot; for n in range(1, len(document.pages) + 1)<br>                               if n not in deleted])<br>    for number in sorted(deleted, reverse=True):<br>        document.pages.delete(number)<br><br><br>def insert_cover(document, cover, position=1):<br>    &quot;&quot;&quot;One-based insertion position, including count + 1 for appending.&quot;&quot;&quot;<br>    if type(position) is not int or not 1 &lt;= position &lt;= len(document.pages) + 1:<br>        raise ValueError(&quot;Cover position must be in 1..page_count + 1&quot;)<br>    if len(cover.pages) != 1:<br>        raise ValueError(&quot;Cover PDF must contain exactly one page&quot;)<br>    document.pages.insert(position, cover.pages[1])<br><br><br>def add_blank_page(document, width=595, height=842):<br>    &quot;&quot;&quot;Explicit dimensions in PDF points (72 points per inch).&quot;&quot;&quot;<br>    if width &lt;= 0 or height &lt;= 0:<br>        raise ValueError(&quot;Blank page dimensions must be positive&quot;)<br>    page = document.pages.add()<br>    page.set_page_size(width, height)<br>    return page<br><br><br>def inspect_static(document, name):<br>    &quot;&quot;&quot;Conservative scope gate, not a comprehensive PDF security audit.&quot;&quot;&quot;<br>    if document.is_encrypted:<br>        raise ValueError(f&quot;{name}: encrypted PDFs require a separate workflow&quot;)<br>    if len(document.outlines) or len(document.form.fields):<br>        raise ValueError(f&quot;{name}: bookmarks or form/signature fields need separate handling&quot;)<br>    for n in range(1, len(document.pages) + 1):<br>        if len(document.pages[n].annotations):<br>            raise ValueError(f&quot;{name}, page {n}: annotations/links require separate handling&quot;)<br><br><br>def signature(page, allow_evaluation_watermark=False):<br>    absorber = pdf.text.TextAbsorber()<br>    absorber.visit(page)<br>    text = &quot; &quot;.join(absorber.text.split())<br>    if allow_evaluation_watermark:<br>        text = re.sub(r&quot;Evaluation Only\. Created with Aspose\.PDF\. Copyright 2002-2026 Aspose Pty Ltd\.&quot;, &quot;&quot;, text).strip()<br>    rect = page.rect<br>    return text, (rect.width, rect.height), str(page.rotate)<br><br><br>def rebuild(report_file, cover_file, destination, deleted, sequence, allow_evaluation_watermark=False):<br>    &quot;&quot;&quot;Inspect -&gt; validate -&gt; process -&gt; stage -&gt; verify -&gt; publish.<br><br>    Inputs stay open until copied pages are saved. Context manager exits<br>    release .NET resources, including on errors. Existing output is refused.<br>    &quot;&quot;&quot;<br>    report_file = Path(report_file).resolve(strict=True)<br>    cover_file = Path(cover_file).resolve(strict=True)<br>    destination = Path(destination).resolve()<br>    if destination in (report_file, cover_file) or os.path.lexists(destination):<br>        raise FileExistsError(f&quot;Destination must be new and separate: {destination}&quot;)<br>    with ExitStack() as stack:<br>        def opened(path=None):<br>            doc = pdf.Document(str(path)) if path else pdf.Document()<br>            stack.enter_context(doc)<br>            return doc<br><br>        report, cover = opened(report_file), opened(cover_file)<br>        validate_plan(len(report.pages), deleted, sequence)<br>        if len(cover.pages) != 1:<br>            raise ValueError(&quot;Cover PDF must contain exactly one page&quot;)<br>        inspect_static(report, report_file.name)<br>        inspect_static(cover, cover_file.name)<br>        output = opened()<br>        expected = []<br>        for position, identity in enumerate(sequence, 1):<br>            source = cover.pages[1] if identity == &quot;cover&quot; else report.pages[int(identity[9:])]<br>            item = signature(source)<br>            if MARKER.findall(item[0]) != [identity]:<br>                raise ValueError(f&quot;{identity}: expected one unique fixture marker; scans need OCR/review&quot;)<br>            expected.append(item)<br>            try:<br>                output.pages.add(source)<br>            except Exception as exc:<br>                raise RuntimeError(f&quot;Copy {identity} to output page {position}: {exc}&quot;) from exc<br>        destination.parent.mkdir(parents=True, exist_ok=True)<br>        with TemporaryDirectory(prefix=&quot;.reorder-&quot;, dir=destination.parent) as temporary:<br>            staged = Path(temporary) / &quot;report.pdf&quot;<br>            output.save(str(staged))<br>            check = opened(staged)<br>            if len(check.pages) != len(sequence):<br>                raise ValueError(&quot;Saved page count differs from requested sequence&quot;)<br>            for position, identity in enumerate(sequence, 1):<br>                actual = signature(check.pages[position], allow_evaluation_watermark)<br>                text, size, rotation = expected[position - 1]<br>                if (actual[0] != text or actual[2] != rotation<br>                        or any(abs(a - b) &gt; 0.01 for a, b in zip(actual[1], size))):<br>                    raise ValueError(f&quot;Verification failed at output page {position} ({identity})&quot;)<br>            inspect_static(check, staged.name)<br>            # check remains open through publication; ExitStack releases it.<br>            # Hard-link publication refuses an existing target, including a race.<br>            # Same-filesystem hard links are required; failure leaves no final PDF.<br>            os.link(staged, destination)<br>    return destination<br><br><br>def load_license():<br>    path = os.environ.get(&quot;ASPOSE_PDF_LICENSE&quot;)<br>    if path:<br>        license = pdf.License()<br>        license.set_license(str(Path(path).resolve(strict=True)))<br>        return license<br>    return None<br><br><br>def main():<br>    parser = argparse.ArgumentParser(description=__doc__)<br>    parser.add_argument(&quot;--report&quot;, type=Path, default=BASE / &quot;input/report.pdf&quot;)<br>    parser.add_argument(&quot;--cover&quot;, type=Path, default=BASE / &quot;input/cover.pdf&quot;)<br>    parser.add_argument(&quot;--output&quot;, type=Path, default=BASE / &quot;output/repaired-report.pdf&quot;)<br>    parser.add_argument(&quot;--plan&quot;, type=Path, default=BASE / &quot;plans/repair.json&quot;)<br>    parser.add_argument(&quot;--allow-evaluation-watermark&quot;, action=&quot;store_true&quot;)<br>    args = parser.parse_args()<br>    try:<br>        license = load_license()  # Keep the license alive throughout processing.<br>        plan = json.loads(args.plan.read_text(encoding=&quot;utf-8&quot;))<br>        result = rebuild(args.report, args.cover, args.output, plan[&quot;delete&quot;], plan[&quot;sequence&quot;], args.allow_evaluation_watermark)<br>        print(f&quot;Verified {len(plan[&#39;sequence&#39;])} pages: {&#39;, &#39;.join(plan[&#39;sequence&#39;])}&quot;)<br>        print(f&quot;Published: {result}&quot;)<br>        print(f&quot;Aspose.PDF {version(&#39;aspose-pdf&#39;)}; licensed={license is not None}&quot;)<br>    except Exception as exc:<br>        print(f&quot;FAILED ({args.report} -&gt; {args.output}): {exc}&quot;, file=sys.stderr)<br>        return 1<br>    return 0<br><br><br>if __name__ == &quot;__main__&quot;:<br>    raise SystemExit(main())<br><br></pre><p>From the example folder, run:</p><pre>python pdf-page-reorder.py</pre><p>With a valid license, the expected messages are:</p><pre>Verified 6 pages: cover, original-6, original-1, original-2, original-4, original-5<br>Published: .../output/repaired-report.pdf<br>Aspose.PDF 26.8.0; licensed=True</pre><p>These are expected licensed messages, not a captured successful six-page run. The default paths are relative to the script. Explicit command-line paths are relative to your working directory. Choose a fresh ` — output` when repeating a run.</p><h4><strong>Run the smaller evaluation fixture</strong></h4><p>The supplied three-page report stays within the evaluation collection limit. This command was exercised successfully:</p><pre>python pdf-page-reorder.py --report input/report-small.pdf --plan plans/evaluation.json --output output/my-evaluation-report.pdf --allow-evaluation-watermark</pre><p>It removes original page 2 and produces:</p><pre>Verified 3 pages: cover, original-3, original-1</pre><p>The watermark option ignores only the exact 2026 evaluation banner observed with Aspose.PDF 26.8.0 during text comparison. It leaves the watermark in the PDF. Other banner text still fails verification; omit this option for licensed processing.</p><figure><img alt="Actual evaluation output" src="https://cdn-images-1.medium.com/max/855/1*1n9hjNVhLAFhwvOAtkcnVQ.png" /><figcaption>Actual evaluation output</figcaption></figure><p><em>Actual three-page evaluation output, including the evaluation watermark.</em></p><h4><strong>Try an invalid plan</strong></h4><pre>python pdf-page-reorder.py --plan plans/invalid-duplicate.json --output output/invalid.pdf</pre><p>The command exits with status 1 and reports Repeated identity in final sequence. It does not publish invalid.pdf.</p><h4><strong>Independently inspect and render the PDFs</strong></h4><p>Run the supporting checks with:</p><pre>python test_reorder.py<br>python verify-and-render.py</pre><p>It saves their previews as before.png, expected-after.png, and evaluation-after.png. The script expects the bundled result atoutput/evaluation-report.pdf; a newly created file with another name is not automatically selected.</p><p>Its assertions are development checks: run it normally, without Python’s O option, which disables assertions. The production rebuild uses explicit exceptions for its verification failures.</p><p>The passing cases cover invalid plans, adjacent deletions, invalid insertion positions, blank-page addition, landscape-cover insertion, missing input, destination collisions, source-byte preservation, and the smaller end-to-end rebuild. Independent marker checks passed, and we visually reviewed the contact sheets. We can&#39;t verify the full six-page Aspose integration until you provide a license. We don&#39;t claim any performance benchmark for these tiny fixtures.</p><h4><strong>Common mistakes and a useful next step</strong></h4><p>The most costly mistake is mixing original page identities with changing collection positions. Either delete original indices in descending order or rebuild from a validated final sequence, as we did here.</p><p>Another mistake is treating a successful save as proof of correctness. Reopen the output, inspect the exact sequence, and review how it looks. Don&#39;t treat six pages as proof that the appendix is in position two.</p><p>Before applying this workflow to a real report, check that:</p><ul><li>Every retained original appears exactly once in the plan.</li><li>The destination is separate from the sources and does not already exist.</li><li>Text, page dimensions, rotation, and visible order pass review.</li><li>Interactive features, scans, and signatures have an appropriate separate workflow.</li></ul><p>A practical extension is a manifest containing the original file hashes, final identity sequence, library version, and verification results. That would make batch jobs easier to audit without changing the identity-based processing model.</p><p>For a related operation, see the series example on <a href="https://medium.com/asposepdf/extract-just-the-pdf-pages-you-need-with-python-e3bd32eca234">extracting selected PDF pages</a>. The same habit applies there: define exactly which original pages you want before changing the document.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37fb4fb22b84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/how-to-add-delete-and-reorder-pdf-pages-with-python-37fb4fb22b84">How to Add, Delete, and Reorder PDF Pages with Python</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extract Just the PDF Pages You Need with Python]]></title>
            <link>https://medium.com/asposepdf/extract-just-the-pdf-pages-you-need-with-python-e3bd32eca234?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3bd32eca234</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 10:58:59 GMT</pubDate>
            <atom:updated>2026-10-28T11:01:44.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SewNr4E0SVf5WD6cKlZ-rw.png" /></figure><p>Sometimes, you might only need five pages from a report that has forty-five.</p><p>Exporting those pages by hand is easy at first. But it gets tedious if the selection changes, the source report is updated, or someone needs to track where a page in the smaller file came from.</p><p>To make this easier, we built a Python script. You can tell it which pages you want, like 2, 5, or 9–11, and it will create a PDF with those pages in order. The script checks the saved file and creates a manifest showing where each page came from. It also saves the source path, page count, creation time, library version, and SHA-256 hashes for both PDFs. This way, you can identify the original files even if they get renamed later.</p><p>After extracting the source, the script re-hashes it. If any bytes change during the process, it stops and doesn&#39;t save the result.</p><p>The script puts both files in a temporary folder. Once everything is verified, it renames the results folder to a unique final name. Previous packets remain available, and if copying or verification fails, the packet isn&#39;t finalized. Remember, directory renaming might not be atomic on all filesystems.</p><h3>From a report to a five-page packet</h3><p>Our example starts with a PDF, a 45-page document titled <em>Cities in the World 2026</em>. It contains city tables with coordinates, countries, population figures, and continents.</p><p>The selection is a single setting:</p><pre>PAGE_SELECTION = &quot;2,5,9-11&quot;</pre><p>This expands to pages 2, 5, 9, 10, and 11. The supplied evidence-packet.pdf contains those five pages: a title page followed by four pages of city tables. We checked the extracted text against the source at each position.</p><p>Page numbers here mean physical positions from the start of the PDF. They can differ from the numbers printed on the page. In our example, the selected title page shows 1 but appears at position 2 in the original file.</p><h3>Set up the script</h3><p>The script uses Aspose.PDF for Python via .NET:</p><pre>pip install aspose-pdf</pre><p>Its settings sit together near the top:</p><pre>BASE_DIR = Path(__file__).resolve().parent<br>INPUT_FILE = BASE_DIR / &quot;data&quot; / &quot;input&quot; / &quot;report.pdf&quot;<br>OUTPUT_ROOT = BASE_DIR / &quot;data&quot; / &quot;output&quot;<br>PAGE_SELECTION = &quot;2,5,9-11&quot;<br>OUTPUT_FILENAME = &quot;evidence-packet.pdf&quot;</pre><p>Paths are relative to the script, so launching it from another folder won&#39;t change where it looks for the input. The full script also reads an optional password from PDF_PASSWORD and a license path from ASPOSE_PDF_LICENSE.</p><p>Aspose&#39;s evaluation mode adds watermarks. Use an appropriate license to reproduce the finished example; its <a href="https://docs.aspose.com/pdf/python-net/licensing/">licensing documentation</a> explains the setup.</p><h4>Check the selection before copying</h4><p>Our `parse_selection()` function accepts individual pages and inclusive ranges. It preserves order, so 5,2 produces page five first, then page two.</p><p>It rejects duplicates, reversed ranges, empty items, zero, and numbers beyond the source page count. That catches mistakes before it writes any output.</p><pre>parse_selection(&quot;2,5,9-11&quot;, 45)<br># [2, 5, 9, 10, 11]<br><br>parse_selection(&quot;5,2&quot;, 45)<br># [5, 2]</pre><p>Once the selection is valid, the copying function does the work:</p><pre>def copy_pages(source: apdf.Document, pages: list[int], output_file: Path) -&gt; None:<br>    &quot;&quot;&quot;Copy requested pages using Aspose&#39;s one-based page collection.&quot;&quot;&quot;<br>    with apdf.Document() as output:<br>        output.ignore_corrupted_objects = False<br>        for position, page_number in enumerate(pages, start=1):<br>            try:<br>                output.pages.add(source.pages[page_number])<br>            except Exception as exc:<br>                raise RuntimeError(<br>                    f&quot;Copying source page {page_number} to output page &quot;<br>                    f&quot;{position} failed: {exc}&quot;<br>                ) from exc<br>        try:<br>            output.save(str(output_file))<br>        except Exception as exc:<br>            raise RuntimeError(f&quot;Saving {output_file.name} failed: {exc}&quot;) from exc</pre><p>Aspose uses one-based page indexing, so `source.pages[2]` means the second page. We add each requested page to a new document and save it. The library&#39;s <a href="https://docs.aspose.com/pdf/python-net/extract-pages/">page extraction guide</a> uses the same approach.</p><p>The error messages identify both the source page and its destination position. That helps locate a failed copy without guessing which page caused it.</p><h4>Reopen the result and check it</h4><p>A successful save doesn&#39;t prove that the right pages made it into the file.</p><p>The script reopens the staged PDF, checks its page count, and compares each page&#39;s extracted text with the requested source page. For this selection, output page three must match source page nine.</p><p>The text comes from this helper:</p><pre>def page_text(document: apdf.Document, page_number: int) -&gt; str:<br>    absorber = apdf.text.TextAbsorber()<br>    absorber.visit(document.pages[page_number])<br>    return absorber.text</pre><p>These checks catch missing pages and text mismatches. They don&#39;t establish visual fidelity: scanned pages may return empty text, and forms, annotations, bookmarks, signatures, or links to omitted pages need separate review. The script doesn&#39;t repair those features.</p><h3>Keep the page history beside the PDF</h3><p>Each successful run creates a new folder containing `evidence-packet.pdf` and `manifest.json`.</p><p>The manifest records the requested selection and this mapping:</p><pre>Output page 1 -&gt; source page 2<br>Output page 2 -&gt; source page 5<br>Output page 3 -&gt; source page 9<br>Output page 4 -&gt; source page 10<br>Output page 5 -&gt; source page 11</pre><p>The script also saves the source path, page count, creation time, library version, and SHA-256 hashes for both PDFs. These details make it easier to identify the original files, even if they get renamed later.</p><p>After extracting the source, the script re-hashes it. If any bytes change during the process, it stops and doesn&#39;t publish the result.</p><p>The script prepares both files in a temporary directory. Once it verifies everything, it renames the results directory to a unique final folder. Previous packets remain available, and if copying or verification fails, the packet is not finalized. Keep in mind that directory renaming may not be atomic on all filesystems.</p><p>Full script: <a href="https://pastebin.com/JZf4iZrQ">https://pastebin.com/JZf4iZrQ</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3bd32eca234" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/extract-just-the-pdf-pages-you-need-with-python-e3bd32eca234">Extract Just the PDF Pages You Need with Python</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Online Password Generator for Every “Create a Password” Moment]]></title>
            <link>https://medium.com/@pdf-python/an-online-password-generator-for-every-create-a-password-moment-b0c6c7642f0a?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0c6c7642f0a</guid>
            <category><![CDATA[web-tools]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[online-security]]></category>
            <category><![CDATA[password-generator]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 12:24:15 GMT</pubDate>
            <atom:updated>2026-10-27T12:24:15.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53f4yAKem24-RlIXlNJxlA.png" /></figure><p>We’ve all been there — using a familiar password, tweaking the last digit, and hoping the website accepts it.</p><p>Then you get a message about a missing uppercase letter or number, or a symbol the site refuses even though it asked for one.</p><p>At Aspose, we usually focus on document tools, but today we want to introduce something a bit different from our app collection: our <a href="https://products.aspose.app/pdf/password-generator">online Password Generator</a>.</p><p>You pick the length, choose which characters to include, and generate a password. A couple of less obvious options are worth a look, especially if you’ve ever had to read a password off another screen.</p><h3>Match the site’s rules</h3><p>If you’re making a password for an account, you probably have the site’s requirements handy. Our generator lets you include or leave out lowercase letters, uppercase letters, numbers, and symbols, so you can match those rules.</p><p>If you’re unsure about length, choose at least 16 characters when the service allows it. Use a different password for each account.</p><p>After you’ve chosen your settings, click <strong>Generate Password</strong> and copy the result. You can make another one with the same settings whenever you need. You don’t have to think of a word first or figure out where to add numbers.</p><h3>Is that a zero or the letter O?</h3><p>A password can be easy to copy and surprisingly annoying to type. You notice it when you’re on your laptop and then type the same string on your phone, checking each character as you go.</p><p>The <strong>Don’t use Similar Characters</strong> option lets you exclude lookalikes. The interface lists examples including “i,” “l,” “1,” “L,” “o,” “0,” and “O.” If you’ll be typing the password by hand, it’s worth turning on.</p><p>There’s also <strong>Don’t use Ambiguous Characters</strong>. The examples shown beside it include braces, brackets, parentheses, slashes, and quotation marks. Check those examples against the rules of the service you’re using before generating your password.</p><p>It’s easy to skip these options when you’re just copying and pasting. But they become helpful the first time you have to enter a password with a remote control.</p><h3>Why is this tool part of the PDF apps collection?</h3><p>That’s a fair question, considering the website address.</p><p>We list the generator with our PDF tools, but it serves a different purpose. It creates the password text. If you want to protect a PDF with that password, you can apply it using our <a href="https://products.aspose.app/pdf/lock">Protect PDF tool</a>.</p><p>For accounts, it works the same way: copy the generated password into the service where you’re signing up or updating your login, then save your changes there.</p><p>So it’s simply another tool in the same set, there whenever you need a password for a document or an account.</p><h3>Give it a try</h3><p>Open the <a href="https://products.aspose.app/pdf/password-generator">Aspose Password Generator</a>, pick a length, select the characters you want, and generate your password. Before you leave, save it in your password manager. Your password is generated locally in your browser and is never sent to our servers or stored by us.</p><p>We’d also love to hear about any tricky situations you’ve faced. Have you come across a password rule that didn’t make sense, or a character you kept confusing? Leave a comment below on Medium — specific examples help us understand what needs attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0c6c7642f0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Split Large PDF Files with Python]]></title>
            <link>https://medium.com/asposepdf/how-to-split-large-pdf-files-with-python-29c5ba664515?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/29c5ba664515</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 13:36:47 GMT</pubDate>
            <atom:updated>2026-10-09T13:36:47.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AiTQJjT3Adaxs8WDTqpOeQ.png" /></figure><p><em>Extract individual pages, separate report sections, and divide long documents into manageable files.</em></p><p>A 120-page report rarely has one audience. Finance needs the tables near the end. Operations needs the middle section. Someone reviewing the summary would rather receive six pages than the entire document.</p><p>We can export those sections manually, but the page selection becomes another task to repeat whenever a new report arrives.</p><p>For our Python PDF project, we use Aspose.PDF to handle documents and Python’s standard library to manage files. The existing processing and merging scripts already provide useful pieces: opening PDFs, checking inputs, loading a license, and saving output. We’ll reuse those patterns and adapt the page-copying code to split a document.</p><p>There are three useful ways to do this:</p><ul><li>One page per file — Each page is a separate item, such as a scanned form</li><li>Custom page ranges — Readers need specific sections</li><li>A fixed number of pages per file — A long document needs predictable chunks</li></ul><p>We’ll use a 12-page report.pdf for the examples. The same page-selection logic applies to longer documents.</p><h4>Set up the project</h4><p>Our project uses Python 3.11 or later. Install its PDF dependency:</p><pre>python -m pip install aspose-pdf</pre><p>Keep the source document separate from the generated files:</p><pre>pdf-splitter/<br>├── input/<br>│   └── report.pdf<br>└── split_pdf.py</pre><p>The complete script below creates a new output directory for each run.</p><p>Aspose.PDF is a commercial library. Its evaluation mode adds a watermark; use a valid license when checking the final output. The vendor also offers a temporary license for testing. See the <a href="https://docs.aspose.com/pdf/python-net/licensing/">licensing documentation</a>.</p><p>Our existing project loads a license like this:</p><pre>import aspose.pdf as apdf<br><br>pdf_license = apdf.License()<br>pdf_license.set_license(str(license_path))</pre><p>Here, license_path points to your license file. Load it before opening or creating documents.</p><h4>Start with the page-copying operation</h4><p>The merging script creates a destination document and adds pages from a source:</p><pre>destination = apdf.Document()<br>destination.pages.add(source.pages)</pre><p>Splitting uses the same idea, except we select the pages that belong in each output.</p><p>For example, to extract page 3:</p><pre>import aspose.pdf as apdf<br><br>source = apdf.Document(&quot;input/report.pdf&quot;)<br>destination = apdf.Document()<br>destination.pages.add(source.pages[3])<br>destination.save(&quot;report-page-003.pdf&quot;)</pre><p>Aspose.PDF uses <strong>one-based page numbering</strong>: source.pages[1] is the first page. Its <a href="https://docs.aspose.com/pdf/python-net/extract-pages/">page extraction documentation</a> shows this same approach.</p><p>That detail matters when we introduce Python’srange(), whose upper boundary is excluded.</p><p>To copy pages 3 through 8, including both:</p><pre>for page_number in range(3, 9):<br>    destination.pages.add(source.pages[page_number])</pre><p>We’ll use inclusive start and end values everywhere else in the article, then add 1 when building the loop.</p><h4>Decide how to group the pages</h4><p>Before writing anything, we need a list of page groups. Each group contains a start page and an end page.</p><p>For individual pages, the groups are simple:</p><pre>groups = [<br>    (page_number, page_number)<br>    for page_number in range(1, page_count + 1)<br>]</pre><p>A 12-page document produces twelve groups: (1, 1), (2, 2), and so on.</p><p>For report sections, we can define the boundaries ourselves:</p><pre>groups = [<br>    (1, 2),   # Summary<br>    (3, 8),   # Main report<br>    (9, 12),  # Appendix<br>]</pre><p>These ranges cover the entire example document without overlaps. If we only need the main report, [(3, 8)] is enough.</p><p>Hard-coded ranges need maintenance. If next month’s summary grows by two pages, the script won’t detect that change. It will still copy exactly the pages we requested.</p><p>For fixed-size chunks, calculate the boundaries:</p><pre>pages_per_file = 5<br><br>groups = [<br>    (start, min(start + pages_per_file - 1, page_count))<br>    for start in range(1, page_count + 1, pages_per_file)<br>]</pre><p>For twelve pages, this produces:</p><pre>1–5<br>6–10<br>11–12</pre><p>The min() keeps the final range inside the document. Without it, the last chunk would try to include pages that don’t exist.</p><p>A chunk size larger than the document produces one output containing all its pages. A chunk size of zero or less should raise an error before processing starts.</p><h4>Check the source before creating outputs</h4><p>Our batch-processing script includes this quick header check:</p><pre>with input_file.open(&quot;rb&quot;) as source:<br>    if b&quot;%PDF-&quot; not in source.read(1024):<br>        raise ValueError(&quot;Invalid PDF: missing PDF header&quot;)</pre><p>It catches obvious mistakes, such as a text file renamed to .pdf. It doesn’t establish that the document is structurally valid. Opening the file with the PDF library is still necessary.</p><p>We also carry over the project’s input-size limit:</p><pre>MAX_PDF_BYTES = 1_000_000_000</pre><p>This is a limit chosen by the application, not a statement about the library’s maximum supported file size. Adjust it to suit the machine and documents you process.</p><p>For page ranges, the rule is:</p><pre>1 &lt;= start &lt;= end &lt;= page_count</pre><p>Validate every range before saving the first output. Discovering an invalid final range after creating nine files leaves us with an incomplete job to clean up.</p><h4>A complete splitter</h4><p>Save the following as split_pdf.py. It combines the project’s input checks and document-handling patterns with the grouping logic above.</p><p>The default configuration splits report.pdf into groups of five pages. Change MODE to &quot;pages&quot; or &quot;ranges&quot; for the other options.</p><pre>import sys<br>from pathlib import Path<br>from tempfile import TemporaryDirectory<br><br>import aspose.pdf as apdf<br><br>BASE = Path(__file__).resolve().parent<br>INPUT_FILE = BASE / &quot;input&quot; / &quot;report.pdf&quot;<br>OUTPUT_ROOT = BASE / &quot;output&quot;<br>LICENSE_PATH = None  # Set to Path(&quot;your-license.lic&quot;) if available.<br>MODE = &quot;chunks&quot;  # &quot;pages&quot;, &quot;ranges&quot;, or &quot;chunks&quot;<br>PAGES_PER_FILE = 5<br>CUSTOM_RANGES = [(1, 2), (3, 8), (9, 12)]<br>MAX_PDF_BYTES = 1_000_000_000<br><br>def build_groups(page_count):<br>    if MODE == &quot;pages&quot;:<br>        groups = [<br>            (page, page)<br>            for page in range(1, page_count + 1)<br>        ]<br>    elif MODE == &quot;ranges&quot;:<br>        groups = list(CUSTOM_RANGES)<br>    elif MODE == &quot;chunks&quot;:<br>        if PAGES_PER_FILE &lt;= 0:<br>            raise ValueError(&quot;PAGES_PER_FILE must be positive&quot;)<br>        groups = [<br>            (<br>                start,<br>                min(start + PAGES_PER_FILE - 1, page_count),<br>            )<br>            for start in range(<br>                1, page_count + 1, PAGES_PER_FILE<br>            )<br>        ]<br>    else:<br>        raise ValueError(f&quot;Unknown mode: {MODE}&quot;)<br>    if not groups:<br>        raise ValueError(&quot;No page ranges were selected&quot;)<br>    for start, end in groups:<br>        if not 1 &lt;= start &lt;= end &lt;= page_count:<br>            raise ValueError(<br>                f&quot;Invalid range {start}-{end}; &quot;<br>                f&quot;document contains {page_count} pages&quot;<br>            )<br>    return groups<br><br>def write_range(source, start, end, output_file):<br>    destination = apdf.Document()<br>    try:<br>        for page_number in range(start, end + 1):<br>            destination.pages.add(<br>                source.pages[page_number]<br>            )<br>        destination.save(str(output_file))<br>    finally:<br>        del destination<br><br>def verify_output(output_file, expected_pages):<br>    document = apdf.Document(str(output_file))<br>    try:<br>        actual_pages = len(document.pages)<br>        if actual_pages != expected_pages:<br>            raise RuntimeError(<br>                f&quot;{output_file.name}: expected &quot;<br>                f&quot;{expected_pages} pages, got {actual_pages}&quot;<br>            )<br>    finally:<br>        del document<br><br>def main():<br>    if not INPUT_FILE.is_file():<br>        raise FileNotFoundError(INPUT_FILE)<br>    if INPUT_FILE.stat().st_size &gt; MAX_PDF_BYTES:<br>        raise ValueError(&quot;Input exceeds the configured size limit&quot;)<br>    with INPUT_FILE.open(&quot;rb&quot;) as stream:<br>        if b&quot;%PDF-&quot; not in stream.read(1024):<br>            raise ValueError(&quot;Invalid PDF: missing PDF header&quot;)<br>    if LICENSE_PATH is not None:<br>        pdf_license = apdf.License()<br>        pdf_license.set_license(str(LICENSE_PATH))<br>    source = apdf.Document(str(INPUT_FILE))<br>    try:<br>        if source.is_encrypted:<br>            raise ValueError(<br>                &quot;This example does not process encrypted PDFs&quot;<br>            )<br>        page_count = len(source.pages)<br>        if page_count == 0:<br>            raise ValueError(&quot;Input contains no pages&quot;)<br>        groups = build_groups(page_count)<br>        print(f&quot;Opened {INPUT_FILE.name}: {page_count} pages&quot;)<br>        OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)<br>        with TemporaryDirectory(<br>            prefix=&quot;.split-&quot;, dir=OUTPUT_ROOT<br>        ) as work:<br>            staging = Path(work) / &quot;files&quot;<br>            staging.mkdir()<br>            for index, (start, end) in enumerate(groups, 1):<br>                name = (<br>                    f&quot;{INPUT_FILE.stem}-part-{index:03d}&quot;<br>                    f&quot;-pages-{start:03d}-{end:03d}.pdf&quot;<br>                )<br>                output_file = staging / name<br>                print(f&quot;Creating {name}&quot;)<br>                write_range(source, start, end, output_file)<br>                verify_output(output_file, end - start + 1)<br>            selected_pages = sum(<br>                end - start + 1 for start, end in groups<br>            )<br>            print(<br>                f&quot;Verified {len(groups)} output files: &quot;<br>                f&quot;{selected_pages} selected pages&quot;<br>            )<br>            # Reserve a fresh directory for this completed run.<br>            run_folder = Path(work).name.removeprefix(&quot;.split-&quot;)<br>            destination = OUTPUT_ROOT / f&quot;split-{run_folder}&quot;<br>            destination.mkdir(exist_ok=False)<br>            try:<br>                staging.rename(destination / &quot;files&quot;)<br>            except Exception:<br>                destination.rmdir()<br>                raise<br>            print(f&quot;Saved to {destination / &#39;files&#39;}&quot;)<br>    finally:<br>        del source<br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        main()<br>    except Exception as exc:<br>        print(f&quot;Split did not complete: {exc}&quot;, file=sys.stderr)<br>        sys.exit(1)</pre><p>Run it with:</p><pre>python split_pdf.py</pre><p>For the 12-page example in chunk mode, the output will look like:</p><pre>Opened report.pdf: 12 pages<br>Creating report-part-001-pages-001-005.pdf<br>Creating report-part-002-pages-006-010.pdf<br>Creating report-part-003-pages-011-012.pdf<br>Verified 3 output files: 12 selected pages<br>Saved to .../output/split-.../files</pre><p>The directory suffix changes on each run. That lets us rerun the script without replacing earlier results.</p><h4>Why save to a temporary directory first?</h4><p>A split creates several files. If writing the third file fails, the first two may be perfectly readable, but the job is still incomplete.</p><p>The script creates and checks all outputs in a temporary directory. Only after verification does it move the containing folder into the run directory. If processing fails earlier, the temporary directory is cleaned up.</p><p>Keeping the staging area inside OUTPUT_ROOT also keeps the move on the same filesystem.</p><p>This is useful for recurring work: a downstream process can wait for the run’s files directory instead of trying to read PDFs while they are still being written.</p><h4>Verify more than the file count</h4><p>For our example, the output page counts should be:</p><pre>5 + 5 + 2 = 12</pre><p>The script reopens each generated PDF and compares its page count with the requested range.</p><p>That catches missing pages and unreadable output. It doesn’t prove that every page contains the expected content. Before relying on a new configuration, open the results and inspect the first and last pages of each part.</p><p>For custom ranges, the total is the number of selected pages. It only equals the source page count when the ranges cover the whole document without duplication.</p><p>Overlaps may be intentional. For example, two teams might both need the introductory pages. The script permits that; it doesn’t assume every job is a complete, nonoverlapping split.</p><h4>Large files need a little more care</h4><p>Splitting by page count doesn’t guarantee a particular file size.</p><p>Five scanned pages may be much larger than fifty pages of text. Separate outputs may also contain copies of resources that were shared within the original document.</p><p>If an upload service has a 10 MB limit, check each generated file’s size after saving. A five-page chunk is only a starting point. An oversized result may need another split, and a single oversized page may require image optimization.</p><p>The script also opens the original document as a whole. Creating one output at a time avoids keeping every destination document alive, but it doesn’t turn source loading into a streaming operation. Test representative files before scheduling large jobs, and measure memory use as well as elapsed time.</p><p>Finally, check any document features your readers depend on. Page extraction alone doesn’t establish that bookmarks, links to other sections, interactive forms, or digital signatures will behave as they did in the source.</p><h4>Make the page boundaries part of the job</h4><p>The actual copying loop is short. The decisions around it determine whether the result is useful: which pages belong together, whether the ranges still match the report, where outputs are saved, and how completion is checked.</p><p>For a stable monthly report, explicit ranges can be enough. For a document whose only requirement is smaller sections, fixed-size chunks are easier to maintain.</p><p>We’d start with the simplest grouping that matches the task, check the resulting PDFs, and keep the original. Once those boundaries are right, the same script can handle the next report without another round of manual exports.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29c5ba664515" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/how-to-split-large-pdf-files-with-python-29c5ba664515">How to Split Large PDF Files with Python</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Merge Multiple PDFs Automatically with Python]]></title>
            <link>https://medium.com/asposepdf/how-to-merge-multiple-pdfs-automatically-with-python-c190230c572d?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/c190230c572d</guid>
            <category><![CDATA[merge-pdf-files]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 09:29:22 GMT</pubDate>
            <atom:updated>2026-10-06T09:29:22.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7uD0d4MAUG1YafpRp5rRXw.png" /></figure><p>A practical way to combine reports, charts, and cover pages into a single PDF, while keeping the files in the right order and adding bookmarks for easier navigation.</p><p>Reports often come in pieces. The cover might be exported from Word, the main report generated by another application, and the charts saved as separate PDF files. Before sending the final version, you need to put all these files together in the correct order.</p><p>Doing this manually isn’t a big deal if it happens once. But if you prepare the same type of report every week or month, opening and merging the files quickly becomes unnecessary routine work.</p><p>Python can handle that part for us.</p><p>In this article, we’ll show how to use Aspose.PDF for Python via .NET to automatically merge a folder of PDF files. We’ll start with a simple merge and then add file ordering, bookmarks, page-size checks, and logging.</p><h4>A real-world example</h4><p>For this example, we’re working with a report called <em>Cities in the World 2026</em>. It isn’t stored as a single document. The folder contains a cover, a backup copy of the cover, a 35-page report, six charts for different continents, and two additional city charts.</p><p>This is a common situation with reports assembled from several sources. Not every PDF in the folder needs to be included, and sorting files alphabetically doesn’t always put them in the right order.</p><p>The pages also have different sizes and orientations. The cover is A4, while the report and charts use Letter-sized pages, including landscape pages.</p><p>There are 11 PDFs in the folder. If we merge all of them, we get a 45-page document with two covers. Since we only need the main cover, we exclude the backup.</p><p>That leaves us with 10 PDFs and a final document of 44 pages.</p><p>We want the main cover first, followed by the 35-page report, the continental charts, and finally the city charts.</p><p>With the order decided, we can put these rules into the Python script instead of arranging the files manually each time.</p><h4>1. Set up the project</h4><p>The sample project uses Python 3.11 or later. Install the two packages used by the script:</p><pre>python -m pip install aspose-pdf python-dotenv</pre><p>Aspose.PDF is a commercial library, so check its current installation and licensing requirements before running a larger document. Evaluation mode has restrictions, including watermarks and page-processing limits. For this 35-page sample report, use an appropriate license or <a href="https://purchase.aspose.com/temporary-license">temporary evaluation license</a>.</p><p>A simple project structure is enough:</p><pre>pdf-project/<br>├── merge_pdfs.py<br>├── .env<br>└── data/<br> ├── input/<br> │ ├── Cover.pdf<br> │ ├── Report.pdf<br> │ └── …other PDFs<br> ├── output/<br> └── logs/</pre><p>Keep environment-specific paths in .env instead of hard-coding them in the script:</p><pre>BASE_FOLDER=./data<br>LICENSE_PATH=C:/licenses/Aspose.PDF.lic</pre><p>Replace the license path with your own. The script resolves relative paths from the script directory, so it behaves consistently even if you launch it from another working directory.</p><h4>2. Start with the merge itself</h4><p>At its core, merging PDFs with Aspose.PDF is straightforward. Open a source document, append its pages to the destination, and save the result:</p><pre>src_document = apdf.Document(str(input_file))<br>dst_document = apdf.Document(str(output_file))<br>dst_document.pages.add(src_document.pages)<br>dst_document.save(str(output_file))</pre><p>You could repeat those four lines for every file. But saving after each addition means repeatedly opening and writing a destination that keeps getting larger.</p><p>For a batch workflow, I prefer a simpler model: create a fresh destination in memory, append every source, and save once at the end. It also makes reruns predictable — the output is rebuilt from the files that exist now instead of accidentally appending the same pages to yesterday’s result.</p><h4>3. Don’t trust alphabetical order</h4><p>Alphabetical sorting is predictable, but it often doesn’t arrange things the way people want in a final report. For instance, a file starting with “Cities” might show up before “Cover”.</p><p>The original example fixes this by using section priorities. When I looked at it, I saw a small naming issue: the rule was set to “Top-5,” but the sample files were actually named “Top 5 — Africa.pdf,” “Top 5 — Asia.pdf,” and so on. This small difference is enough to put those files in the wrong category.</p><p>Using a more flexible sorting key could handle both ways of naming and then use the filename to sort anything that’s still out of order.</p><pre>def sort_key(path):<br>    groups = ((&quot;cover&quot;,), (&quot;report&quot;,), (&quot;top 5&quot;, &quot;top-5&quot;), (&quot;cities&quot;,))<br>    name = path.stem.casefold()<br>    priority = next(<br>        (i for i, prefixes in enumerate(groups)<br>         if any(name.startswith(prefix) for prefix in prefixes)),<br>        len(groups),<br>    )<br>    return priority, path.name.casefold()</pre><p>Now the broad section order is stable, and files inside each section are sorted by name. I also exclude Cover backup.pdf explicitly. A folder scan can tell that it is a valid PDF; it cannot tell whether a human intended to publish it.</p><p>If the exact order is business-critical, a manifest with the required filenames is even better than prefix rules.</p><h4>4. Add bookmarks after adding the pages</h4><p>Once the report reaches 44 pages, bookmarks stop being a nice extra. They make the merged document much easier to navigate.</p><p>There is one timing detail that matters: create the bookmark only after the source pages have been appended. Before that, the destination page you want to link to does not exist yet.</p><pre>bookmark.action = apdf.annotations.GoToAction(<br>destination.pages[first_page]<br>)<br>destination.outlines.append(bookmark)</pre><p>Aspose.PDF uses one-based page numbers here. So if the destination already contains 36 pages, the next document begins on page 37. Capturing first_page before the append gives us the correct target after the pages are added.</p><h4>5. Mixed page sizes are not necessarily a problem</h4><p>The sample files are not all the same size. The cover is roughly A4 (595 × 842 PDF points), the main report uses portrait Letter pages (612 × 792), and the charts use landscape Letter pages (792 × 612). A merged PDF can contain all of them without forcing every page into one format.</p><p>For this workflow, I only want to detect the difference and log a warning. I do not want to resize content automatically, because resizing introduces a different set of decisions about scale, margins, and cropping.</p><p>Sorting width and height first makes the A4 check work for both portrait and landscape pages:</p><pre>width, height = sorted((page.media_box.width, page.media_box.height))<br>is_a4 = abs(width - 595.28) &lt;= 1.0 and abs(height - 841.89) &lt;= 1.0</pre><p>The one-point tolerance allows for small rounding differences from PDF exporters. This is still only a MediaBox check; it does not fully describe how a rotated or cropped page will appear in a viewer.</p><h4>6. Put it all together</h4><p>Here is the complete merge_pdfs.py script. It sorts the input files, merges them, adds bookmarks, checks page sizes, and writes the results to a log.</p><p>The script doesn’t save directly to merged_pages.pdf. It first creates merged_pages.pending.pdf. Only after all files have been processed is that file renamed to merged_pages.pdf.</p><p>There’s a practical reason for doing it this way. If the merge stops halfway through, it won’t overwrite the previous PDF with an incomplete one.</p><p>This also means that seeing merged_pages.pdf in the output folder doesn’t necessarily mean the latest run worked. It may simply be the file from the previous run. I check the completion message or the script’s exit status to make sure the new PDF was created successfully.</p><pre>import csv<br>import logging<br>import sys<br>import time<br>from pathlib import Path<br><br>import aspose.pdf as apdf<br>from dotenv import dotenv_values<br><br>MAX_PDF_BYTES = 1_000_000_000<br>EXCLUDED_NAMES = {&quot;cover backup.pdf&quot;}<br><br>def sort_key(path):<br>    groups = ((&quot;cover&quot;,), (&quot;report&quot;,), (&quot;top 5&quot;, &quot;top-5&quot;), (&quot;cities&quot;,))<br>    name = path.stem.casefold()<br>    priority = next(<br>        (i for i, prefixes in enumerate(groups)<br>         if any(name.startswith(prefix) for prefix in prefixes)),<br>        len(groups),<br>    )<br>    return priority, path.name.casefold()<br><br>def configured_path(config, key, script_folder):<br>    value = config.get(key)<br>    if not value or not value.strip():<br>        raise ValueError(f&quot;{key} must be set in .env&quot;)<br>    path = Path(value).expanduser()<br>    return path if path.is_absolute() else script_folder / path<br><br>def main():<br>    script_folder = Path(__file__).resolve().parent<br>    config = dotenv_values(script_folder / &quot;.env&quot;)<br>    base = configured_path(config, &quot;BASE_FOLDER&quot;, script_folder)<br>    license_path = configured_path(config, &quot;LICENSE_PATH&quot;, script_folder)<br>    input_folder = base / &quot;input&quot;<br>    if not input_folder.is_dir():<br>        raise NotADirectoryError(input_folder)<br>    if not license_path.is_file():<br>        raise FileNotFoundError(license_path)<br><br>    logs = base / &quot;logs&quot;<br>    logs.mkdir(parents=True, exist_ok=True)<br>    logging.basicConfig(<br>        filename=str(logs / &quot;processing.log&quot;),<br>        encoding=&quot;utf-8&quot;,<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s %(levelname)s %(message)s&quot;,<br>    )<br>    inputs = sorted(<br>        (p for p in input_folder.iterdir()<br>         if p.is_file() and p.suffix.lower() == &quot;.pdf&quot;<br>         and p.name.casefold() not in EXCLUDED_NAMES),<br>        key=sort_key,<br>    )<br>    report_path = logs / &quot;processing-report.csv&quot;<br>    with report_path.open(&quot;w&quot;, newline=&quot;&quot;, encoding=&quot;utf-8&quot;) as report:<br>        writer = csv.writer(report)<br>        writer.writerow([&quot;input_file&quot;, &quot;status&quot;, &quot;processing_seconds&quot;, &quot;error&quot;])<br>        if not inputs:<br>            print(&quot;No PDF files found; no output written.&quot;)<br>            return 0<br><br>        pdf_license = apdf.License()<br>        pdf_license.set_license(str(license_path))<br>        destination = apdf.Document()<br>        sources: list[apdf.Document] = []<br>        temporary = base / &quot;output&quot; / &quot;merged_pages.pending.pdf&quot;<br>        output = base / &quot;output&quot; / &quot;merged_pages.pdf&quot;<br>        try:<br>            for input_file in inputs:<br>                started = time.perf_counter()<br>                try:<br>                    if input_file.stat().st_size &gt; MAX_PDF_BYTES:<br>                        raise ValueError(&quot;Input exceeds the 1 GB size limit&quot;)<br>                    source = apdf.Document(str(input_file))<br>                    sources.append(source)<br>                    if len(source.pages) == 0:<br>                        raise ValueError(&quot;Input has no PDF pages&quot;)<br>                    for page in source.pages:<br>                        width, height = sorted(<br>                            (page.media_box.width, page.media_box.height)<br>                        )<br>                        if abs(width - 595.28) &gt; 1 or abs(height - 841.89) &gt; 1:<br>                            logging.warning(<br>                                &quot;%s: page %s is not A4&quot;, input_file.name, page.number<br>                            )<br>                    first_page = len(destination.pages) + 1<br>                    destination.pages.add(source.pages)<br>                    bookmark = apdf.OutlineItemCollection(destination.outlines)<br>                    bookmark.title = input_file.stem<br>                    bookmark.action = apdf.annotations.GoToAction(<br>                        destination.pages[first_page]<br>                    )<br>                    destination.outlines.append(bookmark)<br>                except Exception as exc:<br>                    writer.writerow([<br>                        input_file.name, &quot;failed&quot;,<br>                        f&quot;{time.perf_counter() - started:.3f}&quot;, str(exc),<br>                    ])<br>                    report.flush()<br>                    raise<br>                writer.writerow([<br>                    input_file.name, &quot;appended&quot;,<br>                    f&quot;{time.perf_counter() - started:.3f}&quot;, &quot;&quot;,<br>                ])<br>                report.flush()<br><br>            output.parent.mkdir(parents=True, exist_ok=True)<br>            page_count = len(destination.pages)<br>            destination.save(str(temporary))<br>            temporary.replace(output)<br>            logging.info(&quot;Saved %s: %d pages&quot;, output, page_count)<br>            print(f&quot;Merged {len(inputs)} PDFs into {output} ({page_count} pages)&quot;)<br>            return 0<br>        finally:<br>            temporary.unlink(missing_ok=True)<br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        sys.exit(main())<br>    except Exception:<br>        logging.exception(&quot;Merge did not complete&quot;)<br>        print(&quot;Merge did not complete; check the error and processing log.&quot;,<br>              file=sys.stderr)<br>        sys.exit(1)</pre><p>The source documents stay open until the merge is finished and are closed afterward. That works well for a batch of this size, although it doesn’t put a fixed limit on memory use. The 1 GB check applies to each input PDF separately, not to the total amount of memory used during the merge.</p><p>Now we can run the script from the project folder:</p><pre>python merge_pdfs.py</pre><p>With our sample files, the result should be a 44-page PDF with 10 bookmarks. Cover backup.pdf is excluded, so it won’t appear in the final document.</p><p>After the first run, we open the PDF and do a quick check. The cover should come first, followed by the main report. We also try several bookmarks to make sure they open the right pages. Since our source PDFs have different sizes and orientations, we check both portrait and landscape pages.</p><p>If the merge fails, the logs are usually the first place to look. logs/processing-report.csv shows the status of each input file, its processing time, and any errors. More detailed information, including page-size warnings, is written to logs/processing.log.</p><p>This is particularly handy with a large folder of PDFs. Instead of going through the files one by one, we can see which one caused the problem.</p><h4>Scheduling the script</h4><p>While developing and testing the script, we run it manually. Once the result is consistent, the same command can be scheduled to run automatically.</p><p>On Windows, we can use Task Scheduler. On Linux or macOS, cron does the job. For scheduled runs, we use full paths to Python and merge_pdfs.py, so the command doesn’t depend on the directory it starts from.</p><p>We also need to think about timing. The merge shouldn’t start while another application is still exporting the source PDFs. Two copies of the script shouldn’t write to the same output file at the same time either.</p><p>Scanning the whole input folder works well when there are only a few PDFs. With a larger set, we prefer keeping a list of the files that belong in the report. This reduces the chance of picking up an old export, a temporary file, or another PDF that happens to be in the same folder.</p><p>If previous reports need to be kept, we can save the finished PDFs with a date or version in the filename.</p><p>Forms, digital signatures, and internal links deserve a separate check. Merging the pages successfully doesn’t always mean that these features will behave exactly as they did in the original PDFs.</p><p>For our report, rebuilding the final PDF is now straightforward. We replace the source files in the input folder and run the script again. The script puts them in the expected order, creates the bookmarks, and saves the merged PDF to the output folder.</p><p>No need to rearrange the same pages manually every time or wonder whether an old chart slipped into the final report.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c190230c572d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/how-to-merge-multiple-pdfs-automatically-with-python-c190230c572d">How to Merge Multiple PDFs Automatically with Python</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Automate PDF Processing in Python: A Complete Workflow]]></title>
            <link>https://medium.com/asposepdf/how-to-automate-pdf-processing-in-python-a-complete-workflow-bf836771dbb6?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf836771dbb6</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 08:11:35 GMT</pubDate>
            <atom:updated>2026-09-23T08:23:15.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cr7vDSRy2YL1IKc5UgUOwQ.png" /></figure><p>Working with one or two PDF files is simple enough. But when the same operation has to be repeated for dozens or hundreds of documents, it makes sense to automate it.</p><p>For example, you may have a folder where new PDF files are added regularly. Each file needs to be checked, processed, and saved to another folder. Some PDFs may be corrupted or password-protected, and one problematic file should not stop the rest of the batch.</p><p>Here, we’ll use <strong>Aspose.PDF for Python via .NET</strong> to automate the entire PDF processing workflow.</p><p>The script will:</p><ul><li>find PDF files in an input folder;</li><li>check files before opening them;</li><li>skip PDFs that are too large or password-protected;</li><li>optimize valid documents;</li><li>save processed files to a separate output folder;</li><li>continue with the next PDF if one file cannot be processed;</li><li>log processing errors and other events;</li><li>write the results to a CSV report;</li><li>print a short summary when the job is finished.</li></ul><p>We’ll use PDF optimization as the processing step in this example, but the main focus is the batch workflow itself. Once the file handling, validation, logging, and error handling are in place, the optimize() step can be replaced with another operation, such as conversion, text extraction, watermarking, splitting, merging, or redaction.</p><h3>1. Setting Up the Environment</h3><p>Install Aspose.PDF for Python via .NET using pip:</p><pre>pip install aspose-pdf</pre><p>The official package provides PDF creation, reading, conversion, page and text manipulation, annotations, bookmarks, watermarks, attachments, forms, and other document-processing functionality.</p><p>Our example also uses python-dotenv to keep environment-specific paths outside the Python source code:</p><pre>pip install python-dotenv</pre><p>For this project, we will use the following directory structure:</p><pre>pdf-automation/<br>├── input/<br>│   ├── report-01.pdf<br>│   ├── report-02.pdf<br>│   └── report-03.pdf<br>├── output/<br>├── logs/<br>└── process_pdfs.py</pre><p>The input directory contains source documents. Processed documents are written to output, while logs and the CSV report are stored separately in logs.</p><p>We will also use a .env file:</p><pre>BASE_FOLDER=/path/to/pdf-automation<br>LICENSE_PATH=/path/to/Aspose.PDF.Python.lic</pre><p>Keeping configuration outside the script makes it easier to move the workflow between development, test, and production environments.</p><h3>2. Importing the Required Modules</h3><p>Most of the infrastructure around the PDF API uses Python’s standard library:</p><pre>import csv<br>import logging<br>import os<br>import pathlib<br>import sys<br>import tempfile<br>import time<br><br>import aspose.pdf as apdf<br>from dotenv import dotenv_values</pre><p>Each module has a specific role.</p><p>pathlib handles filesystem paths, logging records processing events, csv creates the final report, tempfile helps us publish only completely processed documents, and time measures processing duration.</p><p>Aspose.PDF performs the actual PDF operations.</p><p>We also define two constants:</p><pre>MAX_PDF_BYTES = 1_000_000_000  # 1 GB<br>REPORT_COLUMNS = (<br>    &quot;input_file&quot;,<br>    &quot;output_file&quot;,<br>    &quot;status&quot;,<br>    &quot;processing_seconds&quot;,<br>    &quot;error&quot;,<br>)</pre><p>The first prevents unexpectedly large documents from being loaded. The second defines a consistent structure for our processing report.</p><h3>3. Distinguishing Skipped Files from Failed Files</h3><p>Not every document that we do not process represents an application failure.</p><p>For example, we may intentionally skip a file because it is password-protected, exceeds our configured size limit, or already has a corresponding output file.</p><p>A custom exception makes this distinction explicit:</p><pre>class SkipPDF(Exception):<br>    &quot;&quot;&quot;The input cannot be processed under the batch&#39;s safety policy.&quot;&quot;&quot;</pre><p>This gives us three possible results for every document:</p><ul><li>success — the PDF was processed and saved;</li><li>skipped — the file was intentionally ignored;</li><li>failed — an unexpected processing error occurred.</li></ul><p>That distinction becomes particularly useful when processing hundreds or thousands of files.</p><h3>4. Finding PDF Files Automatically</h3><p>The workflow starts by discovering PDFs in the input directory.</p><pre>def find_pdf_files(input_folder: pathlib.Path) -&gt; list[pathlib.Path]:<br>    return sorted(<br>        path<br>        for path in input_folder.iterdir()<br>        if path.is_file() and path.suffix.lower() == &quot;.pdf&quot;<br>    )</pre><p>There are several useful details here.</p><p>First, path.is_file() prevents directories from entering the processing queue.</p><p>Second, converting the suffix to lowercase means that both .pdf and .PDF are accepted.</p><p>Finally, sorting the results makes the processing order predictable, which can make logs and troubleshooting easier to follow.</p><p>For this workflow we intentionally scan only one directory level. If recursive discovery is required, Path.rglob(&quot;*.pdf&quot;) can be used instead.</p><h3>5. Validating Files Before Loading Them</h3><p>A file ending in .pdf is not necessarily a valid PDF.</p><p>Before passing anything to the PDF library, the script performs several inexpensive checks.</p><h3>Prevent accidental overwrites</h3><pre>if os.path.lexists(output_file):<br>    raise SkipPDF(&quot;Output already exists; left unchanged&quot;)</pre><p>The batch never silently replaces an existing result.</p><p>This is particularly important when rerunning a job after partial completion.</p><h3>Reject unexpectedly large inputs</h3><pre>if input_file.stat().st_size &gt; MAX_PDF_BYTES:<br>    raise SkipPDF(&quot;Input exceeds the 1 GB size limit&quot;)</pre><p>The 1 GB value is a policy chosen for this example rather than a universal PDF limit. A production application should select a threshold appropriate for its infrastructure and workload.</p><h3>Check for a PDF header</h3><pre>with input_file.open(&quot;rb&quot;) as source:<br>    if b&quot;%PDF-&quot; not in source.read(1024):<br>        raise ValueError(&quot;Invalid PDF: missing PDF header&quot;)</pre><p>This lightweight check helps reject obviously invalid input before handing it to the document-processing layer.</p><p>It is not intended to replace full PDF parsing. The actual document is still validated when Aspose.PDF attempts to open it.</p><h3>6. Loading and Optimizing a PDF</h3><p>Now we can implement the actual PDF operation.</p><pre>def optimize(input_file: str, output_file: str) -&gt; None:<br>    try:<br>        document = apdf.Document(input_file)<br>    except RuntimeError as exc:<br>        if &quot;InvalidPasswordException&quot; in str(exc):<br>            raise SkipPDF(<br>                &quot;Password-protected PDF; no password supplied&quot;<br>            ) from exc<br><br>    if &quot;InvalidPdfFileFormatException&quot; in str(exc):<br>            raise ValueError(<br>                f&quot;Invalid or corrupted PDF: {exc}&quot;<br>            ) from exc<br>        raise<br>    try:<br>        if document.is_encrypted:<br>            raise SkipPDF(<br>                &quot;Encrypted PDF; password-protected files are skipped&quot;<br>            )<br>        document.optimize()<br>        document.save(output_file)<br>    finally:<br>        del document</pre><p>Document is the central object used to load and work with an existing PDF.</p><p>The script explicitly deals with two important input conditions.</p><p>If opening the file reports an invalid password, the document is skipped because this workflow does not accept passwords.</p><p>If the PDF format itself is invalid, the condition is treated as a processing error.</p><p>After successfully loading the document, we also inspect is_encrypted. Aspose.PDF exposes this property to indicate whether a document is encrypted.</p><p>For a valid document, the actual operation is intentionally simple:</p><pre>document.optimize()<br>document.save(output_file)</pre><p>The point of this article is not to explore every optimization option. Optimization is simply the transformation performed by our pipeline.</p><p>It could later be replaced by another operation without changing the surrounding batch-processing architecture.</p><h3>7. Publishing Only Complete Output Files</h3><p>A subtle problem appears when writing directly to the final output location.</p><p>Suppose processing starts creating:</p><pre>output/report.pdf</pre><p>and the operation fails halfway through.</p><p>The output directory could then contain a file that looks like a completed result even though processing never finished.</p><p>To avoid that situation, our workflow first writes the result to a temporary directory:</p><pre>with tempfile.TemporaryDirectory(<br>    prefix=&quot;.pdf-&quot;,<br>    dir=output_file.parent,<br>) as work:<br><br>temporary_output = pathlib.Path(work) / &quot;optimized.pdf&quot;<br>    optimize(str(input_file), str(temporary_output))<br>    os.link(temporary_output, output_file)</pre><p>Only after PDF processing finishes successfully do we publish the file under its final name.</p><p>Using a hard link also provides useful collision behavior: it cannot silently overwrite a destination that another process created after our initial existence check.</p><p>This is a small implementation detail, but it makes the workflow safer than simply saving directly over the final destination.</p><h3>8. Processing One File Without Stopping the Batch</h3><p>The next function brings validation, processing, timing, and error handling together.</p><pre>def process_file(<br>    input_file: pathlib.Path,<br>    output_file: pathlib.Path,<br>) -&gt; tuple[str, float, str]:<br><br>  started_at = time.perf_counter()<br>      logging.info(&quot;Processing %s&quot;, input_file.name)<br>      error = &quot;&quot;<br>      try:<br>          if os.path.lexists(output_file):<br>              raise SkipPDF(&quot;Output already exists; left unchanged&quot;)<br>          if input_file.stat().st_size &gt; MAX_PDF_BYTES:<br>              raise SkipPDF(&quot;Input exceeds the 1 GB size limit&quot;)<br>          with input_file.open(&quot;rb&quot;) as source:<br>              if b&quot;%PDF-&quot; not in source.read(1024):<br>                  raise ValueError(&quot;Invalid PDF: missing PDF header&quot;)<br>          with tempfile.TemporaryDirectory(<br>              prefix=&quot;.pdf-&quot;,<br>              dir=output_file.parent,<br>          ) as work:<br>              temporary_output = pathlib.Path(work) / &quot;optimized.pdf&quot;<br>              optimize(<br>                  str(input_file),<br>                  str(temporary_output),<br>              )<br>              os.link(temporary_output, output_file)<br>      except (SkipPDF, FileExistsError) as exc:<br>          status = &quot;skipped&quot;<br>          error = str(exc)<br>          logging.warning(<br>              &quot;Skipped %s: %s&quot;,<br>              input_file.name,<br>              error,<br>          )<br>      except PermissionError as exc:<br>          status = &quot;failed&quot;<br>          error = (<br>              &quot;Permission denied reading input &quot;<br>              f&quot;or writing output: {exc}&quot;<br>          )<br>          logging.error(<br>              &quot;Failed to process %s: %s&quot;,<br>              input_file.name,<br>              error,<br>          )<br>      except Exception as exc:<br>          status = &quot;failed&quot;<br>          error = str(exc)<br>          logging.exception(<br>              &quot;Failed to process %s&quot;,<br>              input_file.name,<br>          )<br>      else:<br>          status = &quot;success&quot;<br>          logging.info(<br>              &quot;Successfully processed %s&quot;,<br>              input_file.name,<br>          )<br>      return (<br>          status,<br>          time.perf_counter() - started_at,<br>          error,<br>      )</pre><p>The most important design decision here is that an error in one PDF does <strong>not</strong> terminate the entire job.</p><p>Imagine processing 500 documents and discovering that file number 73 is corrupted. There is usually little reason to prevent the remaining 427 documents from being attempted.</p><p>Instead, the function returns the status, processing time, and error message to the caller.</p><h3>9. Adding Application Logging</h3><p>Console messages are useful while developing a script, but automated workflows need persistent logs.</p><p>We configure Python logging like this:</p><pre>def configure_logging(logs_folder: pathlib.Path) -&gt; None:<br>    logs_folder.mkdir(parents=True, exist_ok=True)<br><br>    logging.basicConfig(<br>           filename=str(logs_folder / &quot;processing.log&quot;),<br>           encoding=&quot;utf-8&quot;,<br>           level=logging.INFO,<br>           format=&quot;%(asctime)s %(levelname)s %(message)s&quot;,<br>        )</pre><p>The resulting log can contain entries such as:</p><pre>2026-09-17 08:10:15 INFO Processing report-01.pdf<br>2026-09-17 08:10:16 INFO Successfully processed report-01.pdf<br>2026-09-17 08:10:16 INFO Processing protected.pdf<br>2026-09-17 08:10:16 WARNING Skipped protected.pdf: Password-protected PDF; no password supplied</pre><p>This becomes valuable when the script runs unattended — for example, from a scheduler, server process, or document-processing service.</p><h3>10. Processing the Entire Directory</h3><p>Once individual-file processing is isolated, batch processing becomes straightforward.</p><pre>def process_files(<br>    input_files: list[pathlib.Path],<br>    output_folder: pathlib.Path,<br>    report_path: pathlib.Path,<br>) -&gt; tuple[int, int, int]:<br><br>  if input_files:<br>        output_folder.mkdir(parents=True, exist_ok=True)<br>    successfully_processed = 0<br>    failed = 0<br>    skipped = 0<br>    logging.info(&quot;Files found: %d&quot;, len(input_files))<br>    with report_path.open(<br>        &quot;w&quot;,<br>        newline=&quot;&quot;,<br>        encoding=&quot;utf-8&quot;,<br>    ) as report_file:<br>        writer = csv.writer(report_file)<br>        writer.writerow(REPORT_COLUMNS)<br>        report_file.flush()<br>        for pdf_in_file in input_files:<br>            pdf_out_file = output_folder / pdf_in_file.name<br>            status, processing_seconds, error = process_file(<br>                pdf_in_file,<br>                pdf_out_file,<br>            )<br>            if status == &quot;success&quot;:<br>                successfully_processed += 1<br>            elif status == &quot;skipped&quot;:<br>                skipped += 1<br>            else:<br>                failed += 1<br>            writer.writerow(<br>                [<br>                    str(pdf_in_file),<br>                    str(pdf_out_file),<br>                    status,<br>                    f&quot;{processing_seconds:.3f}&quot;,<br>                    error,<br>                ]<br>            )<br>            report_file.flush()<br>    return successfully_processed, failed, skipped</pre><p>Notice that documents are processed one at a time.</p><p>We do not load every PDF into memory before starting the job. Each document enters the pipeline individually and is released after processing.</p><p>That is a useful pattern when the number or size of input documents is unpredictable.</p><h3>11. Creating a CSV Processing Report</h3><p>Application logs are designed primarily for diagnostics. A structured report answers a different question:</p><p><strong>What happened to each document?</strong></p><p>Our CSV contains five columns:</p><pre>input_file,output_file,status,processing_seconds,error</pre><p>A resulting report could look like this:</p><pre>input/report-01.pdf,output/report-01.pdf,success,0.842,<br>input/report-02.pdf,output/report-02.pdf,skipped,0.004,Output already exists; left unchanged<br>input/broken.pdf,output/broken.pdf,failed,0.015,Invalid PDF: missing PDF header</pre><p>This format can easily be opened in Excel, imported into a database, analyzed with Pandas, or consumed by another automation process.</p><p>Calling flush() after each record is deliberate. If the batch terminates unexpectedly, already completed results remain recorded instead of being left only in an unwritten buffer.</p><h3>12. Loading Configuration and Applying the License</h3><p>The main() function coordinates the entire workflow.</p><p>Configuration comes from .env:</p><pre>config_path = (<br>    pathlib.Path(__file__).resolve().parents / &quot;.env&quot;<br>)<br><br>  with config_path.open(encoding=&quot;utf-8&quot;) as config_file:<br>    config = dotenv_values(stream=config_file)</pre><p>The script validates both the base directory and the license file before starting document processing.</p><p>The license is applied once:</p><pre>pdf_license = apdf.License()<br>pdf_license.set_license(license_path)</pre><p>Aspose.PDF can also be evaluated without a license, but the evaluation version has restrictions, including an evaluation watermark and collection limitations. For a batch workflow intended to produce normal output documents, a valid or temporary license should therefore be configured.</p><p>Another small optimization is that the script applies the license only when there are actually PDFs to process.</p><h3>13. Displaying a Batch Summary</h3><p>After the last document has been attempted, the workflow calculates the total processing time and creates a human-readable summary:</p><pre>summary = (<br>    f&quot;Files found:            {len(pdf_in_files)}\n&quot;<br>    f&quot;Successfully processed: {successfully_processed}\n&quot;<br>    f&quot;Failed:                 {failed}\n&quot;<br>    f&quot;Skipped:                {skipped}\n&quot;<br>    f&quot;Total processing time: {total_seconds:.1f} seconds\n&quot;<br>    f&quot;Report: {report_path.relative_to(base_folder).as_posix()}&quot;<br>)</pre><p>A typical run might produce:</p><pre>Files found:            25<br>Successfully processed: 21<br>Failed:                  1<br>Skipped:                 3<br>Total processing time: 18.4 seconds<br>Report: logs/processing-report.csv</pre><p>These numbers are only an example. Actual processing time depends on the PDFs, hardware, storage, and operation being performed.</p><p>The script also returns a non-zero exit code when at least one document fails:</p><pre>return 1 if failed else 0</pre><p>That makes the workflow easier to integrate with shell scripts, CI jobs, schedulers, containers, and monitoring systems.</p><h3>14. Putting Everything Together</h3><p>The complete application follows a simple pipeline:</p><pre>Input folder<br>     │<br>     ▼<br>Discover PDF files<br>     │<br>     ▼<br>Validate input<br>     │<br>     ▼<br>Load PDF<br>     │<br>     ▼<br>Optimize document<br>     │<br>     ▼<br>Save temporary result<br>     │<br>     ▼<br>Publish completed PDF<br>     │<br>     ├──────────► processing.log<br>     │<br>     └──────────► processing-report.csv</pre><p>The important part is not optimization itself.</p><p>It is the separation of responsibilities.</p><p>File discovery knows nothing about PDF optimization. The optimization function knows nothing about CSV reports. Reporting does not need to understand how the PDF was transformed.</p><p>This makes individual parts of the workflow easier to replace.</p><h3>15. Turning the Pipeline into Other PDF Workflows</h3><p>Once the batch-processing infrastructure exists, optimize() becomes a replaceable processing stage.</p><p>For example, the same architecture could be adapted to:</p><ul><li>collect related documents and create combined reports.</li><li>break large documents into individual pages or predefined page ranges.</li><li>process folders of documents and send extracted text to search, analytics, or AI pipelines.</li><li>automatically mark incoming documents as DRAFT, CONFIDENTIAL, or with organization-specific information.</li><li>use the same discovery, validation, error handling, logging, and reporting layers while changing only the document transformation.</li><li>search documents for known patterns and create sanitized output copies while preserving the originals.</li></ul><p>This is why building a workflow is often more valuable than writing a script around a single API call.</p><h3>Wrapping Up</h3><p>PDF automation becomes more interesting when we stop thinking about individual API operations and start thinking about the complete lifecycle of a document.</p><p>A useful batch processor needs more than:</p><pre>document.optimize()<br>document.save(...)</pre><p>It needs to decide which files are safe to process, protect existing output, handle problematic documents, recover from individual failures, record what happened, and produce results that downstream systems can trust.</p><p>In this example, <strong>Aspose.PDF for Python via .NET</strong> handles the PDF processing itself, while Python’s standard library provides the surrounding automation infrastructure.</p><p>The result is a workflow that can serve as a foundation for much larger document-processing systems — and the actual PDF operation can change without requiring the entire pipeline to be rewritten.</p><p>Source code: <a href="https://pastebin.com/BxgQMMQ2">https://pastebin.com/BxgQMMQ2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf836771dbb6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/how-to-automate-pdf-processing-in-python-a-complete-workflow-bf836771dbb6">How to Automate PDF Processing in Python: A Complete Workflow</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use TextBuilder in Aspose.PDF for Python for Precise Text Placement]]></title>
            <link>https://medium.com/asposepdf/how-to-use-textbuilder-in-aspose-pdf-for-python-for-precise-text-placement-ba57dbdc3327?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba57dbdc3327</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[document-processing]]></category>
            <category><![CDATA[aspose]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 08:23:02 GMT</pubDate>
            <atom:updated>2026-09-14T08:23:02.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiupsD85r1vs8qZU2kKaGw.png" /></figure><p>When adding regular text to a PDF, page.paragraphs.add(...) is often enough. But sometimes the text needs to appear at an exact position on the page. A label, a caption, or text inside a fixed area is a good example.</p><p>For this type of work, Aspose.PDF for Python provides special tool (class) TextBuilder.</p><p>In the examples below, I use it in two ways: first, with individual TextFragment objects, and then with TextParagraph when there is more text and wrapping becomes important.</p><h3>2. Creating a TextBuilder</h3><p>TextBuilder works with a specific page, so we start by creating the document and page and then pass that page to the builder:</p><pre>document = ap.Document()<br>page = document.pages.add()<br><br>text_builder = ap.text.TextBuilder(page)</pre><p>From here, text can be added with append_text(). For paragraph content, there is append_paragraph().</p><h3>2. Placing Text at Exact Coordinates</h3><p>Let’s start with two simple text fragments:</p><pre><br>def text_builder_example_01(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text_builder = ap.text.TextBuilder(page)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.position = ap.text.Position(10, 800)<br>    text_builder.append_text(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Yet another text fragment&quot;)<br>    text_fragment.position = ap.text.Position(90, 700)<br>    text_builder.append_text(text_fragment)<br><br>    document.save(output_file_name)</pre><p>Both fragments use position, but their coordinates are different:</p><pre>ap.text.Position(10, 800)<br>ap.text.Position(90, 700)</pre><p>So instead of letting the paragraph layout decide where the text goes, we specify its position ourselves.</p><p>This is probably the simplest reason to useTextBuilder: you know where the text needs to appear on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*q6CYoQ_fPMeOqrqmeVp_rQ.png" /></figure><h3>3. Formatting Positioned Text</h3><p>Position and formatting are handled separately. We can place a TextFragment first and then configure its TextState in the usual way:</p><pre>def text_builder_example_02(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.position = ap.text.Position(10, 700)<br><br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Times New Roman&quot;)<br>    text_fragment.text_state.font_size = 12<br>    text_fragment.text_state.background_color = ap.Color.light_gray<br>    text_fragment.text_state.foreground_color = ap.Color.red<br>    text_fragment.text_state.stroking_color = ap.Color.dark_red<br>    text_fragment.text_state.draw_text_rectangle_border = True<br><br>    text_builder = ap.text.TextBuilder(page)<br>    text_builder.append_text(text_fragment)<br><br>    document.save(output_file_name)</pre><p>Here the fragment is placed at (10, 700), while TextState controls how it looks.</p><p>The example also draws a border around the text rectangle:</p><pre>text_fragment.text_state.stroking_color = ap.Color.dark_red<br>text_fragment.text_state.draw_text_rectangle_border = True</pre><p>stroking_color sets the color used for the border, and draw_text_rectangle_border enables the border itself.</p><p>The rest of the properties work as expected: font selects Times New Roman, font_size is set to 12, and foreground and background colors are applied to the fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*0Y2Th0Ep8t161LxJwqRCPg.png" /></figure><h3>4. Using TextParagraph for Longer Text</h3><p>Exact coordinates work well for short fragments. For longer text, I would use TextParagraph instead.</p><p>Here is a basic example:</p><pre>def text_builder_example_03(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text = (<br>        &quot;Alice was beginning to get very tired of sitting by her sister on the bank, &quot;<br>        &quot;and of having nothing to do...&quot;<br>    )<br><br>    builder = ap.text.TextBuilder(page)<br>    paragraph = ap.text.TextParagraph()<br>    paragraph.position = ap.text.Position(20, 780)<br>    paragraph.append_line(text)<br>    paragraph.first_line_indent = 50<br><br>    paragraph.formatting_options.wrap_mode = (<br>        ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS<br>    )<br><br>    builder.append_paragraph(paragraph)<br>    document.save(output_file_name)</pre><p>There are a few differences from the earlier TextFragment examples.</p><p>The paragraph still has a position:</p><pre>paragraph.position = ap.text.Position(20, 780)</pre><p>But now we can also set paragraph-specific properties. In this example, first_line_indent = 50 adds an indent to the first line.</p><p>For wrapping, the code uses:</p><pre>ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS</pre><p>This keeps the text wrapping at word boundaries instead of breaking it at arbitrary positions.</p><p>Once the paragraph is ready, it is added with append_paragraph() rather than append_text().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*mPhBj6POvOjKRC2zpymAew.png" /></figure><h3>5. Keeping a Paragraph Inside a Rectangle</h3><p>Positioning a paragraph gives us a starting point. Sometimes that is not enough because the text also has to stay inside a defined area.</p><p>TextParagraph.rectangle can be used for this:</p><pre>TextParagraph.rectangle can be used for this:<br>def text_builder_example_05(output_file_name: str):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text1 = &quot;Alice was beginning to get very tired of sitting by her sister...&quot;<br>    text2 = &quot;So she was considering in her own mind...&quot;<br><br>    builder = ap.text.TextBuilder(page)<br>    paragraph = ap.text.TextParagraph()<br>    paragraph.first_line_indent = 20<br>    paragraph.rectangle = ap.Rectangle(132, 630, 420, 750, True)<br>    paragraph.formatting_options.wrap_mode = (<br>        ap.text.TextFormattingOptions.WordWrapMode.DISCRETIONARY_HYPHENATION<br>    )<br><br>    fragment = ap.text.TextFragment(text1)<br>    fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Times New Roman&quot;)<br>    fragment.text_state.font_size = 12<br>    paragraph.append_line(fragment)<br><br>    paragraph.append_line(&quot; &quot;)<br><br>    fragment = ap.text.TextFragment(text2)<br>    fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Times New Roman&quot;)<br>    fragment.text_state.font_size = 12<br>    paragraph.append_line(fragment)<br><br>    builder.append_paragraph(paragraph)<br>    document.save(output_file_name)</pre><p>The rectangle is defined here:</p><pre>paragraph.rectangle = ap.Rectangle(132, 630, 420, 750, True)</pre><p>Now the paragraph has an area in which its content can be laid out.</p><p>This example uses another wrapping mode as well:</p><pre>ap.text.TextFormattingOptions.WordWrapMode.DISCRETIONARY_HYPHENATION</pre><p>The paragraph contains two TextFragment objects, with an empty line between them. Each fragment still has its ownTextState, so paragraph layout does not prevent us from formatting the text itself.</p><p>A setup like this is useful when a PDF layout has predefined areas for content. For example, the same approach can be used for a caption, note, sidebar, or another block that has to fit into a particular part of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*HLDvmTJuvma8RMP1bkwjAg.png" /></figure><h3>TextBuilder, TextFragment, or TextParagraph?</h3><p>I use them for slightly different jobs.</p><p>TextBuilder is connected to the page and is responsible for adding the positioned text. TextFragment works well for individual pieces of text, especially when their coordinates are known. TextParagraph is a better fit when several lines should be treated as one block and need indentation or wrapping.</p><p>Formatting still stays in TextState. Moving from a fragment to a paragraph does not change how fonts, sizes, or colors are configured.</p><p>For example, if I only need to put a short label at (10, 700), a positioned TextFragment is enough. If the content is several lines long and has to fit inside a rectangle, I would create a TextParagraph and let its formatting options handle the wrapping.</p><p>In practice, I wouldn’t use TextBuilder for every piece of text in a PDF. If normal paragraph flow already gives the expected result, it page.paragraphs.add() is simpler.</p><p>TextBuilder becomes useful when the position itself is part of the layout. For a short label or caption, I can set the coordinates on a TextFragment and add it exactly where I need it. When there is more text, especially inside a limited area, it TextParagraph gives me control over indentation, wrapping, and the available rectangle.</p><p>What I like about this approach is that I don’t have to change the way the text itself is formatted. Fonts, sizes, colors, and borders still belong to TextState; TextBuilder just gives me more control over where that text ends up on the page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba57dbdc3327" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/how-to-use-textbuilder-in-aspose-pdf-for-python-for-precise-text-placement-ba57dbdc3327">How to Use TextBuilder in Aspose.PDF for Python for Precise Text Placement</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Formatting in PDFs with Python Using Aspose.PDF]]></title>
            <link>https://medium.com/asposepdf/text-formatting-in-pdfs-with-python-using-aspose-pdf-6d8dcfadec52?source=rss-d3aa36435255------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d8dcfadec52</guid>
            <category><![CDATA[aspose]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[document-automation]]></category>
            <dc:creator><![CDATA[Aspose-PDF-Python]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 12:25:15 GMT</pubDate>
            <atom:updated>2026-08-12T12:25:15.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgn0fXMZC4a9WcN9V31RPQ.png" /></figure><p><em>How </em><strong><em>TextFragment</em></strong><em>, </em><strong><em>TextSegment</em></strong><em>, and </em><strong><em>TextState</em></strong><em> work in Aspose.PDF, and where text formatting is defined.</em></p><p>Generating a simple PDF with Aspose.PDF for Python takes only a few steps: create a Document, add a Page, create some text and add it to the page.</p><p>Formatting becomes more interesting when different parts of the document need different styles. A title may need a larger font, a word may need to be bold or italic, or a single character may need to appear as superscript or subscript.</p><p>Aspose.PDF handles these cases at three levels:</p><ul><li>document.page_info.default_text_state — document-level defaults</li><li>TextFragment.text_state — formatting for a complete text fragment</li><li>TextSegment.text_state — formatting for part of a fragment</li></ul><p>The examples below show when to use each one.</p><h3>Where text formatting starts in Aspose.PDF</h3><p>Four objects are involved in these examples:</p><ol><li>Document represents the PDF document and contains shared settings.</li><li>Page receives the document content.</li><li>TextFragment represents a block or fragment of text.</li><li>TextSegment represents an inline part of a TextFragment.</li></ol><p>Properties such as font, size, and color can be set at different levels. Which level you use depends on the scope of the formatting.</p><h3>1. Adding plain text</h3><p>The simplest example creates two text fragments and adds them to a page:</p><pre>import aspose.pdf as ap<br><br>def add_text_example_01(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Chapter 1&quot;)<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Down the Rabbit-Hole&quot;)<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)</pre><p>page.paragraphs.add() adds each TextFragment to the page&#39;s paragraph collection. The text is therefore handled by the paragraph layout engine instead of being positioned manually with x/y coordinates. We’ll discuss how to position text on a page separately, but now we’ll explore formatting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIfQL0VXxgKPTzOJpXFJVA.png" /></figure><p>No formatting properties are set explicitly here, so the fragments use the default TextState values.</p><h3>2. Setting a default font</h3><p>If the same font is used throughout a document, it can be set through default_text_state:</p><pre>def add_text_example_02(output_file_name):<br>    document = ap.Document()<br>    document.page_info.default_text_state.font = (<br>        ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    )<br><br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Chapter 1&quot;)<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Down the Rabbit-Hole&quot;)<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)</pre><p>The following assignment sets Calibri as the default font:</p><pre>document.page_info.default_text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)</pre><p>A fragment uses this font unless its own text_state.font property overrides it.</p><p>Setting the font once at the document level is useful when most of the document uses the same typeface and avoids repeating the same assignment for every fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LeotSMWUTYGLosNCHuEXA.png" /></figure><p>FontRepository.find_font(&quot;Calibri&quot;) looks for the requested font in the runtime environment. It does not create or install the font, so the font must be available on the system where the code runs.</p><h3>3. Formatting a complete TextFragment</h3><p>Formatting that applies to a complete text fragment can be set through TextFragment.text_state.</p><pre>def add_text_example_03(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text Bold&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.font_style = ap.text.FontStyles.BOLD<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text Italic&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.font_style = ap.text.FontStyles.ITALIC<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text Underline&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.underline = True<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text Stroking&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.strike_out = True<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)</pre><p>Several formatting properties are available through the same text_state object:</p><ul><li>font selects the font</li><li>font_size sets its size</li><li>font_style applies styles such as BOLD or ITALIC</li><li>underline enables underlining</li><li>strike_out adds a strikeout</li></ul><p>There is no separate object for each of these styles. They are properties of TextState, so a fragment can combine several formatting settings when needed.</p><p>Use TextFragment.text_state when the formatting should affect the complete fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFnzcUrPahQXrgS_o1yxbw.png" /></figure><h3>4. Setting text and background colors</h3><p>Text color and background color are also controlled through TextState:</p><pre>def add_text_example_04(output_file_name):<br>    document = ap.Document()<br>    document.page_info.default_text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br><br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.foreground_color = ap.Color.orange<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.background_color = ap.Color.light_gray<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)</pre><p>foreground_color sets the text color. background_color sets the color behind the text.</p><p>This example uses two predefined ap.Color values:</p><pre>ap.Color.orange<br>ap.Color.light_gray</pre><p>The full list of color’s values you can find <a href="https://reference.aspose.com/pdf/python-net/aspose.pdf/color/#properties">here</a>.</p><p>Both properties belong to the same TextState used for fonts, font size, and other text formatting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-r_oKNkfMpy4D1eAVLm7g.png" /></figure><h3>5. Formatting part of a line with TextSegment</h3><p>TextFragment.text_state works when the whole fragment has the same formatting. For mixed formatting inside a fragment, use TextSegment.</p><p>The following example adds two segments and gives each one a different vertical position:</p><pre>def add_text_example_05a(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.segments.append(ap.text.TextSegment(&quot;Additional text segment 1&quot;))<br>    text_fragment.segments.append(ap.text.TextSegment(&quot;Additional text segment 2&quot;))<br><br>    index = 0<br>    for text_segment in text_fragment.segments:<br>        if index == 1:<br>            text_segment.text_state.superscript = True<br>        if index == 2:<br>            text_segment.text_state.subscript = True<br>        index += 1<br><br>    page.paragraphs.add(text_fragment)<br>    document.save(output_file_name)</pre><p>A TextFragment contains a segments collection. Each segment has its own text_state, so individual parts of the same fragment can be formatted independently.</p><p>In this example, one segment is superscript, and another is subscript.</p><p>The original text passed to TextFragment is also part of the segments collection. The appended segments follow it, which is why the example can select them by index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SlMXKeG9wPZtqcgkp4mxbA.png" /></figure><p>For a shorter case, a specific segment can be formatted directly:</p><pre>fragment = ap.text.TextFragment(&quot;H&quot;)<br>fragment.segments.append(ap.text.TextSegment(&quot;2&quot;))<br>fragment.segments[1].text_state.subscript = True<br>fragment.segments.append(ap.text.TextSegment(&quot;O&quot;))</pre><p>Here, the &quot;2&quot; segment is selected directly and formatted as a subscript.</p><h3>Full source code</h3><pre>import aspose.pdf as ap<br><br><br>def add_text_example_01(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Chapter 1&quot;)<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Down the Rabbit-Hole&quot;)<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)<br><br><br>def add_text_example_02(output_file_name):<br>    document = ap.Document()<br>    document.page_info.default_text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br><br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Chapter 1&quot;)<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Down the Rabbit-Hole&quot;)<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)<br><br><br>def add_text_example_03(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text Bold&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.font_style = ap.text.FontStyles.BOLD<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text Italic&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.font_style = ap.text.FontStyles.ITALIC<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text Underline&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.underline = True<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text Stroking&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.strike_out = True<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)<br><br><br>def add_text_example_04(output_file_name):<br>    document = ap.Document()<br>    document.page_info.default_text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br><br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.foreground_color = ap.Color.orange<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.background_color = ap.Color.light_gray<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)<br><br><br>def add_text_example_05a(output_file_name):<br>    document = ap.Document()<br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.segments.append(ap.text.TextSegment(&quot;Additional text segment 1&quot;))<br>    text_fragment.segments.append(ap.text.TextSegment(&quot;Additional text segment 2&quot;))<br><br>    index = 0<br>    for text_segment in text_fragment.segments:<br>        if index == 1:<br>            text_segment.text_state.superscript = True<br>        if index == 2:<br>            text_segment.text_state.subscript = True<br>        index += 1<br><br>    page.paragraphs.add(text_fragment)<br>    document.save(output_file_name)<br><br><br>def add_text_example_05b(output_file_name):<br>    document = ap.Document()<br>    document.page_info.default_text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br><br>    page = document.pages.add()<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.foreground_color = ap.Color.orange<br>    page.paragraphs.add(text_fragment)<br><br>    text_fragment = ap.text.TextFragment(&quot;Sample text fragment&quot;)<br>    text_fragment.text_state.font = ap.text.FontRepository.find_font(&quot;Calibri&quot;)<br>    text_fragment.text_state.font_size = 16<br>    text_fragment.text_state.background_color = ap.Color.light_gray<br>    page.paragraphs.add(text_fragment)<br><br>    document.save(output_file_name)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    add_text_example_01(&quot;../sample_data/output/sample1.pdf&quot;)<br>    add_text_example_02(&quot;../sample_data/output/sample2.pdf&quot;)<br>    add_text_example_03(&quot;../sample_data/output/sample3.pdf&quot;)<br>    add_text_example_04(&quot;../sample_data/output/sample4.pdf&quot;)<br>    add_text_example_05a(&quot;../sample_data/output/sample5a.pdf&quot;)<br>    add_text_example_05b(&quot;../sample_data/output/sample5b.pdf&quot;)</pre><h3>Choosing the right formatting level</h3><p>The main difference between the three formatting levels is their scope:</p><ul><li>Use default_text_state for formatting that should be used as a document default.</li><li>Use TextFragment.text_state when a complete fragment needs its own formatting.</li><li>Use TextSegment.text_state when only part of a fragment needs different formatting.</li></ul><p>FontRepository.find_font() also depends on the requested font being available in the runtime environment, while page.paragraphs.add() lets the paragraph layout engine position text instead of requiring manual coordinates.</p><p>Text formatting in Aspose.PDF for Python is handled primarily through TextState. The object on which that state is set determines how much text the formatting affects.</p><p>Document defaults belong to default_text_state, fragment-level formatting belongs to TextFragment.text_state, and inline changes belong to TextSegment.text_state.</p><p>The same approach covers fonts, sizes, bold and italic styles, underlining, strikeout, foreground and background colors, superscript, and subscript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d8dcfadec52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asposepdf/text-formatting-in-pdfs-with-python-using-aspose-pdf-6d8dcfadec52">Text Formatting in PDFs with Python Using Aspose.PDF</a> was originally published in <a href="https://medium.com/asposepdf">aspose-pdf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>