File Name vs Document Title: Tidy Up PDF Metadata
when the automation script processes reportfinalv2.pdf When the document title is written into the database, downstream translation or retrieval systems may rec
If you run automation that handles PDFs, such as scripts that feed translation or retrieval systems, the title you pick for each file matters. A file called report_final_v2.pdf can end up in your database as a meaningless string if you copy the wrong value. This guide is for developers and data teams who need titles that are reliable enough to pass downstream.
The problem is that a PDF has two possible titles: the filename and the title stored inside the file. These often disagree, and the internal title can be empty, garbled, or filled with placeholder text by faulty tools. Trusting doc.metadata["title"] directly is a common source of errors.
You will learn how to set up a hierarchical title-extraction strategy with validation and fallbacks, label each result with its source, and define when a file should go to manual review. Before you process important files, keep the original copies.
How do you pick a reliable PDF title? The short answer
Extract the metadata title first, validate it, fall back to the filename only when the metadata fails, and tag every result with its source.
| Your situation | What to do | Why |
|---|---|---|
| The metadata title is non-empty and not on the invalid list | Use the metadata title and tag the source as metadata | It is the title the document declares about itself |
| The metadata title is empty or matches an invalid pattern | Use the filename without its extension and tag filename_fallback or invalid_metadata_fallback | It gives a usable title when internal metadata is unreliable |
| The metadata cannot be decoded | Log decode_error, stop, and do not guess | Corrupted text must never pass downstream silently |
| The filename is meaningless and the metadata is invalid | Keep the result, label it low_confidence, and review it manually | Automation cannot confirm the title |
Why do file names and document titles differ?
The two values come from different places:
- The filename is set by the operating system or the downloader.
- The document title is stored inside the PDF, in the
/Infodictionary or in XMP metadata.
Because these sources are independent, they are often inconsistent. The internal metadata may also be empty, garbled, or contain placeholder values written by faulty tools.
Typical scenarios where metadata is missing or untrustworthy
The PDF specification allows metadata fields to be empty or absent. In practice, three problems come up often:
- No metadata at all. The generating tool writes no title, so the
titlefield returns an empty string. - Default values from batch tools. Processing tools overwrite the title with values such as "Untitled," "Microsoft Word," or a string of UUIDs.
- Encoding errors. The title appears as gibberish or is truncated.
Some PDFs also put the real title in the body text on the opening page rather than in the metadata. In that case, even a non-empty metadata title may not match the document's intended identifier. None of these cases can be solved with one API call. You need explicit validation and fallback logic.
Synthetic examples: expected output and boundary handling
The following synthetic examples show the expected behaviour. You need to build your own test files; these are not real documents.
- Normal input: The internal
/Titleis "2024Annual Financial Audit Report" and the filename isaudit_2024.pdf. The expected title is "2024 Annual Financial Audit Report," taggedmetadata. - Boundary input 1:
/Titleis an empty string and the filename isQ3_report_draft.pdf. The expected title is "Q3_report_draft" (without the extension), taggedfilename_fallback. - Boundary input 2:
/Titleis "untitled document," matched case-insensitively against a predefined list of invalid values, and the filename isscan_001.pdf. The expected title is "scan_001," taggedinvalid_metadata_fallback. - Boundary input 3:
/Titlecontains an illegal UTF-8 sequence and decoding fails. The code should raise a clear exception or return a safe default, and logdecode_error. It must never silently use corrupted text.
Two rules run through all of these. Every output carries a source label, and the fallback rules are written explicitly in the code rather than left as implicit assumptions.
PyMuPDF metadata extraction and validation
The following Python example applies this logic with PyMuPDF. Install PyMuPDF>=1.24.0. Because API stability depends on the official documentation, lock to a specific version in real use.
The example builds a minimal PDF in memory, so you do not need external files. To test with real documents, replace the stream with a local PDF byte stream, and make sure you are legally allowed to read the file.
import pymupdf
import re
from typing import Dict, Any
# 合成示例:创建一个带元数据的PDF用于演示
def create_sample_pdf(title: str) -> bytes:
doc = pymupdf.open()
page = doc.new_page()
page.insert_text((72, 72), "Sample content")
if title is not None:
doc.set_metadata({"title": title})
return doc.tobytes()
INVALID_TITLES = {"untitled", "untitled document", "microsoft word", "", "document"}
def extract_title_with_fallback(pdf_bytes: bytes, filename: str) -> Dict[str, str]:
doc = None
try:
doc = pymupdf.open(stream=pdf_bytes)
meta = doc.metadata or {}
raw_title = (meta.get("title") or "").strip()
# 检查是否为无效占位符或纯空白
if not raw_title or raw_title.lower() in INVALID_TITLES:
fallback = re.sub(r'\.[^.]+$', '', filename)
source = "invalid_metadata_fallback" if raw_title else "filename_fallback"
return {"title": fallback, "source": source}
# 有效元数据标题
return {"title": raw_title, "source": "metadata"}
except UnicodeDecodeError:
raise ValueError("Metadata title contains invalid encoding")
finally:
if doc is not None:
doc.close()
# 验证逻辑(合成样本)
sample_ok = create_sample_pdf("2024年度财务审计报告")
result_ok = extract_title_with_fallback(sample_ok, "audit_2024.pdf")
assert result_ok == {"title": "2024年度财务审计报告", "source": "metadata"}
sample_empty = create_sample_pdf("")
result_empty = extract_title_with_fallback(sample_empty, "Q3_report_draft.pdf")
assert result_empty == {"title": "Q3_report_draft", "source": "filename_fallback"}
sample_invalid = create_sample_pdf("Untitled Document")
result_invalid = extract_title_with_fallback(sample_invalid, "scan_001.pdf")
assert result_invalid == {"title": "scan_001", "source": "invalid_metadata_fallback"}
This code demonstrates only title extraction and fallback. It does not include XMP parsing, multilingual title selection, or OCR-based fallback. In production, extend the validation rules and add logging.
📊 At a glance: title sources and their handling
| Source label | When it applies | Automated? |
|---|---|---|
metadata | The metadata title is non-empty and not on the invalid list | Yes |
filename_fallback | The metadata title is empty | Yes |
invalid_metadata_fallback | The metadata title matches an invalid pattern | Yes |
decode_error | Decoding fails; the error is logged and no title is inferred | No, check file integrity manually |
low_confidence | The filename is also meaningless and the metadata is invalid | No, confirm manually or add context |
Acceptance criteria and manual review boundary
Use this table to decide when automation can be trusted and when a person must check the file.
| Observed condition | Processing decision | Automated? |
|---|---|---|
| Metadata title is non-empty and not on the invalid list | Use the metadata title, tagged source=metadata | Yes |
| Metadata title is empty or matches an invalid pattern | Fall back to the filename without its extension, with the matching fallback tag | Yes |
| Metadata decoding fails or throws an exception | Stop, log the error, and do not try to infer the content | No, check file integrity manually |
Filename is meaningless (for example tmp123.pdf) and metadata is invalid | Run the fallback but label the result low_confidence | No, confirm manually or add context |
| Scanned image with no text layer | This logic does not apply; extract the title with OCR first | No, it belongs to a different pipeline |
This table covers only the metadata title stage. Overall document understanding still needs evaluation, including body text and table of contents structure. A working code sample does not mean production-level reliability.
Reference and next step
- PyMuPDF Document.metadata official documentation
- PyMuPDF
set_metadatamethod: see theset_metadataentry on the same documentation page.
Using this checklist for document translation
Before you send a document for translation, check that the page order, source locations, and text integrity are correct. Then submit the same sample to the translation process. Afterwards, confirm that headings, body text, and figure captions still correspond correctly. Do not judge the result only by whether the text reads smoothly.
OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.
🎯 Which approach fits you?
If you run batch jobs on downloaded files
Use the metadata title when it is valid, and fall back to the filename with a source tag when it is not. Keep the labels so you can trace every decision later.
If your PDFs are scanned images
This title logic does not apply to files with no text layer. Extract the title with OCR in a separate pipeline first.
If decoding fails on a file
Stop processing that file and check its integrity manually. Do not let a guessed title reach your database.
❓ FAQ
1. Why not just use the metadata title every time?
Metadata can be empty, overwritten with default values, or garbled by encoding errors. Validating it and falling back to the filename when needed prevents those values from reaching your data.
2. What does the source label do?
It records whether a title came from metadata, a filename fallback, an invalid-metadata fallback, or was marked low_confidence. This lets you trace each decision later.
3. What should happen when decoding fails?
Log decode_error, stop processing, and do not infer a title. Corrupted text should never be used silently.
4. Can this approach handle scanned PDFs?
No. Files without a text layer need OCR to extract a title, which belongs to a different processing pipeline.
📝 Summary
Do not rely on a single metadata field. Validate the internal title, fall back to the filename with a clear label, and send unreliable cases to manual review. Test these rules on your own sample files before you use them in production.
Try it now: upload a document and get it translated with the layout intact


