Skip to main content

A Python library for translating PDF documents while preserving the original layout

Project description

pdftradoc

A Python library for translating PDF documents while preserving the original layout.

Features

  • Extract text segments from PDF with position, font, color, and style information
  • Translate segments automatically using Google Translate API
  • Generate translated PDF using overlay approach (preserves original layout)
  • Support for external translation (you translate, library generates PDF)
  • Automatic font size adjustment when translation is longer than original
  • Watermark exclusion (TCPDF, etc.)

Installation

pip install pymupdf deep-translator pillow

Then copy the pdftradoc folder to your project.

Quick Start

Option 1: Automatic Translation

from pdftradoc import extract, translate, apply_overlay

# 1. Extract segments from PDF
extract("document.pdf", "segments.json")

# 2. Translate automatically (Italian to Albanian)
translate("segments.json", source_lang="it", target_lang="sq")

# 3. Generate translated PDF
apply_overlay("document.pdf", "segments.json", "translated.pdf", dpi=200)

Option 2: External Translation (Manual)

from pdftradoc import extract, apply_overlay

# 1. Extract segments
extract("document.pdf", "segments.json")

# 2. Edit segments.json manually or with your translation system
#    Add translations to the "translation" field for each segment

# 3. Generate PDF with your translations
apply_overlay("document.pdf", "segments.json", "translated.pdf", dpi=200)

JSON Format

After extraction, the JSON file contains:

{
  "source": "document.pdf",
  "pages": 2,
  "segments": [
    {
      "id": 0,
      "page": 0,
      "text": "Original text",
      "translation": "",
      "bbox": [100.0, 200.0, 300.0, 220.0],
      "font": "Helvetica",
      "size": 12.0,
      "color": [0.0, 0.0, 0.0],
      "bold": false,
      "italic": false,
      "rotation": 0,
      "origin": [100.0, 218.0]
    }
  ]
}

Segment Fields

Field Description
id Unique segment identifier
page Page number (0-indexed)
text Original text
translation Translated text (fill this!)
bbox Bounding box [x0, y0, x1, y1]
font Font name
size Font size in points
color RGB color [r, g, b] (0-1 range)
bold Is bold text
italic Is italic text
rotation Text rotation in degrees
origin Text baseline origin [x, y]

API Reference

extract(pdf_path, json_path)

Extract all text segments from a PDF.

result = extract("document.pdf", "segments.json")
# Returns: {"segments": 150, "pages": 5, "json_path": "segments.json"}

translate(json_path, source_lang, target_lang, ...)

Auto-translate segments using Google Translate.

result = translate(
    "segments.json",
    source_lang="it",      # Source language (or "auto")
    target_lang="sq",      # Target language
    batch_size=50,         # Segments per batch
    skip_short=2,          # Skip segments shorter than this
    preserve_numbers=True  # Don't translate number-only segments
)
# Returns: {"total": 150, "translated": 120, "skipped": 30, "errors": []}

apply_overlay(pdf_path, json_path, output_path, dpi=150, font_path=None)

Generate translated PDF using overlay approach.

result = apply_overlay(
    "document.pdf",
    "segments.json",
    "translated.pdf",
    dpi=200,               # Image resolution (higher = better quality)
    font_path=None         # Optional: path to custom TTF font
)
# Returns: {"applied": 120, "pages_processed": 5, "errors": []}

apply(pdf_path, json_path, output_path)

Generate translated PDF using redaction approach (faster, smaller files).

result = apply("document.pdf", "segments.json", "translated.pdf")

stats(json_path)

Get statistics from a JSON file.

result = stats("segments.json")
# Returns: {"total_segments": 150, "translated": 120, "percentage": 80.0, ...}

show(json_path, max_segments=20)

Display segments from a JSON file.

show("segments.json", max_segments=10)

Language Codes

Common language codes for translation:

Code Language
auto Auto-detect
it Italian
en English
de German
sq Albanian
fr French
es Spanish
pt Portuguese
ru Russian
zh-CN Chinese (Simplified)
ja Japanese
ar Arabic

DPI Settings

The dpi parameter in apply_overlay affects quality and file size:

DPI Quality File Size Use Case
100 Low Small Draft, quick preview
150 Medium Medium Standard use
200 High Large Final documents
300 Very High Very Large Print quality

Dependencies

  • PyMuPDF (fitz) - PDF manipulation
  • deep-translator - Google Translate API
  • Pillow - Image processing

Examples

Translate German PDF to Albanian

from pdftradoc import extract, translate, apply_overlay

extract("german_doc.pdf", "segments.json")
translate("segments.json", source_lang="de", target_lang="sq")
apply_overlay("german_doc.pdf", "segments.json", "albanian_doc.pdf", dpi=200)

Translate with Custom Font

apply_overlay(
    "document.pdf",
    "segments.json",
    "translated.pdf",
    dpi=200,
    font_path="/path/to/custom-font.ttf"
)

Check Translation Progress

from pdftradoc import stats

result = stats("segments.json")
print(f"Translated: {result['translated']}/{result['total_segments']} ({result['percentage']}%)")

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pdftradoc-1.0.0.tar.gz (14.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pdftradoc-1.0.0-py3-none-any.whl (12.4 kB view details)

Uploaded Python 3

File details

Details for the file pdftradoc-1.0.0.tar.gz.

File metadata

  • Download URL: pdftradoc-1.0.0.tar.gz
  • Upload date:
  • Size: 14.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for pdftradoc-1.0.0.tar.gz
Algorithm Hash digest
SHA256 a374ad02d31d5372eff5168969af23f90cce9e931ad32090ae64427d7fd2f4eb
MD5 5349369527cd0f682c7ceaeae858baf3
BLAKE2b-256 b3e3f3d1661ccbea19e0982fd827bb58e10ef001140a7809df03fd20b97bd9e6

See more details on using hashes here.

File details

Details for the file pdftradoc-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: pdftradoc-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 12.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for pdftradoc-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 db19717f26684d97b46bb184119cc5cb8398b76b91f8afd9e2046f50a955fc86
MD5 a17e19cdf3bc5452365470c66e198462
BLAKE2b-256 3cfb2df072c0e1052f66244d0f73c7d0a83898c1e2339ceb9b972177e30918c4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page