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

Python中HTML转PDF异常求助:A4发票渲染不一致

解决A4发票HTML转PDF渲染不一致问题

问题概述

用Python airium库生成的A4发票在HTML页面显示正常,但转PDF时出现两个问题:

  • WeasyPrint转换:部分内容被截断
  • PdfKit+wkhtmltopdf转换:发票号位置偏移

针对WeasyPrint内容截断的解决方案

  1. 强制指定A4页面规格
    在HTML的<head>中添加CSS,明确页面尺寸与边距,防止内容溢出:

    @page {
      size: A4;
      margin: 2cm; /* 根据实际布局调整 */
    }
    body {
      width: 210mm;
      height: 297mm;
      margin: 0 auto;
      box-sizing: border-box;
    }
    

    确保所有容器宽度不超过210mm - 2*边距。

  2. 控制分页行为
    添加CSS避免区块内容被分页截断:

    .invoice-block {
      page-break-inside: avoid;
    }
    .force-page-break {
      page-break-after: always;
    }
    
  3. 优化WeasyPrint调用
    在代码中直接传入页面样式参数:

    from weasyprint import HTML, CSS
    
    path = r"C:\Users\Administrateur\data\Dev\"
    input_html = path + "invoice.html"
    output_pdf = path + "invoice.pdf"
    
    # 直接指定页面样式
    page_css = CSS(string='@page { size: A4; margin: 2cm; }')
    HTML(input_html).write_pdf(output_pdf, stylesheets=[page_css], presentational_hints=True)
    

针对PdfKit+wkhtmltopdf发票号偏移的解决方案

  1. 添加精确转换参数
    禁用智能缩放,强制A4尺寸与边距:

    import pdfkit
    
    path = r"C:\Users\Administrateur\data\Dev\"
    input_html = path + "invoice.html"
    output_pdf = path + "invoice.pdf"
    
    path_wkhtmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"
    config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
    
    # 设置转换参数
    options = {
        'page-size': 'A4',
        'margin-top': '2cm',
        'margin-right': '2cm',
        'margin-bottom': '2cm',
        'margin-left': '2cm',
        'zoom': '1.0',
        'disable-smart-shrinking': ''
    }
    
    pdfkit.from_file(input_html, output_pdf, configuration=config, options=options)
    
  2. 修复定位CSS
    确保发票号的定位参考父元素为相对定位,避免解析偏移:

    .invoice-header {
      position: relative; /* 作为绝对定位的参考容器 */
    }
    .invoice-number {
      position: absolute;
      top: 10mm;
      right: 10mm;
    }
    
  3. 升级wkhtmltopdf版本
    旧版本存在布局解析bug,建议更新至最新稳定版。


通用优化建议

  • 使用mm/cm等相对单位替代px,适配A4尺寸;
  • 避免使用过于复杂的CSS(如部分flex/grid高级特性),确保转换工具兼容;
  • 先在浏览器打印预览(设置A4)中验证HTML布局,再进行PDF转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:40:03