- 一、html转换成pdf工具-wkhtmltopdf
- 1. 什么是wkhtmltopdf
- 2. 如何使用它?
- 3. 常见问题
- error while loading shared libraries: libjpeg.so.62: cannot open shared object file: No such file or
- 下载安装字体文件(缺少字体会导致生成的PDF文件里的中文都是方块)
- 二、Python生成PDF(pdfkit库)
- 1. 网页生成 pdf【pdfkit.from_url()函数】
- 2. html 文件生成 pdf【pdfkit.from_file()函数】
- 3. 字符串生成 pdf【pdfkit.from_string()函数】
- 三、参考
官网:https://wkhtmltopdf.org/
1. 什么是wkhtmltopdfwkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely “headless” and do not require a display or display service.
wkhtmltopdf 和 wkhtmltoimage 是开源 (LGPLv3) 命令行工具,可使用 Qt WebKit 渲染引擎将 HTML 渲染为 PDF 和各种图像格式。 这些完全“headless”运行,不需要界面或界面服务。
如果您喜欢,它还是一个 C 库。
2. 如何使用它?wkhtmltopdf是 “命令行工具” ,支持多个平台,可在win,linux,os x 等系统下运行。
-
下载预编译的二进制文件或从源代码构建
-
创建要转换为 PDF(或图像)的 HTML 文档
-
通过该工具运行您的 HTML 文档。
问题描述:
执行 wkhtmltopdf -V 报错 error while loading shared libraries: libjpeg.so.62: cannot open shared object file: No such file or directory
解决方法:
apt-get install libjpeg62-dev
下载安装字体文件(缺少字体会导致生成的PDF文件里的中文都是方块)①yum install -y fontconfig mkfontscale 或者
apt-get -y install fontconfig xfonts-utils
② 下载字体文件(TTF文件)放入/usr/share/fonts
③ 执行三个命令
mkfontscale
mkfontdir
fc-cache
- 使用pip安装pdfkit库
pip3 install pdfkit
- 安装wkhtmltopdf文件
注:pdfkit是基于wkhtmltopdf的python封装,所以需要安装wkhtmltopdf。wkhtmltopdf是轻量级软件,非常很容易安装。
下载地址: https://wkhtmltopdf.org/downloads.html
- 使用pdfkit库生成pdf文件
pdfkit可以将网页、html文件、字符串生成pdf文件!
# 导入库
import pdfkit
'''将网页生成pdf文件'''
def url_to_pdf(url, to_file):
# 将wkhtmltopdf.exe程序绝对路径传入config对象
path_wkthmltopdf = r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
# 生成pdf文件,to_file为文件路径
pdfkit.from_url(url, to_file, configuration=config)
print('完成')
# 这里传入我知乎专栏文章url,转换为pdf
url_to_pdf(r'https://zhuanlan.zhihu.com/p/69869004', 'out_1.pdf')
2. html 文件生成 pdf【pdfkit.from_file()函数】
# 导入库
import pdfkit
'''将html文件生成pdf文件'''
def html_to_pdf(html, to_file):
# 将wkhtmltopdf.exe程序绝对路径传入config对象
path_wkthmltopdf = r'D:\Program Files\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')
3. 字符串生成 pdf【pdfkit.from_string()函数】
import pdfkit
def str_to_pdf(string, to_file):
# 将wkhtmltopdf.exe程序绝对路径传入config对象
path_wkthmltopdf = r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
# 生成pdf文件,to_file为文件路径
pdfkit.from_string(string, to_file, configuration=config)
print('完成')
if __name__ == '__main__':
str_to_pdf('This is test!', 'out_str_to_pdf.pdf')
三、参考
Python生成PDF(pdfkit库)
参考URL: https://www.jianshu.com/p/489c3aff61bd/



