Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Wed Jan 29, 2025 7:28 pm

Hello everyone. I encountered a difficult problem and I can't figure out what the error is.
"Word error when trying to open file.
Try the following:
* Check the document and disk permissions.
* Check if you have enough memory and disk space.
* Open the file with a backup converter.
(C:\Users\user\...\output.docx)"

I have 2 classes in Python, each class has a method that generates a docx document from a template.
First (after which the file is launched) method:
Code: Select all
    def generateDocx(self, hpsm_number, fio):
        print("Начинаю генерировать документ")
        doc = Document()  # Новый документ
        doc.LoadFromFile("ManagingTheVolumeAndPlacementOfTableSpacesOfTheKPPMDatabases/template.docx")  # Загрузка шаблона

        moscow_time = datetime.now(pytz.timezone('Europe/Moscow')).strftime('%d.%m.%Y %H:%M') + " МСК"  # Текущее время

        doc.Replace("hpsm_number", hpsm_number, False, True)  # Замена номера
        doc.Replace("fio", fio, False, True)  # Замена ФИО
        doc.Replace("date_time_msk", moscow_time, False, True)  # Замена времени

        pictures = []  # Список изображений
        for i in range(doc.Sections.Count):  # Проход по секциям
            sec = doc.Sections.get_Item(i)

            for j in range(sec.Paragraphs.Count):  # Проход по параграфам
                par = sec.Paragraphs.get_Item(j)

                if par.ChildObjects.Count > 0:  # Проверка наличия объектов
                    for k in range(par.ChildObjects.Count):  # Проход по объектам
                        docObj = par.ChildObjects.get_Item(k)
                        if docObj.DocumentObjectType == DocumentObjectType.Picture:  # Проверка на изображение
                            pictures.append(docObj)  # Добавление изображения

        for i, picture in enumerate(pictures):  # Загрузка изображений
            picture.LoadImage(f"ManagingTheVolumeAndPlacementOfTableSpacesOfTheKPPMDatabases/{i}.png")  # Загрузка
            picture.Width = 150.0  # Ширина
            picture.Height = 200.0  # Высота

        doc.SaveToFile("output.docx", FileFormat.Docx)  # Сохранение документа
        doc.Close()  # Закрытие документа


Second (after which the file does not run) method:
Code: Select all
    def generateDocx(self, hpsm_number, fio):
        """Генерация документа .docx с заданными параметрами."""
        print("Начинаю генерировать документ")
        doc = Document()  # Создание нового документа
        doc.LoadFromFile("ComputingEnvironmentAnalysisAISKP/template.docx")  # Загрузка шаблона документа

        # Получение текущего времени в Москве
        moscow_time = datetime.now(pytz.timezone('Europe/Moscow')).strftime('%d.%m.%Y %H:%M') + " МСК"

        # Замена плейсхолдеров в документе
        doc.Replace("hpsm_number", hpsm_number, False, True)
        doc.Replace("fio", fio, False, True)
        doc.Replace("date_time_msk", moscow_time, False, True)

        pictures = []  # Список для хранения загружаемых изображений
        for i in range(doc.Sections.Count):  # Проход по секциям документа
            sec = doc.Sections.get_Item(i)

            for j in range(sec.Paragraphs.Count):  # Проход по параграфам
                par = sec.Paragraphs.get_Item(j)

                if par.ChildObjects.Count > 0:  # Проверка на наличие объектов в параграфе
                    for k in range(par.ChildObjects.Count):  # Проход по подчинённым объектам
                        docObj = par.ChildObjects.get_Item(k)
                        if docObj.DocumentObjectType == DocumentObjectType.Picture:  # Проверка на изображение
                            pictures.append(docObj)  # Добавление изображения в список

        # Загрузка изображений
        for i, picture in enumerate(pictures):
            picture.LoadImage(f"ComputingEnvironmentAnalysisAISKP/{i}.png")  # Загрузка изображения
            picture.Width = 150.0  # Установка ширины изображения
            picture.Height = 200.0  # Установка высоты изображения

        # Сохранение документа
        doc.SaveToFile("output.docx", FileFormat.Docx)
        doc.Close()  # Закрытие документа



With all this, the python code is executed without exceptions and errors.please help me solve this problem

Linker_z
 
Posts: 6
Joined: Wed Jan 29, 2025 5:18 pm

Thu Jan 30, 2025 2:02 am

Hello,

Thank you for your letter. Are you saying there is an issue when opening the result document? Are you using Microsoft Word to open it? Please provide your ”template.docx“ and ”output.docx“ documents for further investigation. You can attach them here or send them to us via email ([email protected]). Thank you in advance.

Sincerely,
Lisa
E-iceblue support team
User avatar

Lisa.Li
 
Posts: 1383
Joined: Wed Apr 25, 2018 3:20 am

Thu Jan 30, 2025 3:17 am

Lisa.Li wrote:Hello,

Thank you for your letter. Are you saying there is an issue when opening the result document? Are you using Microsoft Word to open it? Please provide your ”template.docx“ and ”output.docx“ documents for further investigation. You can attach them here or send them to us via email ([email protected]). Thank you in advance.

