gpt4 book ai didi

python - HTML 到 PDF 尺寸不正确

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:16 25 4
gpt4 key购买 nike

我正在尝试使用 Python 自动生成 PDF,并使用 HTML 设置报告样式,然后将其转换为 PDF。我正在使用两个库从 HTML 生成 PDF(pdfkitweasyprint),但我都无法工作。

这是我尝试呈现的 HTML 代码:

<!DOCTYPE html>

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style>
html {
min-width: 100%;
min-height: 100%;
}

body {
width: 816px;
height: 1056px;
}
</style>
<title>Monthly Report</title>
</head>
<body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="width: 100% !important;">
<h2 style="text-align: center">MONTHLY REPORT</h2>
<img src="static/company1_logo.png" height="56" width="150"/>
<img src="static/company2_logo.png" style="float: right" height="56" width="137"/>
</body>
</html>

这是我在 pdfkit 中使用的内容:

import pdfkit
pdfkit.from_file('test.html', 'test.pdf')

输出的 PDF 尺寸极小,几乎难以阅读。 weasyprint 的替代方案:

pdf = HTML('test.html').write_pdf()
with open('test.pdf', 'wb') as f:
f.write(pdf)

这看起来更好,但它只是松散地遵循我的CSS(即图像没有调整大小,上边距不能改变)。有没有办法创建一个可以轻松转换为 PDF 的 HTML 页面/我做错了什么?

最佳答案

pdfkit 中,它是 wkhtmltopdf 的包装器dpi 值默认设置为 96

要生成高质量的可打印 PDF,请尝试在 pdfkit 的 options 中使用 300 到 400 之间的 dpi 值。

以下内容帮助了我

options = {
'dpi': 365,
'page-size': 'A4',
'margin-top': '0.25in',
'margin-right': '0.25in',
'margin-bottom': '0.25in',
'margin-left': '0.25in',
'encoding': "UTF-8",
'custom-header' : [
('Accept-Encoding', 'gzip')
],
'no-outline': None,
}

pdfkit.from_string(soup, file_path, options = options)

关于python - HTML 到 PDF 尺寸不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44444811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com