PDFKIT的使用

1,774 阅读2分钟

pdfkit是python的第三方库,可以将网页、html文件、字符串转成pdf格式。

使用pip命令安装pdfkit库

pip install pdfkit

安装wkhtmltopdf.exe文件

注:pdfkit是基于wkhtmltopdf的python封装,所以需要安装wkhtmltopdf.exe。wkhtmltopdf是轻量级软件,非常很容易安装

下载地址: wkhtmltopdf.org/downloads.h…

下载完成后,一路next,将wkhtmltopdf安装好。

务必要记住安装地址,找到wkhtmltopdf.exe文件所在的绝对路径,后面要用到

使用pdfkit库生成pdf文件

pdfkit可以将网页、html文件、字符串生成pdf文件。

  • 网页url生成pdf【pdfkit.from_url()函数】
# 导入库
import pdfkit

'''将网页url生成pdf文件'''
def url_to_pdf(url, to_file):
    # 将wkhtmltopdf.exe程序绝对路径传入config对象
    path_wkthmltopdf = r"E:/wkhtmltopdf/bin/wkhtmltopdf.exe"
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_url(url, to_file, configuration=config)
    print('完成')


url_to_pdf(r'https://www.baidu.com', 'out_1.pdf')
  • html文件生成pdf【pdfkit.from_file()函数】
# 导入库
import pdfkit

'''将html文件生成pdf文件'''
def html_to_pdf(html, to_file):
    # 将wkhtmltopdf.exe程序绝对路径传入config对象
    path_wkthmltopdf = r'E:/wkhtmltopdf/bin/wkhtmltopdf.exe'
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_file(html, to_file, configuration=config)
    print('完成')

html_to_pdf('sample.html','out_2.pdf')
  • 字符串生成pdf【pdfkit.from_string()函数】
# 导入库
import pdfkit

'''将字符串生成pdf文件'''
def str_to_pdf(string, to_file):
    # 将wkhtmltopdf.exe程序绝对路径传入config对象
    path_wkthmltopdf = r'E:/wkhtmltopdf/bin/wkhtmltopdf.exe'
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_string(string, to_file, configuration=config)
    print('完成')

str_to_pdf('This is test!','out_3.pdf')

pdfkit的部分配置

  • 导入css文件

在使用pdfkit时,我们可以通过配置css文件自定义pdf的排版样式

css = r'E:\work\my_aleks\webapps\quiz\templates\quizReport.css'
pdfkit.from_file('xx.html', 'xx.pdf', configuration=config, css=css)
  • options

通过配置相关options调整生成的pdf页面

options = {
        'quiet': '',
        'dpi': 75,
        'javascript-delay': '2000',  # 延时2s,echarts画图需要时间
        'minimum-font-size': '24',  # 字体大小
        'footer-right': 'xx有限公司',  # 页脚
        'footer-font-size': 10,  # 页脚字体大小
        'footer-spacing': 20,  # 页脚距离正文距离
        'footer-line': '',  # 页脚显示与正文分割线
        'margin-bottom': 25,  # 正文与底部距离
        'encoding': 'UTF-8',
        'image-quality': 500  # 当使用 jpeg 算法压缩图片时使用这个参数指定的质量(默认为 94)  解决分式位置上移问题,原因不清楚,猜测:公式被转成类似图片
        # 'no-pdf-compression': '',
    }
   
 pdfkit.from_file('xx.html', 'xx.pdf', configuration=config, options=options)

使用中的问题

  • pdf截断问题

在使用pdfkit把html转为pdf格式时,会遇到类似表格截断问题

image-20210726112944212.png

在html中添加类的css可以解决这个问题

.truncation {
            page-break-inside: avoid !important;
        }
在表格外层套一层div加上这个类

image-20210726113057479.png

  • pdf文件名问题

pdf保存的文件名不可以带特殊字符,包括-,_,否则会报错

相关链接

PDFKIT官网:pdfkit.org/

WKHTMLTOPDF参数详解:wkhtmltopdf.org/usage/wkhtm…

WKHTMLTOPDF参数详解中文: www.cnblogs.com/chenjunwu/p…