【发布时间】:2020-01-30 04:42:56
【问题描述】:
我正在尝试在我的 Flask 应用程序中呈现 PDF 文档。为此,我使用以下 HTML 模板:
<!DOCTYPE html>
<html>
<head>
<style>
@page {
margin:0
}
h1 {
color:white;
}
.header{
background: #0a0045;
height: 250px;
}
.center {
position: relative;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align:center;
}
</style>
</head>
<body>
<div class="header">
<div class="center">
<h1>Name</h1>
</div>
</div>
</body>
</html>
我的标题部分的顶部和右侧/左侧不断出现白边:
有没有办法去除它们?
编辑:
以下是在我的 Flask 应用中使用 WeasyPrint 生成 PDF 文件的代码:
def generate_pdf(id):
element = Element.query.filter_by(id=id).first()
attri_dict = get_element_attri_dict_for_tpl(element)
html = render_template('element.html', attri_dict=attri_dict)
pdf = HTML(string=html).write_pdf()
destin_loc = app.config['ELEMENTS_FOLDER']
timestamp = dt.datetime.now().strftime('%Y%m%d%H%M%S')
file_name = '_'.join(['new_element', timestamp])
path_to_new_file = destin_loc + '/%s.pdf' % file_name
f = open(path_to_new_file, 'wb')
f.write(pdf)
filename = return_latest_element_path()
return send_from_directory(directory=app.config['ELEMENTS_FOLDER'],
filename=filename,
as_attachment=True)
【问题讨论】:
-
您如何使用 Weasyprint?
-
感谢克里斯的回复,我将用于使用 Flask-WeasyPrint 呈现 pdf 文档的代码添加到原始问题中。
-
这不是我想要的。我要求生成您的 PDF 的 代码。此外,该屏幕截图似乎显示了呈现 HTML 的浏览器。您不应该显示 PDF 吗?
-
帖子又被编辑了,我想这是你要的代码。生成的 pdf 文档 (element.pdf) 看起来与浏览器中显示的完全一样,带有顶部和侧边距。
标签: python pdf flask margin weasyprint