Sincerely,
Lisa
E-iceblue support team


Thanks for the answer, I sent you a message by email with the same topic as on the forum ("Error opening docx document")

Linker_z
 
Posts: 6
Joined: Wed Jan 29, 2025 5:18 pm

Thu Jan 30, 2025 9:07 am

Hello,

Thank you for your feedback. When I opened your ”output.docx“ in MS Word, I did encounter an error. But I simulated some data to test individually, there were no issues when the output document was opened. What are the scenarios in which you invoke these two methods? Please provide your complete test code so that we can fully simulate your scenario for testing. Thanks in advance.

Sincerely,
Lisa
E-iceblue support team
User avatar

Lisa.Li
 
Posts: 1383
Joined: Wed Apr 25, 2018 3:20 am

Thu Jan 30, 2025 10:34 am

Lisa.Li wrote:Hello,

Thank you for your feedback. When I opened your ”output.docx“ in MS Word, I did encounter an error. But I simulated some data to test individually, there were no issues when the output document was opened. What are the scenarios in which you invoke these two methods? Please provide your complete test code so that we can fully simulate your scenario for testing. Thanks in advance.

Sincerely,
Lisa
E-iceblue support team



Here is the full code


Code: Select all
import pretty_errors
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from datetime import datetime
import pytz
import time
from spire.doc import Document, DocumentObjectType, FileFormat
from secret import URL2, USERNAME2, PASSWORD2  # Предполагается, что эти данные хранятся в отдельном модуле


class ComputingEnvironmentAnalysisAISKP:
    def __init__(self):
        """Инициализация класса ComputingEnvironmentAnalysisAISKP."""
        print("Инициализация ComputingEnvironmentAnalysisAISKP")
        self.browser = None  # Объект веб-браузера

    def setUp(self):
        """Настройка веб-браузера перед тестированием."""
        print("Настройка браузера")
        service = Service(executable_path="webdriver/chromedriver.exe")
        options = webdriver.ChromeOptions()
        options.add_argument('window-size=1920,1080')  # Установка размера окна
        self.browser = webdriver.Chrome(options=options, service=service)  # Создание экземпляра браузера
        print("Запускаю браузер")

    def tearDown(self):
        """Закрытие браузера после завершения действий."""
        if self.browser:
            self.browser.quit()  # Закрытие веб-браузера
            print("Закрываю браузер")

    def login(self):
        """Вход в систему и выполнение необходимых действий после входа."""
        print("Вход в систему")
        self.browser.get(URL2)  # Переход на страницу логина
        self.browser.find_element(By.NAME, 'user').send_keys(USERNAME2)  # Ввод имени пользователя
        self.browser.find_element(By.NAME, 'password').send_keys(PASSWORD2)  # Ввод пароля
        self.browser.find_element(By.XPATH,
                                  '//*[@id="reactRoot"]/div[1]/main/div[3]/div/div[2]/div/div/form/button').click()  # Клик для входа

        # Ожидание загрузки страницы
        time.sleep(5)

        # Уменьшение масштаба видимости
        self.browser.execute_script("document.body.style.zoom='50%'")  # Изменение масштабирования под размер монитора
        time.sleep(10)  # Дополнительное ожидание

        self.browser.save_screenshot('ComputingEnvironmentAnalysisAISKP/0.png')  # Сохранение скриншота

    def generateDocx(self, hpsm_number, fio):
        """Генерация документа .docx с заданными параметрами."""
        print("Начинаю генерировать документ")
        doc = Document()  # Создание нового документа
        doc.LoadFromFile("ComputingEnvironmentAnalysisAISKP/template.docx")  # Загрузка шаблона документа

        # Получение текущего времени в Москве
        moscow_time = datetime.now(pytz.timezone('Europe/Moscow')).strftime('%d.%m.%Y %H:%M') + " МСК"

        # Замена плейсхолдеров в документе
        doc.Replace("hpsm_number", hpsm_number, False, True)
        doc.Replace("fio", fio, False, True)
        doc.Replace("date_time_msk", moscow_time, False, True)

        pictures = []  # Список для хранения загружаемых изображений
        for i in range(doc.Sections.Count):  # Проход по секциям документа
            sec = doc.Sections.get_Item(i)

            for j in range(sec.Paragraphs.Count):  # Проход по параграфам
                par = sec.Paragraphs.get_Item(j)

                if par.ChildObjects.Count > 0:  # Проверка на наличие объектов в параграфе
                    for k in range(par.ChildObjects.Count):  # Проход по подчинённым объектам
                        docObj = par.ChildObjects.get_Item(k)
                        if docObj.DocumentObjectType == DocumentObjectType.Picture:  # Проверка на изображение
                            pictures.append(docObj)  # Добавление изображения в список

        # Загрузка изображений
        for i, picture in enumerate(pictures):
            picture.LoadImage(f"ComputingEnvironmentAnalysisAISKP/{i}.png")  # Загрузка изображения
            picture.Width = 150.0  # Установка ширины изображения
            picture.Height = 200.0  # Установка высоты изображения

        # Сохранение документа
        doc.SaveToFile("output.docx", FileFormat.Docx)
        doc.Close()  # Закрытие документа

    def getScreenshot(self):
        """Запуск процесса получения скриншота и генерации документа."""
        print("Запуск процесса")
        self.setUp()  # Настройка браузера
        self.login()  # Выполнение входа
        self.tearDown()  # Закрытие браузера после завершения

