可以将网页、html文件以及字符串生成pdf文件
准备工作:
安装三方库 pip install pdfkit ,并且还要下载软件。
(默认安装路径)C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe 注:pdfkit是基于wkhtmltopdf的python封装,所以需要安装wkhtmltopdf.exe。
了解参数:
准备工作完成啦!我们了解下参数
pdfkit.from_string('hello,python', 'out.pdf') # 字符串
pdfkit.from_url('https://www.baidu.com/', 'out.pdf') # 网址
pdfkit.from_url(['https://www.baidu.com/', 'https://www.douban.com/'], 'out.pdf') # 多个网址
pdfkit.from_file('test.html', 'out.pdf') # 本地文件
pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf') # 多个文件
也可以传递一个打开的文件:
注意:文件名不得包含特殊字符,否则会报错。
with open('file.html') as f:
pdfkit.from_file(f,'out.pdf')
如果想对生成的PDF作进一步处理,我们可以将其读取到一个变量中:
#设置输出文件为False,将结果赋给一个变量
pdf = pdfkit.form_url('https://www.douban.com/', False)
我们可以制定所有的 wkhtmltopdf 选项 http://wkhtmltopdf.org/usage/wkhtmltopdf.txt. 我们可以移除选项名字前面的 ‘—‘ .如果选项没有值, 使用None, Falseor * 作为字典值
options = {
'quiet': '', # 静默
'page-size': 'Letter', # 纸张大小
'margin-top': '0.75in', # 上下左右的间距
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8", # 防止中文乱码
'no-outline': None # 无边框
}
pdfkit.from_url('https://www.baidu.com/', 'out.pdf', options=options)
举个栗子:
import pdfkit
path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' # 路径
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) # 配置
pdfkit.from_url('https://www.baidu.com/', 'out.pdf', configuration=config) # 注意要加上配置
我们也可以加上参数来控制文档的样式
import pdfkit
path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' # 路径
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) # 配置
options = {
'quiet': '', # 静默
'page-size': 'A4', # 纸张大小
'margin-top': '0.75in', # 上下左右的间距
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
# 'orientation': 'Landscape', # 纸张横向排列
'encoding': "UTF-8", # 防止中文乱码
'no-outline': None # 无边框
}
pdfkit.from_url('https://www.douban.com/', 'out.pdf',
configuration=config, options=options) # 注意要加上配置
print('完成!')
或者我们可以用函数来做
import pdfkit
def url_to_pdf(url, to_file): # 定义函数
path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' # 路径
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) # 配置
pdfkit.from_url(url, to_file, configuration=config)
url = input('请输入网址:')
url_to_pdf(url,
'C:\\Users\\Administrator\\Desktop\\out.pdf') # 传入参数
print('已完成并保存在桌面! ')
strnig、file同理。实际使用过程中也更加灵活多变。
import pdfkit
url = "www.baidu.com" # 定义url和文件名
title = "mypdf"
file_name = title+'.pdf' # 命名
# file_name = './PDF/'+title+'.pdf' # 定义相对路径存储文件
config = pdfkit.configuration(
wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe') # 配置+路径
options = {
'quiet': '', # 静默
'page-size': 'A4', # 纸张大小
'margin-top': '0.75in', # 上下左右的间距
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'orientation': 'Landscape', # 纸张横向排列
'encoding': "UTF-8", # 防止中文乱码
'no-outline': None # 无边框
}
pdfkit.from_url(url, file_name, options=options, configuration=config)
print('完成!')