Skip to content
Danube Labs

Translate Word Document with AI and Keep Formatting

To translate a Word document with AI and keep the formatting, extract the text run by run, translate it in chunks with context, and write it back into the same runs. PDFs need extraction or OCR first.

By Alexandru Secureanu8 min read
A Word page and a slide side by side, the same layout with bold and table intact, one in English and one in Romanian

To translate a Word document with AI and keep the formatting, work on the file's structure. Extract every paragraph, table cell, text box and slide shape with its position, translate the text in chunks with context and a glossary, then write each result back into the same runs, the stretches of text that share one format, so bold, italics, fonts and colours survive. PDFs are harder: they need text extraction, or OCR for scans, and usually end up as a rebuilt document.

Why does copy-paste into a chatbot break the formatting?

A chat window handles plain text and Markdown. A Word file stores paragraphs, runs, styles, tables, headers, footers, text boxes and fields. Pasting flattens all of that. Tables lose their grid, text boxes and headers are skipped unless you paste them separately, and the answer you paste back arrives with new styles. Long files exceed the model's context window, so you split them by hand, and each piece loses its neighbours, which is how one term ends up translated three ways. Nothing numbers the segments either, so a skipped or merged sentence goes unnoticed. And the whole document goes to a third-party service.

How does a Word or PowerPoint file store text?

The python-docx documentation describes the model. A paragraph contains one or more runs, each holding part of the paragraph's text, and character formatting such as font, size, bold, italic and underline is applied at the run level. A sentence with one bold word is therefore three runs. Runs can also split in the middle of a word after editing, so merge them before you translate. Table cells hold their own paragraphs. Headers and footers live on each section. Text boxes keep their paragraphs inside w:txbxContent elements, which Microsoft's Open XML reference calls a rich text box content container.

PowerPoint follows the same pattern. In python-pptx the chain is shape, text frame, paragraphs, runs. Auto shapes and table cells can contain text, other shapes cannot, and character formatting sits on the run's font. Group shapes contain child shapes, so a translator has to recurse into them.

How should AI document translation work?

  1. Extract segments. Walk the file and record every paragraph, cell, text box and shape with an ID and a location, for example slide 4, shape 7, paragraph 2.
  2. Merge runs. Join the runs of one paragraph into a single translation unit and keep a marker wherever the formatting changes.
  3. Add context. Send each chunk with its neighbouring segments, the document title and a glossary, sized to fit the model's context window.
  4. Demand structure. Ask for output keyed by segment ID, such as a JSON object, and reject anything else.
  5. Validate. Check that every ID came back, that numbers, dates and placeholders match the source, and that no segment is empty.
  6. Write back. Put each translated paragraph into its original runs.
  7. Proofread. Optionally run a second pass with another prompt or model.
  8. Check the layout. Translated text is often longer or shorter than the source, so look for overflow in slides, table cells and headers.

Step 6 has three possible strategies for a paragraph with mixed formatting. Putting all the text into the first run is simple and loses inline emphasis. Wrapping each run in a numbered tag, asking the model to keep the tags and splitting the answer back into runs keeps the emphasis, and the first strategy can serve as the fallback when tags go missing. Splitting by character count is fragile because word order and length change between languages, so avoid it.

What does run-level replacement look like in python-docx?

One fact from the python-docx documentation drives the design. Assigning to Paragraph.text replaces all content with a single run and removes run-level formatting. Assigning to Run.text keeps the run's formatting. The sketch below uses the second form, with the tag strategy and the first-run fallback. The translate function is yours, so call a local model or an API from it.

import re
from docx import Document

TAG = re.compile(r"<r(\d+)>(.*?)</r\1>", re.S)

def translate_paragraph(par, translate):
    runs = [r for r in par.runs if r.text]
    if not runs:
        return
    tagged = "".join(f"<r{i}>{r.text}</r{i}>" for i, r in enumerate(runs))
    out = translate(tagged)                  # your model call; it must keep the tags
    parts = dict(TAG.findall(out))
    if len(parts) == len(runs):              # every run came back
        for i, run in enumerate(runs):
            run.text = parts[str(i)]         # Run.text keeps bold, italic, font, colour
    else:                                    # tags lost: fall back to the first run
        runs[0].text = re.sub(r"</?r\d+>", "", out)
        for run in runs[1:]:
            run.text = ""

