pdfkit生成pdf文件的方式:
① pdfkit.from_string() # 将字符串转成pdf文件,如果字符串是html代码,pdf也是识别的
② pdfkit.from_file() # 将文件转成pdf文件
③ pdfkit.from_url() # 将网址的整个内容转成pdf文件
生成pdf代码样例:
# info 代表文件路径
# e_file_path 代表生成的pdf具体路径
# 如果output_path=False 代表返回一个字符串
result = pdfkit.from_file(info, output_path=e_file_path, configuration=config)
由于pdfkit生成pdf是依赖于wkhtmltopdf,而wkhtmltopdf是整个依赖包的级别是轻量软件级别的,所有需要安装wkhtmltopdf软件,安装完成之后,拿到wkhtmltopdf运行的路径
如:C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe
path_wk = "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"
config = pdfkit.configuration(wkhtmltopdf=path_wk)
生成pdf的过程需要注意的坑:
①pdf文件的名称不可以是中文名称,并且文件名字是Unicode编码
e_file_path = "测试.pdf"
pdfkit.from_string(info, e_file_path, configuration=config)
# 由于要生成的pdf文件名是中文,方法不识别中文,抛出字符编码报错,无法生成pdf文件
②不设置字符编码,可能导致pdf内容乱码
# 设置方式
options = {
'encoding': "utf-8"
}
# 也可以设置生成pdf的大小等
options = {
'encoding': "utf-8",
'page-size': 'A4',
'margin-top': '0mm',
'margin-right': '0mm',
'margin-bottom': '0mm',
'margin-left': '0mm'
}
pdfkit.from_string(info, e_file_path, options=options, configuration=config)
③在生成pdf的过程中,引用了css文件样式,是不能引用相对路径的,相对路径的css文件是不识别的,绝对路径css文件在生成pdf的过程中,才是识别的。
a = PROJECT_ROOT + '/static/v3/bk.css'
b = PROJECT_ROOT + '/static/v3/bootstrap.min.css'
c = PROJECT_ROOT + '/static/v3/font-awesome.css'
css = [a, b, c]
result = pdfkit.from_string(info, e_file_path, css=css, configuration=config)
注意:css可以是一个str路径,也可以是一个css路径列表
④生成pdf时,是不识别图标css文件的
⑤如果生成的pdf文件已经存在,在相同目录下生成重复的pdf文件是不会覆盖的,会直接报错
⑥如果成功生成pdf,返回的结果就是True,如果生成pdf失败,返回的并不是False。