
Automate Factur-X and ZUGFeRD e-Invoices in Python with PDF.co
15 MIN READ
Use PDF.co’s Split PDF by pages API to divide a PDF into separate files using page numbers or ranges.
This example uploads a local PDF, submits a synchronous request to /v1/pdf/split, and downloads every resulting PDF.
Use Python 3 and install Requests:
python -m pip install requests
Get your API key from the PDF.co dashboard, then set it in the terminal where you will run the program:
export PDFCO_API_KEY="YOUR_API_KEY"$env:PDFCO_API_KEY="YOUR_API_KEY"Replace YOUR_API_KEY with your actual key. Use a small PDF for this synchronous example.
Save this code as split_pdf.py:
import argparse
import os
from pathlib import Path
import requests
def api_json(response):
response.raise_for_status()
data = response.json()
if data.get("error"):
raise RuntimeError(data.get("message", "PDF.co reported an error"))
return data
def main():
parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path)
parser.add_argument("pages", help="One-based ranges, or * for every page")
parser.add_argument("output_directory", type=Path)
args = parser.parse_args()
if not args.source.is_file():
raise ValueError("Source PDF does not exist")
args.output_directory.mkdir(parents=True, exist_ok=False)
headers = {"x-api-key": os.environ["PDFCO_API_KEY"]}
upload = api_json(requests.get(
"https://api.pdf.co/v1/file/upload/get-presigned-url",
headers=headers,
params={
"name": args.source.name,
"contenttype": "application/octet-stream",
},
timeout=60,
))
with args.source.open("rb") as source:
response = requests.put(
upload["presignedUrl"],
data=source,
headers={"Content-Type": "application/octet-stream"},
timeout=120,
)
response.raise_for_status()
result = api_json(requests.post(
"https://api.pdf.co/v1/pdf/split",
headers=headers,
json={
"url": upload["url"],
"pages": args.pages,
"name": "part.pdf",
"async": False,
},
timeout=120,
))
urls = result.get("urls")
if not isinstance(urls, list) or not urls:
raise RuntimeError("The split response contains no output URLs")
if not all(isinstance(url, str) and url for url in urls):
raise RuntimeError("Unexpected output URL list")
for number, url in enumerate(urls, start=1):
download = requests.get(url, timeout=120)
download.raise_for_status()
if not download.content.startswith(b"%PDF-"):
raise RuntimeError(f"Output {number} is not a PDF response")
destination = args.output_directory / f"part-{number:02d}.pdf"
with destination.open("xb") as output:
output.write(download.content)
print(f"Saved {destination}")
if __name__ == "__main__":
main()The upload API returns two URLs:
The storage upload and download requests do not include the API-key header.
This endpoint uses one-based page numbering: the first page is 1.
For a PDF containing at least four pages, run:
python split_pdf.py input.pdf "1-2,3-4" split-output
The program creates:
split-output/part-01.pdf: Source pages 1–2.split-output/part-02.pdf: Source pages 3–4.To create one PDF per page, run:
python split_pdf.py input.pdf "*" split-every-page
Keep * quoted so your shell does not expand it into local filenames.
Use ranges that exist in the source document. The program requires a new output directory for each attempt and does not overwrite an existing directory.
Open each saved PDF and compare its pages and order with the original.
For the two-range example, confirm that there are two output PDFs containing the expected pages. For *, confirm that the output count matches the source page count.
The program downloads each entry in the returned urls list. If a later download fails, earlier files remain saved; inspect those partial results before retrying.
PDF.co’s output links are temporary, so download the files before they expire.
For longer documents, adapt the program to use async: true and Background Job Check. Wait for success before retrieving results. The asynchronous response’s singular url points to a JSON list of output PDF URLs; read that list and download each PDF rather than saving the JSON file as a PDF.
In this tutorial, you learned how to split PDF pages in Python using the PDF.co Web API.
Create an account, get an API key and test a request.