Search code examples
pythondocx

How to add text to a word document header


Header I'm trying to add "Adapted Proof" text to the header of my .docx document. I would like to add this text right after "Instruções:" however, I believe I am passing it the wrong way and the code is not finding this word "Instruções:" in the text. If I place the word instructions anywhere else in the document, the text "adapted proof" is appended.

import os
import shutil
from docx import Document
import requests
from senhaapi import API_KEY
import json
from docxtpl import DocxTemplate

ans = read_multiple_choice(
    "Escolha a matéria da prova que será submetida",
    [{"label": "Português", "value": "portugues"},
     {"label": "Matemática", "value": "matematica"},
     {"label": "Geografia", "value": "geografia"},
     {"label": "História", "value": "historia"},
     {"label": "Física", "value": "fisica"},
     {"label": "Química", "value": "quimica"},
     {"label": "Literatura", "value": "Literatura"},
     {"label": "Inglês", "value": "ingles"},
     {"label": "Espanhol", "value": "espanhol"}, ],
)

if ans == "portugues":
    file_response = read_file("Enviar")
    file_name = file_response.name

    if not file_name.endswith(".docx"):
        display("A prova enviada deve estar no formato .docx", size='medium')
    else:
        script_dir = os.getcwd()
        destination_dir = os.path.join(script_dir, "foo/bar")
        os.makedirs(destination_dir, exist_ok=True)
        original_file_path = os.path.join(destination_dir, file_name)
        with open(original_file_path, "wb") as destination_file:
            shutil.copyfileobj(file_response.file, destination_file)

        document = Document(original_file_path)

        texto_a_adicionar = "Prova Adaptada"

        for paragraph in document.paragraphs:
            if not paragraph.text.strip():  # Verificar se o parágrafo está vazio
                paragraph.add_run(texto_a_adicionar)
                break  # Parar após adicionar o texto

        modified_file_path = os.path.join(destination_dir, "modified_" + file_name)
        document.save(modified_file_path)

else:
    display("Selecione uma opção válida", size='medium')

The parts that contain file_responder, display, read_multiple_choice, are from my work library and work normally. I appreciate the help


Solution

  • Your current code is adding the text to a paragraph in the body of the document not the header.

    I found the way to fix via the python-docx library:

    import os
    import shutil
    from docx import Document
    from docx.oxml.ns import qn
    from docx.shared import Pt
    from docxtpl import DocxTemplate
    from senhaapi import API_KEY  # You need to import your API key module here
    from your_library import read_multiple_choice, read_file, display  # Import your library functions here
    
    ans = read_multiple_choice(
        "Escolha a matéria da prova que será submetida",
        [{"label": "Português", "value": "portugues"},
         {"label": "Matemática", "value": "matematica"},
         # ... other options ...
         {"label": "Espanhol", "value": "espanhol"},],
    )
    
    if ans == "portugues":
        file_response = read_file("Enviar")
        file_name = file_response.name
    
        if not file_name.endswith(".docx"):
            display("A prova enviada deve estar no formato .docx", size='medium')
        else:
            script_dir = os.getcwd()
            destination_dir = os.path.join(script_dir, "foo/bar")
            os.makedirs(destination_dir, exist_ok=True)
            original_file_path = os.path.join(destination_dir, file_name)
            with open(original_file_path, "wb") as destination_file:
                shutil.copyfileobj(file_response.file, destination_file)
    
            document = Document(original_file_path)
            
            texto_a_adicionar = "Adapted Proof"
    
            # Iterate through all sections and headers to find "Instruções:" and modify the header
            for section in document.sections:
                header = section.header
                for paragraph in header.paragraphs:
                    if "Instruções:" in paragraph.text:
                        run = paragraph.add_run(texto_a_adicionar)
                        font = run.font
                        font.size = Pt(12)  # Set the font size as needed
                        break  # Stop after modifying the header
    
            modified_file_path = os.path.join(destination_dir, "modified_" + file_name)
            document.save(modified_file_path)
    
    else:
        display("Selecione uma opção válida", size='medium')
     
    

    replace your_library with your libary I thnk python-docx is a good method but you may be looking for something else goodluck hope my code works for you