WeasyPrint 是一个用于将 HTML 转换为 PDF 的 Python 库,它依赖于 WebKit 渲染引擎。在使用 WeasyPrint 在 Docker 容器中通过 FastAPI 导出 PDF 时,可能会遇到字体问题,因为容器内部可能没有安装所需的字体,或者字体路径没有被正确配置。
在使用 WeasyPrint 时,可能会遇到字体缺失的问题,这通常是因为 Docker 容器内部没有安装相应的字体,或者 WeasyPrint 无法找到这些字体文件。
以下是一个完整的 FastAPI 应用示例,它使用 WeasyPrint 在 Docker 容器中导出 PDF,并确保字体正确加载:
from fastapi import FastAPI
from weasyprint import HTML, CSS
import os
app = FastAPI()
@app.get("/export-pdf")
async def export_pdf():
css = CSS(string='''
@font-face {
font-family: 'MyFont';
src: url('/usr/share/fonts/truetype/my_fonts/MyFont.ttf');
}
body {
font-family: 'MyFont', sans-serif;
}
''')
html_content = '''
<html>
<head><title>Sample PDF</title></head>
<body>
<h1>Hello, World!</h1>
<p>This is a sample PDF generated with WeasyPrint.</p>
</body>
</html>
'''
HTML(string=html_content).write_pdf('output.pdf', stylesheets=[css])
# Return the PDF file as a response
return FileResponse('output.pdf', media_type='application/pdf')
确保在 Dockerfile 中安装了字体,并且字体文件路径正确无误。
通过以上步骤,你应该能够在 Docker 容器中使用 WeasyPrint 导出包含自定义字体的 PDF 文件。
领取专属 10元无门槛券
手把手带您无忧上云