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 situationWhat to doWhy
The metadata title is non-empty and not on the invalid listUse the metadata title and tag the source as metadataIt is the title the document declares about itself
The metadata title is empty or matches an invalid patternUse the filename without its extension and tag filename_fallback or invalid_metadata_fallbackIt gives a usable title when internal metadata is unreliable
The metadata cannot be decodedLog decode_error, stop, and do not guessCorrupted text must never pass downstream silently
The filename is meaningless and the metadata is invalidKeep the result, label it low_confidence, and review it manuallyAutomation 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 /Info dictionary 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:

  1. No metadata at all. The generating tool writes no title, so the title field returns an empty string.
  2. Default values from batch tools. Processing tools overwrite the title with values such as "Untitled," "Microsoft Word," or a string of UUIDs.
  3. 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 /Title is "2024Annual Financial Audit Report" and the filename is audit_2024.pdf. The expected title is "2024 Annual Financial Audit Report," tagged metadata.
  • Boundary input 1: /Title is an empty string and the filename is Q3_report_draft.pdf. The expected title is "Q3_report_draft" (without the extension), tagged filename_fallback.
  • Boundary input 2: /Title is "untitled document," matched case-insensitively against a predefined list of invalid values, and the filename is scan_001.pdf. The expected title is "scan_001," tagged invalid_metadata_fallback.
  • Boundary input 3: /Title contains an illegal UTF-8 sequence and decoding fails. The code should raise a clear exception or return a safe default, and log decode_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 labelWhen it appliesAutomated?
metadataThe metadata title is non-empty and not on the invalid listYes
filename_fallbackThe metadata title is emptyYes
invalid_metadata_fallbackThe metadata title matches an invalid patternYes
decode_errorDecoding fails; the error is logged and no title is inferredNo, check file integrity manually
low_confidenceThe filename is also meaningless and the metadata is invalidNo, 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 conditionProcessing decisionAutomated?
Metadata title is non-empty and not on the invalid listUse the metadata title, tagged source=metadataYes
Metadata title is empty or matches an invalid patternFall back to the filename without its extension, with the matching fallback tagYes
Metadata decoding fails or throws an exceptionStop, log the error, and do not try to infer the contentNo, check file integrity manually
Filename is meaningless (for example tmp123.pdf) and metadata is invalidRun the fallback but label the result low_confidenceNo, confirm manually or add context
Scanned image with no text layerThis logic does not apply; extract the title with OCR firstNo, 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

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

Updated 2026-11-29