【问题标题】:How to remove margins from PDF? (Generated using WeasyPrint)如何从PDF中删除边距? (使用 Wea​​syPrint 生成)
【发布时间】: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 应用中使用 Wea​​syPrint 生成 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)

【问题讨论】:

  • 您如何使用 Wea​​syprint?
  • 感谢克里斯的回复,我将用于使用 Flask-WeasyPrint 呈现 pdf 文档的代码添加到原始问题中。
  • 这不是我想要的。我要求生成您的 PDF 的 代码。此外,该屏幕截图似乎显示了呈现 HTML 的浏览器。您不应该显示 PDF 吗?
  • 帖子又被编辑了,我想这是你要的代码。生成的 pdf 文档 (element.pdf) 看起来与浏览器中显示的完全一样,带有顶部和侧边距。

标签: python pdf flask margin weasyprint


【解决方案1】:

也许你忘记了“;”或/和“mm”, 它有效:

@page {
        size: A4; /* Change from the default size of A4 */
        margin: 0mm; /* Set margin on each page */
      }

【讨论】:

    猜你喜欢
    • 2018-02-11
    • 2016-12-06
    • 2018-08-05
    • 2021-10-20
    • 2016-09-26
    • 2021-09-23
    • 2020-02-06
    • 2019-06-06
    • 1970-01-01
    相关资源
    最近更新 更多