def translate_table(table, translate):
    seen = set()
    for row in table.rows:
        for cell in row.cells:
            if cell._tc in seen:             # merged cells repeat in row.cells
                continue
            seen.add(cell._tc)
            for par in cell.paragraphs:
                translate_paragraph(par, translate)
            for nested in cell.tables:
                translate_table(nested, translate)

def header_footer_paragraphs(section):
    for part in (section.header, section.first_page_header, section.even_page_header,
                 section.footer, section.first_page_footer, section.even_page_footer):
        if not part.is_linked_to_previous:   # linked parts belong to an earlier section
            yield from part.paragraphs

def translate_document(src, dst, translate):
    doc = Document(src)
    for par in doc.paragraphs:
        translate_paragraph(par, translate)
    for table in doc.tables:
        translate_table(table, translate)
    for section in doc.sections:
        for par in header_footer_paragraphs(section):
            translate_paragraph(par, translate)
    doc.save(dst)

Three details come from testing this on a sample file. A merged cell appears in row.cells once for every grid column it covers, so the seen set stops it being translated twice. A header that is linked to the previous section returns that section's paragraphs, which the is_linked_to_previous check avoids. And python-docx does not give you a high-level text box object, so paragraphs inside w:txbxContent need an XML search of your own.

For a presentation, the loop changes shape but the run logic stays the same. This helper walks text shapes, table cells and group shapes.

from pptx import Presentation

def walk(shapes):
    for shape in shapes:
        if shape.has_text_frame:
            yield from shape.text_frame.paragraphs
        if shape.has_table:
            for row in shape.table.rows:
                for cell in row.cells:
                    yield from cell.text_frame.paragraphs
        if shape.shape_type == 6:            # group shape: recurse into its children
            yield from walk(shape.shapes)

for slide in Presentation("deck.pptx").slides:
    for par in walk(slide.shapes):
        ...                                  # same run logic as for Word

How do you translate a PDF with AI?

A PDF stores positioned fragments of text. It has no paragraphs, runs or table structure to write back into. PyMuPDF can extract text as plain text, as blocks or words with position information, or as a detailed dictionary of lines and spans, so you can recover where each piece sat. You then have four routes.

  • Translate the source. If you still have the Word or PowerPoint file, translate that and export a new PDF. This gives the best layout by a distance.
  • Convert, translate, export. Convert the PDF to DOCX, translate it as above and export again. Quality depends on the converter, so check tables first.
  • Rebuild by blocks. Extract text blocks with coordinates, translate them and place the results in the same boxes on a new page. You need rules for text that no longer fits, such as a smaller font.
  • Scans. A scanned page has no text layer, so run OCR first. OCRmyPDF adds a text layer to scanned PDFs using Tesseract. Proofread the OCR output before translating, because mistakes in names and numbers carry straight into the translation.

Set expectations for any PDF job. The result is usually a rebuilt, simplified layout, not a pixel-perfect copy.

Should you use a local or a cloud model for confidential documents?

OptionStrengthWatch for
Local model (llama.cpp, Transformers)Documents never leave your machineNeeds a capable GPU or lots of RAM, and a smaller model can translate less well
Cloud API (Gemini, OpenRouter and others)Strong models without local hardwareData-use terms, which differ by provider and by plan

Terms matter. Google's Gemini API terms say that content sent to Unpaid Services may be used to improve Google products and read by human reviewers, and they tell you not to submit sensitive, confidential or personal information there. For Paid Services, Google states that it does not use prompts or responses to improve its products. Other providers differ, so read the data terms of whichever one you choose, and if documents contain personal data, check your legal obligations too.

A hybrid setup works well, with local models for sensitive files and cloud models for the rest. You can also replace names and identifiers with placeholders before sending and restore them afterwards. Cloud translation of long files is token-heavy, so the batching and caching ideas in how we cut LLM costs by 99% apply here too.

