PDFKIT使用css禁用部分class导致白边的处理

通过设置CSS和pdfkit的选项来处理(测试有效)

必须安装wkhtmltopdf https://wkhtmltopdf.org/downloads.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# PDF 生成选项
options = {
'margin-top': '0',
'margin-right': '0',
'margin-bottom': '0',
'margin-left': '0',
'page-size': 'A4',
'encoding': 'UTF-8',
'no-outline': None,
'quiet': '',
# 禁用页眉页脚
'no-header-line': '',
'no-footer-line': '',
'disable-smart-shrinking': '',
# 自定义页面大小
'page-width': '210mm', # A4纸宽度
'page-height': '297mm' # A4纸高度
}

# CSS样式
css = '''
@page {
margin: 0;
padding: 0;
}
body {
margin: 0;
padding: 0;
}
/* 隐藏元素 */
.news_release_btn,
.hot_news2,
.good_author {
display: none !important;
}
'''

# 使用pdfkit生成PDF
pdfkit.from_url(url, output_path,
options=options,
css=css)

如果还有白边,可以尝试以下方法:

1.直接在HTML中添加内联样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 在HTML内容中添加样式
html_content = '''
<style>
* {
margin: 0 !important;
padding: 0 !important;
}
@page {
margin: 0;
size: A4;
}
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
''' + original_html

pdfkit.from_string(html_content, output_path, options=options)
  1. 使用自定义纸张大小(测试有效)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    options = {
    'margin-top': '0',
    'margin-right': '0',
    'margin-bottom': '0',
    'margin-left': '0',
    'page-width': '210mm',
    'page-height': '297mm',
    'disable-smart-shrinking': '',
    'zoom': '1.0', # 可以调整缩放比例
    'custom-header': [
    ('Accept-Encoding', 'gzip')
    ],
    'no-outline': None,
    'encoding': 'UTF-8'
    }
  2. 如果是特定元素的白边

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /* 针对特定容器 */
    .container {
    margin: 0 !important;
    padding: 0 !important;
    width: 100% !important;
    max-width: none !important;
    }

    /* 确保图片等内容不会溢出 */
    img {
    max-width: 100%;
    height: auto;
    }

PDFKIT使用css禁用部分class导致白边的处理
https://more678.github.io/2025/02/01/PDF白边解决方式/
作者
tenstrings
发布于
2025年2月1日
许可协议