python - 在 Linux(Azure 应用服务)上运行 python word (.docx) 到 pdf 转换器的问题?
问题描述
我正在尝试将 Flask 应用程序部署到 Azure Web App Service。我正在运行 Windows 操作系统,但 Azure 应用服务仅支持 Linux 上的 Python。每当它加载涉及将 .docx 转换为 pdf 的 python 模块时,我都会遇到错误。我的容器崩溃,我收到以下消息:
:( Application Error
If you are the application administrator, you can access the diagnostic resources.
以下是我从日志中观察到的错误消息
我已经尝试过 docx2pdf,但我得到了这个错误:
"/opt/python/3.9.0/lib/python3.9/importlib/metadata.py", line 511, in read_text
return self._path.joinpath(filename).read_text(encoding='utf-8')
AttributeError: 'PosixPath' object has no attribute 'read_text'
我尝试了comtypes并得到了这个错误:
File "/tmp/8d97989fbb07031/antenv/lib/python3.9/site-packages/comtypes/__init__.py", line 23, in <module>
from _ctypes import COMError
ImportError: cannot import name 'COMError' from '_ctypes'
我在 python 3.9.7 上运行。对于部署,我已经在 Windows Powershell 和 VScode 上尝试了 azure CLI,我也尝试从 Github 进行部署,但我仍然遇到同样的错误。
有没有办法解决我遇到的问题?还是有另一种方法可以使用python在linux中将docx文件转换为pdf?
解决方案
要解决这个AttributeError: 'PosixPath' object has no attribute 'read_text'
错误,你可以参考这个 GitHub 问题:setup failed 'PosixPath' object has no attribute 'read_text' and 'PosixPath' object has no attribute 'read_text'
为了解决这个ImportError: cannot import name 'COMError' from '_ctypes'
错误,根据SuperBiasedMan COMTypes 是为 Windows 设计的,而不是 Linux。
谢谢阿卜杜勒赫迪·赫勒。发布您的建议作为帮助其他社区成员的答案。
您可以尝试以下代码在 Linux Azure 应用服务上将 docx 文件转换为 pdf:
import sys
import subprocess
import re
def convert_to(folder, source, timeout=None):
args = [libreoffice_exec(), '--headless', '--convert-to', 'pdf', '--outdir', folder, source]
process = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
filename = re.search('-> (.*?) using filter', process.stdout.decode())
return filename.group(1)
def libreoffice_exec():
# TODO: Provide support for more platforms
if sys.platform == 'darwin':
return '/Applications/LibreOffice.app/Contents/MacOS/soffice'
return 'libreoffice'
result = convert_to('TEMP Directory', 'Your File', timeout=15)
可以参考Converting DOCX to PDF using Python、Converting docx to pdf with pure python (on linux, without libreoffice)和How to convert Word document to PDF in Azure App service on Linux
推荐阅读
- ansible - 银河角色。在配置的模块路径中找不到模块文件。此外,缺少核心模块
- python-3.x - 如何键入提示 Python 3 元类?
- typescript - Azure Functions 上的 GraphQL 订阅 - 这可能吗?
- python - 如何从看不见的文档中的列表中识别术语
- c# - 在 SWIG 中使用相同的 C# 代码连接调试和发布 DLL?
- html - 使标题 100% 的屏幕
- react-native - 如何在 Parallel 调用中为每个动画提供回调
- odoo - Odoo XML-RPC:改变活跃的公司?
- css - Chrome 77.0.3865.90 使用 margin-left 搞乱了布局:-100%
- bash - 在没有 ./ 或 bash 或源的情况下运行可执行文件