用python实现html转pdf:weasyprint、pdfkit

目录

weasyprint

pdfkit

报错处理

文件转pdf:from_file

URL网页转pdf:from_url

字符串转pdf:from_string

部分参数说明

verbose

toc、cover、cover_first

css


weasyprint

支持将文件、URL、字符串转为pdf,使用weasyprint将html转pdf,代码简单,但是环境配置麻烦,几乎都在报错的路上。

环境配置参考:https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#installation

需要下载安装对应版本的msys:官网下载地址https://www.msys2.org/

运行就报这个错:raise OSError(msg)
OSError: cannot load library 'libgobject-2.0-0': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'libgobject-2.0-0',需要将gtk的bin添加到环境变量path中,或者使用os模块添加。

代码示例:

from weasyprint import HTML
import os

os.add_dll_directory(r'E:\python\gtk-bundle_3.6.4-20130513_win64\bin')


def html_pdf():
    html = HTML(filename='test.html')
    html.write_pdf('test.pdf')


if __name__ == '__main__':
    html_pdf()

pdfkit

报错处理

基本会出现的报错处理:

报错1:

OSError: No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

没有安装或配置wkhtmltopdf程序:

安装包下载地址:https://wkhtmltopdf.org/downloads.html

配置方法,在转pdf时指定configuration参数,如下:

config = pdfkit.configuration(wkhtmltopdf=r'E:\wkhtmltopdf\bin\wkhtmltopdf.exe')

pdfkit.from_file('test.html', 'ts.pdf', configuration=config)

报错2:

OSError: wkhtmltopdf reported an error:
Exit with code 1 due to network error: ProtocolUnknownError

没有设置'enable-local-file-access':True,具体设置见下文中options配置参数。

文件转pdf:from_file

支持将html、TXT、xml文件转为pdf

配置参数:https://wkhtmltopdf.org/usage/wkhtmltopdf.txt

import pdfkit

def html_pdf():
    config = pdfkit.configuration(wkhtmltopdf=r'E:\wkhtmltopdf\bin\wkhtmltopdf.exe')

    options = {
        # 可添加allow、cookie、custom-header、post等参数
        'encoding': 'utf-8',
        'enable-local-file-access': True,
        'page-size': 'A4',  # 设置页面大小为A4
        'dpi': 500,  # 设置分辨率
        'margin-top': '10mm',  # 设置上边距
        'margin-left': '10mm',
        'margin-right': '10mm',
        'margin-bottom': '10mm',
        'no-outline': None,
        'custom-header': [
            ('Accept-Encoding', 'gzip')
        ],
        'cookie': [
            ('cookie-key1', 'cookie-value1'),
            ('cookie-key2', 'cookie-value2')
        ],
        'orientation': 'Landscape'  # 默认横向Portrait,纵向为Landscape
    }

    # 可以传递单个文件或多个文件的列表:
    pdfkit.from_file('test.html', 'ts.pdf', configuration=config, options=options)
    pdfkit.from_file(['test1.html','test2.html','test3.html'], 'ts.pdf', configuration=config, options=options)
    

通过打开文件的方式转换

    with open('test.html', 'r', encoding='utf-8') as f:
        pdfkit.from_file(f, 'test.pdf', configuration=config, options=options)

URL网页转pdf:from_url

    # 可以传递单个URL或多个URL的列表:
    url_list = ['https://cloud.tencent.com', 'https://blog.csdn.net', 'https://fanyi.youdao.com/']
    pdfkit.from_url('https://fanyi.youdao.com/', 'test.pdf', configuration=config, options=options)
    pdfkit.from_url(url_list, 'test.pdf', configuration=config, options=options)

字符串转pdf:from_string

可以通过HTML中的meta标签传递 options的 参数

    html_body = """
        <html>
          <head>
            <meta name="pdfkit-page-size" content="A4"/>
            <meta name="pdfkit-orientation" content="Landscape"/>
            <meta name="pdfkit-encoding" content="utf-8"/>
          </head>
          测试页面打印效果
          </html>
        """
    pdfkit.from_string('测试字符串转pdf', 'str_to_pdf.pdf', configuration=config, options=options)
    pdfkit.from_string(html_body, 'test1.pdf', configuration=config)  # 可以通过HTML中的meta标签传递 options的 参数

部分参数说明

在from_file、from_url、from_string中可使用的其他参数介绍

verbose

可在API调用中传递verbose=True,获取wkhtmltopdf的报错说明

pdfkit.from_url('https://mp.csdn.net/', 'out.pdf', verbose=True, configuration=config)

toc、cover、cover_first

由于toc和cover选项必须分开指定,如果需要在toc之前提供封面,要使用cover_first选项

    toc = {
        'xsl-style-sheet': 't.xsl'
    }
    cover = 'c.html'
    pdfkit.from_file('file.html', options=options, toc=toc, cover=cover)
    pdfkit.from_file('file.html', options=options, toc=toc, cover=cover, cover_first=True)
css

在文件或字符串转pdf时,可通过css选项指定外部css文件,支持单个或多个css文件的添加

    # 添加单个css文件
    pdfkit.from_file('file.html', options=options, css='example.css', configuration=config)

    # 添加多个css文件
    css_list = ['example.css', 'example2.css']
    pdfkit.from_file('file.html', options=options, css=css_list, configuration=config)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值