You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用pdfkit将HTML转PDF时自定义移动端适配页面尺寸的方法

关于pdfkit自定义移动端PDF尺寸的两种实现方式

嘿,其实你完全可以直接在from_file方法里设置自定义PDF尺寸,不过你的代码里有个小细节需要调整——因为pdfkit底层依赖的wkhtmltopdf,对于自定义页面尺寸,需要用page-width和page-height这两个独立参数,而不是把宽高放进page-size数组里。page-size参数一般是用来指定预设尺寸(比如A4、Letter这类)的。

方法一:直接在from_file中设置自定义尺寸

修正你的options配置,把自定义宽高拆成单独的参数,同时明确单位(比如像素px,避免默认单位歧义),完整代码如下:

import pdfkit

# 假设你已经定义了config对象
config = pdfkit.configuration(wkhtmltopdf='你的wkhtmltopdf路径')

# 修正后的options:用page-width和page-height定义自定义尺寸
options = {
    'page-width': '400px',
    'page-height': '800px',
    'margin-top': '0.0in',
    'margin-right': '0.0in',
    'margin-bottom': '0.0in',
    'margin-left': '0.0in',
    'encoding': "UTF-8",
    'custom-header': [('Accept-Encoding', 'gzip')],
    'no-outline': None
}

# 直接用from_file生成指定尺寸的PDF
pdfkit.from_file('test1.html', 'out1.pdf', configuration=config, options=options)

方法二:先创建PDF对象再添加内容

如果你更倾向于先初始化PDF实例再操作,也可以通过PDFKit类来实现,本质和from_file是一致的,代码示例:

import pdfkit

config = pdfkit.configuration(wkhtmltopdf='你的wkhtmltopdf路径')
options = {
    'page-width': '400px',
    'page-height': '800px',
    # 其他同上面的options配置
}

# 创建PDF对象,指定源文件类型为'file'
pdf = pdfkit.PDFKit('test1.html', 'file', configuration=config, options=options)
# 导出为PDF文件
pdf.to_file('out1.pdf')

额外注意事项

  • 尺寸单位支持px(像素)、mm(毫米)、in(英寸)等,按需选择即可;
  • 为了更好适配移动端阅读,建议同时调整你的HTML内容样式,比如设置body { max-width: 400px; margin: 0 auto; },确保页面内容不会超出PDF宽度;
  • 如果遇到尺寸不生效的情况,可以检查wkhtmltopdf的版本,部分旧版本对自定义参数的支持可能有差异。

内容的提问来源于stack exchange,提问作者Ullsokk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:15:32