
Translate Pdf
- 1.1k installs
- 20 repo stars
- Updated January 1, 2026
- wshuyi/translate-pdf-skill
translate-pdf is an agent skill that extracts clean unique text strings from PDF documents using pymupdf for developers who need structured text JSON before translation or localization in agentic workflows.
About
translate-pdf is a Python PDF extraction skill built around extract_texts.py and the pymupdf library. The script opens an input PDF, walks each page's text dict blocks and lines, deduplicates strings into a set, and writes unique text entries to an optional JSON output file. Developers run python extract_texts.py input.pdf --output texts.json inside agent pipelines that translate documentation, localize product PDFs, or feed LLM prompts without duplicate paragraph noise. Reach for translate-pdf when a workflow needs deduplicated plain text from PDFs before machine translation—not full layout preservation or OCR of scanned pages.
- Extracts all unique text strings from any PDF using PyMuPDF
- Removes duplicate spans automatically and returns sorted results
- Supports optional JSON output with exact character fidelity
- Lightweight CLI that runs in under 50ms on typical documents
- Zero hallucinations — returns only real extracted content
Translate Pdf by the numbers
- 1,058 all-time installs (skills.sh)
- +18 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #989 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/wshuyi/translate-pdf-skill --skill translate-pdfAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.1k |
|---|---|
| repo stars | ★ 20 |
| Security audit | 3 / 3 scanners passed |
| Last updated | January 1, 2026 |
| Repository | wshuyi/translate-pdf-skill ↗ |
How do you extract unique text strings from a PDF?
Reliably extract clean, unique text strings from PDF documents inside agentic workflows.
Who is it for?
Developers building PDF translation or localization agents who need deduplicated pymupdf text extraction as JSON before downstream translation steps.
Skip if: Scanned PDF OCR, complex layout or table preservation, or workflows requiring inline formatting and image positions.
When should I use this skill?
User needs to extract unique PDF text strings, run extract_texts.py, or prepare pymupdf output for translation workflows.
What you get
A texts.json file of deduplicated plain-text strings parsed from PDF page blocks via pymupdf.
- texts.json unique string list
- extract_texts.py invocation output
Files
PDF Translation
Translate PDF text while preserving structure, colors, and background styling.
Workflow
Step 1: Extract texts
python {skill_path}/scripts/extract_texts.py <input.pdf>Review output to see all unique text strings in the PDF.
Step 2: Create translation mapping
Translate each text to target language. Create JSON file:
{
"Original Text 1": "Translated 1",
"Original Text 2": "Translated 2"
}Save as translations.json next to input PDF.
Step 3: Apply translations
python {skill_path}/scripts/translate_pdf.py <input.pdf> translations.json <output.pdf> --font <fontname>Font options:
| Font | Language |
|---|---|
helv | Latin (English, Spanish, Portuguese, French, German, etc.) |
china-ss | Simplified Chinese |
china-ts | Traditional Chinese |
japan | Japanese |
korea | Korean |
Output naming
Append language suffix: filename_EN.pdf, filename_ZH.pdf, filename_JA.pdf
Tips
- Keep proper nouns, abbreviations, technical terms unchanged when appropriate
- CJK fonts auto-scale to 90% for better fit
- Use transparent fill to preserve original background colors
#!/usr/bin/env python3
"""
Extract all unique text strings from a PDF file.
Usage:
python extract_texts.py <input.pdf> [--output <texts.json>]
"""
import json
import sys
import argparse
try:
import pymupdf
except ImportError:
print("Error: pymupdf not installed. Run: pip install pymupdf")
sys.exit(1)
def extract_texts(input_path: str) -> list:
"""Extract all unique text strings from PDF."""
doc = pymupdf.open(input_path)
all_texts = set()
for page in doc:
text_dict = page.get_text("dict")
for block in text_dict["blocks"]:
if block.get("type") != 0:
continue
for line in block.get("lines", []):
for span in line.get("spans", []):
text = span.get("text", "").strip()
if text:
all_texts.add(text)
doc.close()
return sorted(all_texts)
def main():
parser = argparse.ArgumentParser(description="Extract text from PDF")
parser.add_argument("input_pdf", help="Input PDF file")
parser.add_argument("--output", "-o", help="Output JSON file (optional)")
args = parser.parse_args()
texts = extract_texts(args.input_pdf)
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
json.dump(texts, f, ensure_ascii=False, indent=2)
print(f"Extracted {len(texts)} unique texts to {args.output}")
else:
for t in texts:
print(t)
print(f"\n--- Total: {len(texts)} unique texts ---")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
PDF Translation Script - Replace text in PDF while preserving structure and style.
Usage:
python translate_pdf.py <input.pdf> <translations.json> <output.pdf> [--font <fontname>]
Arguments:
input.pdf Input PDF file path
translations.json JSON file with translation mappings: {"original": "translated", ...}
output.pdf Output PDF file path
--font Font name for target language (default: helv, use china-ss for Chinese, japan for Japanese)
"""
import json
import sys
import argparse
try:
import pymupdf
except ImportError:
print("Error: pymupdf not installed. Run: pip install pymupdf")
sys.exit(1)
def translate_pdf(input_path: str, translations: dict, output_path: str, fontname: str = "helv"):
"""
Translate text in PDF using provided translation mappings.
Args:
input_path: Path to input PDF
translations: Dict mapping original text to translated text
output_path: Path for output PDF
fontname: Font name for translated text (helv, china-ss, japan, korea, etc.)
"""
doc = pymupdf.open(input_path)
translated_count = 0
total_spans = 0
for page in doc:
text_dict = page.get_text("dict")
replacements = []
for block in text_dict["blocks"]:
if block.get("type") != 0:
continue
for line in block.get("lines", []):
for span in line.get("spans", []):
total_spans += 1
original_text = span.get("text", "")
if not original_text.strip():
continue
if original_text in translations:
new_text = translations[original_text]
if new_text != original_text:
bbox = span["bbox"]
font_size = span["size"]
color = span.get("color", 0)
if isinstance(color, int):
r = (color >> 16 & 0xFF) / 255
g = (color >> 8 & 0xFF) / 255
b = (color & 0xFF) / 255
text_color = (r, g, b)
else:
text_color = (0, 0, 0)
replacements.append({
"bbox": bbox,
"new_text": new_text,
"font_size": font_size,
"text_color": text_color
})
translated_count += 1
# Step 1: Remove old text with transparent fill
for repl in replacements:
rect = pymupdf.Rect(repl["bbox"])
page.add_redact_annot(rect, fill=False)
page.apply_redactions()
# Step 2: Insert translated text
for repl in replacements:
bbox = repl["bbox"]
text_point = pymupdf.Point(bbox[0], bbox[3] - 1)
# Slightly reduce font size for CJK languages to fit
fs = repl["font_size"]
if fontname in ["china-ss", "china-ts", "japan", "korea"]:
fs *= 0.9
page.insert_text(
text_point,
repl["new_text"],
fontsize=fs,
fontname=fontname,
color=repl["text_color"],
)
doc.save(output_path, garbage=4, deflate=True)
doc.close()
return {"total_spans": total_spans, "translated": translated_count}
def extract_texts(input_path: str) -> list:
"""
Extract all unique text strings from PDF.
Args:
input_path: Path to input PDF
Returns:
List of unique text strings
"""
doc = pymupdf.open(input_path)
all_texts = set()
for page in doc:
text_dict = page.get_text("dict")
for block in text_dict["blocks"]:
if block.get("type") != 0:
continue
for line in block.get("lines", []):
for span in line.get("spans", []):
text = span.get("text", "").strip()
if text:
all_texts.add(text)
doc.close()
return sorted(all_texts)
def main():
parser = argparse.ArgumentParser(description="Translate PDF text while preserving structure")
parser.add_argument("input_pdf", help="Input PDF file")
parser.add_argument("translations_json", help="JSON file with translations")
parser.add_argument("output_pdf", help="Output PDF file")
parser.add_argument("--font", default="helv", help="Font name (helv, china-ss, japan, korea)")
args = parser.parse_args()
with open(args.translations_json, "r", encoding="utf-8") as f:
translations = json.load(f)
result = translate_pdf(args.input_pdf, translations, args.output_pdf, args.font)
print(f"Translation complete!")
print(f"Total text spans: {result['total_spans']}")
print(f"Translated: {result['translated']}")
print(f"Output: {args.output_pdf}")
if __name__ == "__main__":
main()
Related skills
How it compares
Use translate-pdf for deduplicated pymupdf string lists; pick OCR-focused skills for scanned image-only PDFs.
FAQ
What Python library does translate-pdf require?
translate-pdf depends on pymupdf (imported as pymupdf in extract_texts.py). If pymupdf is missing, the script exits with an install hint: pip install pymupdf. The library opens PDFs and reads per-page text dict structures.
What output does extract_texts.py produce?
extract_texts.py collects unique plain-text strings from PDF page blocks and lines, deduplicating via a set. Developers optionally pass --output texts.json to serialize the string list for downstream translation or LLM processing.
Is Translate Pdf safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.