if __name__ == "__main__":  # Исправлено: __name__ в двойных подчеркиваниях
    test = ComputingEnvironmentAnalysisAISKP()  # Создание экземпляра класса
    #test.getScreenshot()  # Получение скриншота
    test.generateDocx("C01598996", "Кириллов Е. А.")  # Генерация документа
#TODO не открывается документ

Linker_z
 
Posts: 6
Joined: Wed Jan 29, 2025 5:18 pm

Fri Jan 31, 2025 8:30 am

Hello,

Thank you for providing the code
I removed the code that was not called in your code and used the latest Spire Doc 13.1.0 conducted testing, but I still haven't reproduced the issue you mentioned. Are you using the latest version? If not, please update and retest. In addition, I have attached my test code and input-output files for your reference. Please run the code in the attachment directly and confirm if the problem still exists. Looking forward to your feedback.

Sincerely,
William
E-iceblue support team
User avatar

William.Zhang
 
Posts: 656
Joined: Mon Dec 27, 2021 2:23 am

Fri Jan 31, 2025 12:15 pm

William.Zhang wrote:Hello,

Thank you for providing the code
I removed the code that was not called in your code and used the latest Spire Doc 13.1.0 conducted testing, but I still haven't reproduced the issue you mentioned. Are you using the latest version? If not, please update and retest. In addition, I have attached my test code and input-output files for your reference. Please run the code in the attachment directly and confirm if the problem still exists. Looking forward to your feedback.

Sincerely,
William
E-iceblue support team


I updated my version of the library. I launched the generated file that you sent me - and it opened. Then I deleted it, launched the code that you sent me - and got an error. Maybe you have any ideas on how to supplement the logging system so that it would be possible to see more clearly what actions the library performs, or perhaps you know how to get error logs when opening this file through Word


addendum: I tried to open the generated file through the built-in WordPad program, and the display is quite normal, almost as it should be

Linker_z
 
Posts: 6
Joined: Wed Jan 29, 2025 5:18 pm

Fri Jan 31, 2025 12:48 pm

William.Zhang wrote:Hello,

Thank you for providing the code
I removed the code that was not called in your code and used the latest Spire Doc 13.1.0 conducted testing, but I still haven't reproduced the issue you mentioned. Are you using the latest version? If not, please update and retest. In addition, I have attached my test code and input-output files for your reference. Please run the code in the attachment directly and confirm if the problem still exists. Looking forward to your feedback.

Sincerely,
William
E-iceblue support team


Friends, I think I found the reason why the first file after generation according to the first template opens, and the second file after generation according to the second template gives an error. I asked my colleague to open the generated file that gives an error, on the computer it also gave an error, but he tried to open it through the phone. I looked through the contents and found that the list of servers that goes in 2 columns is not displayed correctly ... then I compared the templates and saw that the 1 template (which is generated without an error) does not have a list of servers in 2 columns, and in the 2nd (which is generated with an error) template there are 2 columns. I am attaching two templates at once and screenshots of the file with the error opened on the phone.

Linker_z
 
Posts: 6
Joined: Wed Jan 29, 2025 5:18 pm

Tue Feb 04, 2025 10:14 am

Hello,

Thanks for your reply.
Thank you for providing more information. Are you saying that this issue is caused by your template and is unrelated to do with our product. Looking forward to your reply.

Sincerely,
William
E-iceblue support team
User avatar

William.Zhang
 
Posts: 656
Joined: Mon Dec 27, 2021 2:23 am

Tue Feb 04, 2025 10:50 am

William.Zhang wrote:Hello,

Thanks for your reply.
Thank you for providing more information. Are you saying that this issue is caused by your template and is unrelated to do with our product. Looking forward to your reply.

Sincerely,
William
E-iceblue support team

Hello again. I finished writing a report generation for a similar template, which also uses a table with invisible fields, and everything works fine there. However, I found a way to fix my problem, I open the document through WordPad and immediately save it with replacement of the original file. Thanks for trying to help solve my problem, maybe one day I will understand why it happens, I do not blame your product, it is very good!

Linker_z
 
Posts: 6
Joined: Wed Jan 29, 2025 5:18 pm

Thu Feb 06, 2025 1:02 am

Hello,

Thanks for your feedback.
If you encounter other problems with our products in the future, please feel free to write to us.

Sincerely,
William
E-iceblue support team
User avatar

William.Zhang
 
Posts: 656
Joined: Mon Dec 27, 2021 2:23 am

Return to Spire.Doc