How do glossaries and proofreading passes improve quality?

  • Glossary. Keep a list of source terms and their approved translations, add it to every chunk's prompt, then check that each source term in a segment appears with its approved target. Add a do-not-translate list for brand and product names.
  • Consistency. Cache translations by exact source text, so a repeated sentence is translated once and reads the same everywhere.
  • Register. State the audience and whether the tone is formal or informal. Romanian, for example, has formal and informal forms of address that models may mix.
  • Proofreading pass. Send the translation to a second prompt or model that returns only corrections by segment ID. Ask it to look for untranslated fragments, grammar, number and date formats and broken tags.
  • Human review. For contracts, medical or legal text, treat the output as a draft that a qualified person signs off.

What is AI Translator Pro building?

AI Translator Pro is a Danube Labs desktop app that is in development. It is closed source and not released, so this describes what it is built to do. It translates DOCX, PPTX, PDF and TXT files with local models (llama.cpp or Transformers) or cloud APIs (Gemini, OpenRouter), chosen per job. It extracts paragraphs, table cells, text boxes and slide shapes, translates them in chunks and rebuilds them with their bold, italics, colours and fonts. An optional second pass uses a proofreading model. OCR with EasyOCR and OpenCV covers images, the clipboard and scanned PDF pages. A rich-text editor with copy-to-Word keeps formatting, and batch mode, pause and stop handle long jobs.

Need document translation built around your files?

If you need document translation or another AI workflow built around your own files, see AI systems or book a free intro call. If your source is a recording, start with our guide to local Whisper transcription.

Frequently asked questions

Can AI translate a Word document and keep the formatting?
Yes, when the tool edits the file's structure. It extracts paragraphs, table cells and text boxes, translates them in chunks, and writes the text back into the original runs. Pasting into a chat window loses tables, text boxes and styles. Always check the result against a copy of the original.
How do I translate a PowerPoint with AI without breaking the layout?
Translate shape by shape. Walk each slide's shapes, table cells and group shapes, translate each paragraph, and write it back into the same runs so fonts and colours stay. Then check for overflow, because translated text is often a different length and the boxes keep their original size.
Can AI translate a PDF and keep the layout?
Rarely in an exact way. A PDF stores positioned text with no paragraphs or tables, so tools extract text blocks, or run OCR on scans, and rebuild a new layout. If you still have the original Word or PowerPoint file, translate that and export a new PDF.
Is it safe to translate confidential documents with AI?
It depends on where the model runs. A local model keeps files on your machine. For a cloud API, read the data-use terms: Google's Gemini API terms tell you not to submit sensitive or confidential information to Unpaid Services. You can also replace names and identifiers with placeholders before sending.
Why does translated text overflow slides and table cells?
Languages express the same idea in different lengths, and the boxes keep their original size. Check every slide and table after translating. Ask the model for concise wording, allow shrink-on-overflow or a smaller font where text no longer fits, and review the result by eye before you send the file.
Is a local or a cloud model better for document translation?
Each wins somewhere. Local models keep documents on your machine but need capable hardware, and smaller ones can translate less well. Cloud APIs give strong quality without hardware, under their own data terms. Test both on two or three pages of your own documents with your glossary, and consider a hybrid.
Share

Related articles

  • 7 min read

    AI Adoption in Romania: Where SMEs Stand in 2026

    AI adoption in Romania: 5.21% of enterprises used AI in 2025, the lowest share in the EU. Eurostat data, first use cases, costs, GDPR, the AI Act and verified funding.

    • AI
    • Small business
    • Automation
  • 7 min read

    AI Agents ROI: A Practical Formula for Your Business

    AI agents ROI comes down to time saved times loaded cost, minus tokens, review and maintenance. A formula, a worked example, a pilot method and when not to automate.

    • AI
    • Automation
    • Business
  • 7 min read

    AI News September 2026: Models, Prices, Deals and Rules

    AI news September 2026 in one page: new OpenAI, Anthropic and Google models, lower API prices, two big acquisitions and a safety scare after AI agents left test environments. Every item is sourced.

    • AI news
    • AI
    • Regulation