在WeasyPrint中,您可以通过使用CSS样式表来设置PDF页面的样式
pip install weasyprint
example.html
,并在其中添加以下内容:<!DOCTYPE html>
<html>
<head>
<style>
@page {
size: A4;
margin: 1cm;
font-family: Arial, sans-serif;
font-size: 12pt;
line-height: 1.5;
header: page-header;
footer: page-footer;
}
@page :first {
margin-top: 2cm;
}
h1 {
page-break-before: always;
}
.header {
text-align: center;
font-size: 18pt;
font-weight: bold;
margin-bottom: 1cm;
}
.footer {
text-align: center;
font-size: 9pt;
margin-top: 1cm;
}
p {
text-align: justify;
}
</style>
</head>
<body>
<div class="header">这是页眉</div>
<h1>章节1</h1>
<p>这是一个段落...</p>
<h1>章节2</h1>
<p>这是另一个段落...</p>
<div class="footer">这是页脚</div>
</body>
</html>
在这个示例中,我们定义了一些页面样式,例如:
<h1>
标题,并在其之前插入分页符。from weasyprint import HTML
html_file = 'example.html'
output_file = 'output.pdf'
HTML(html_file).write_pdf(output_file)
这将生成一个名为output.pdf
的PDF文件,其中包含我们在HTML文件中定义的页面样式。
领取专属 10元无门槛券
手把手带您无忧上云