-
2021-05-13 14:14:26
wkhtmltopdf
关于wkhtmltopdf的简介:
wkhtmltopdf主要用于HTML生成PDF。
pdfkit是基于wkhtmltopdf的python封装,支持URL,本地文件,文本内容到PDF的转换,其最终还是调用wkhtmltopdf命令。是目前接触到的python生成pdf效果较好的。
pdfkit
关于pdfkit的简介:
Python和wkhtmltopdf使用webkit引擎将html转变为PDF文件。
Intsall
setup 1
yum
yum install wkhtmltopdf
如果yum找不到,可以手动下载tar.xz文件
wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar -xvf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
cd wkhtmltox/bin
cp ./* /usr/sbin/
setup 2
pip install pdfkit
setup 3
[root@xxx tmp]# wkhtmltopdf -V
wkhtmltopdf 0.12.4 (with patched qt)
使用
input 方式
支持url/file/string的导入。
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')
支持list
pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf')
pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')
支持打开的文件
with open('file.html') as f:
pdfkit.from_file(f, 'out.pdf')
options
自定义设置
options = {
'page-size': 'Letter',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'custom-header' : [
('Accept-Encoding', 'gzip')
]
'cookie': [
('cookie-name1', 'cookie-value1'),
('cookie-name2', 'cookie-value2'),
],
'no-outline': None,
'outline-depth': 10,
}
pdfkit.from_url('http://google.com', 'out.pdf', options=options)
引用css
# Single CSS file
css = 'example.css'
pdfkit.from_file('file.html', options=options, css=css)
# Multiple CSS files
css = ['example.css', 'example2.css']
pdfkit.from_file('file.html', options=options, css=css)
支持中文字符
需要找一台有安装了中文字体的电脑复制一份字体文件(就是/usr/share/fonts下的文件),然后操作就可以了。
需要在html的字符集设置为utf8
参考资料
更多相关内容 -
SVG-to-PDFKit:将SVG插入使用PDFKit创建的PDF文档中
2021-05-12 04:17:48SVG到PDFKit 将SVG插入使用PDFKit创建的PDF文档中。 安装 npm install svg-to-pdfkit --save 用 SVGtoPDF(doc, svg, x, y, options); 如果愿意,可以将函数添加到PDFDocument原型中: PDFDocument.prototype.... -
PDFKit 一个适用于Node和浏览器的JavaScript PDF生成库-javascript
2021-06-21 10:28:08PDFKit 一个适用于Node和浏览器的JavaScript PDF生成库 PDFKit 一个用于 Node 和浏览器的 JavaScript PDF 生成库。 描述 PDFKit 是一个用于 Node 和浏览器的 PDF 文档生成库,可以轻松创建复杂的多页可打印文档。 ... -
PDFKit-node操作pdf
2018-08-14 12:12:58PDFKit is a PDF document generation library for Node and the browser that makes creating complex, multi-page, printable documents easy. It's written in CoffeeScript, but you can choose to use the API... -
PdfKit:小工具:合并pdf、为pdf自动生成书签
2021-06-24 23:08:07PdfKit 鉴于网上不少影印的PDF没有目录,自己暂时还没找到一个小工具自动生成目录的,就做了这个PdfKit 功能 合并PDF 为PDF生成目录 使用说明 如果是生成书签,则至少说明目录所在页数和内容第一页所在页数,输出原... -
pdfkit-node-certificate-template:Node.js中带有pdfkit的认证模板
2021-05-14 09:21:19Node.js中PDFKit的证书模板 我正在学习如何制作pdf证书,并创建了此模板来帮助其他开发人员。 入门 安装依赖项 yarn 或者 npm install 启动服务器 yarn dev ou npm run dev 打开文件output.pdf 开始编辑... -
pdfkit mac 版本
2020-09-30 11:50:13python 的pdfkit mac版本,母站下载速度感人,所以上传到这里咯。怎么用的话你可以翻一翻啦 很容易找到。 -
react-pdfkit:React renderer用pdfkit生成PDF文档
2021-05-17 14:47:36react-pdfkit React renderer用pdfkit生成PDF文档 -
voilab-pdf-table:PdfKit包装器有助于在简单表中绘制信息
2021-05-03 04:48:33PdfKit包装器有助于在简单表中绘制信息。 安装 npm install --save voilab-pdf-table 用法 // in some service var PdfTable = require ( 'voilab-pdf-table' ) , PdfDocument = require ( 'pdfkit' ) ; module . ... -
如何在iOS中使用pdfkit以编程方式从pdf文件中提取粗体文本?
2021-04-04 08:47:22我正在使用PDFKit显示我的pdf文件。 我已经集成了搜索功能,但是我只想搜索粗体文本/单词。 我想知道是否可以做我正在寻找的东西,或者Apple不允许这样做? 因为String数据类型来自Foundation类,而UIFont来自UIKit... -
pdfkit, 一个用于节点和浏览器的JavaScript PDF生成.zip
2019-10-10 20:28:41pdfkit, 一个用于节点和浏览器的JavaScript PDF生成 PDFKit一个用于节点和浏览器的JavaScript PDF生成。 描述PDFKit是用于节点和浏览器的PDF文档生成库,它使创建复杂。多页面。可以打印文档容易。 它是用tmodel编写... -
swift-BookReader在iOS11上的PDFKit示例代码是一个构建在PDFKit之上的iBooks.app的克隆
2019-08-15 07:08:18BookReader 在iOS 11上的PDFKit示例代码,是一个构建在PDFKit之上的iBooks.app的克隆 -
pdfkit简单使用
2021-02-16 11:08:45import pdfkit from db.users import UserDB config=pdfkit.configuration(wkhtmltopdf=r"D:\softwares\wkhtmltopdf\bin\wkhtmltopdf.exe") options = { 'page-size': 'A4', 'margin-top': '10mm', 'margin-right':...任务:保存
json
格式数据到pdf
表格1. 背景
来源,小练手项目。
请求数据的前端接口为:/get/all/userinfo
采用的后端为flask
,因为后端自定定义了对应的数据获取,这里就直接调用后端的接口:from db.users import UserDB UserDB().getAllUserInfo()
对应的数据库采用mongodb
,删除其余的非相关部分,UserDB
类如下:import pymongo import db.settings as setting class UserDB(object): def __init__(self): # 获取MongoClient对象 self.myclient = pymongo.MongoClient("mongodb://" + setting.DB_HOST + ":" + setting.DB_PORT + "/") # 得到数据库链接 self.mydb = self.myclient[setting.DB_DATABASE_NAME] # 得到user数据库表 self.userTabConnection = self.mydb[setting.DB_TABLE_USERS] def getAllUserInfo(self): return list(self.userTabConnection.find())
而
setting
就是简单的定义了一些配置信息,如:PORT = 4040 HOST = '127.0.0.1' STATIC_FOLDER = 'static' TEMPLATES_FOLDER = 'templates'
在前端的
views
,对应如下定义:@app.route('/get/all/userinfo', methods=["get"]) def getAllUserInfo(): # username = request.args.get("username") results = [] for obj in UserDB().getAllUserInfo(): obj = dict(obj) obj.pop('_id') results.append(obj) return json.dumps({"data": results})
该链接调用:
对应的渲染页面:
而链接地址中的showAll=true
用于在表格中的渲染所有参数,在js
中使用// 来源:链接获取 // 如:http://127.0.0.1:4040/admin/userinfo?username=%E7%8E%8B%E5%88%9A&showAll=true if(window.location.search.split("&")[1] != undefined && window.location.search.split("&")[1].split("=")[0] == 'showAll'){ var showAll = JSON.parse(window.location.search.split("&")[1].split("=")[1]); //保存为pdf的时候,需要显示所有 }else{ var showAll = false; }
来获取到
showAll
参数,然后简单配置逻辑即可。2. 保存
pdf
使用
pdfkit
,参考使用python生成pdf进行安装。这里做简单记录:- 安装
pdfkit
:pip install pdfkit -i https://pypi.douban.com/simple
- 安装
wkhtmltopdf
:https://wkhtmltopdf.org/downloads.html
经过测试,使用
pdfkit.from_url
没有延迟,不能完整加载所有内容,故这里考虑直接使用字符串的格式。import pdfkit from db.users import UserDB config=pdfkit.configuration(wkhtmltopdf=r"D:\softwares\wkhtmltopdf\bin\wkhtmltopdf.exe") options = { 'page-size': 'A4', 'margin-top': '10mm', 'margin-right': '10mm', 'margin-bottom': '10mm', 'margin-left': '10mm', 'orientation':'Landscape', #横向 'encoding': "UTF-8", 'no-outline': None, 'footer-right':'[page]' #设置页码 } HTML = "<center style='margin-bottom: 20px;'><h1>总用户信息</h1></center><table class='mytable'><tr class='mytable-th'><td>用户ID</td><td>用户姓名</td><td>性别</td><td>电话</td><td>QQ</td><td>微信</td><td>用户角色</td><td>所属部门</td><td>直接领导</td></tr>" kehu_num = 0 datas = list(UserDB().getAllUserInfo()) for i in range(len(datas)): if datas[i]['role'] == "客户": kehu_num += 1 HTML += "<tr class='mytable-tr'><td>"+str(i+1)+"</td><td>"+datas[i]['username']+\ "</td><td>"+datas[i]['sex']+"</td><td>"+datas[i]['phone']+"</td><td>"+datas[i]['qq']+\ "</td><td>"+datas[i]['weichat']+"</td><td>"+datas[i]['role']+"</td><td>"+datas[i]['department']+\ "</td><td>"+datas[i]['superior']+"</td></tr>" HTML += "<div style='font-size: 1.2rem;margin-top: 20px;margin-bottom: 20px;'>用户总数量:"+str(len(datas))+",客户数量:"+str(kehu_num)+",职工数量:"+str(len(datas)-kehu_num)+"</div>" pdfkit.from_string(HTML, "Test.pdf", options=options, css="randerTable.css", configuration=config)
打开
pdf
查看效果:
附
css
文件.mytable{ line-height: 30px; width: 100%; border: 1px solid #CCCCCC; } .mytable-th{ background: #EEEEEE; border-bottom: 1px solid #B2B2B2; } .mytable-th td{ padding: 5px 20px; font-size: 1.2rem; font-weight: bold; color: #4E5465; text-align: center; border-left: 1px solid #EEEEEE; border-top: 1px solid #EEEEEE; } .mytable-tr:hover{ background: #CCCCCC; } .mytable-tr td{ padding: 5px 20px; font-size: 1.2rem; color: #333333; text-align: center; border-left: 1px solid #EEEEEE; border-top: 1px solid #EEEEEE; } .mytable-tr td::selection{ background: #000000; color: white; } .mytable-th td:first-child input, .mytable-tr td:first-child input{ width: 15px; height: 15px; } .mytable-th td:first-child, .mytable-tr td:first-child{ padding: 5px 8px; } .mytable-tr td:last-child span{ display: inline-block; margin-left: 10px; padding: 1px 5px; border-radius: 3px; color: white; font-size: 0.9rem; cursor: pointer; /* 设置可选择属性 */ -moz-user-select:none; -o-user-select:none; -webkit-user-select:none; -ms-user-select:none; user-select:none; letter-spacing: 0.2rem; } .mytable-tr td:last-child span:first-child{ margin-left: 0; background: #009688; } .mytable-tr td:last-child span:first-child:hover{ background: #037E74; color: #EEEEEE; } .mytable-tr td:last-child span:last-child{ margin-right: 0; background: #EB7350; } .mytable-tr td:last-child span:last-child:hover{ background: #BC4827; color: #EEEEEE; } .mytable-header{ background: #CCCCCC; height: 50px; text-align: left; display: flex; flex-direction: row; border: 2px solid #CCCCCC; margin-bottom: 10px; } .mytable-header-left, .mytable-header-right{ flex: 1; } .mytable-header-right{ text-align: right; } .mytable-header span{ display: inline-block; line-height: 30px; margin-top: 10px; padding-left: 8px; padding-right: 8px; border-radius: 5px; color: white; /* 设置可选择属性 */ -moz-user-select:none; -o-user-select:none; -webkit-user-select:none; -ms-user-select:none; user-select:none; letter-spacing: 0.2rem; margin-left: 5px; cursor: pointer; } .mytable-header .mytable-header-left span:first-child:hover{ background: #087167; color: #EEEEEE; } .mytable-header .mytable-header-left span:first-child{ background: #009688; } .mytable-header .mytable-header-left span:last-child:hover{ background: #6C6C6C; color: #EEEEEE; } .mytable-header .mytable-header-left span:last-child{ background: #999999; } .mytable-header .mytable-header-left span:nth-child(2):hover{ background: #8E2108; color: #EEEEEE; } .mytable-header .mytable-header-left span:nth-child(2){ background: #CB2D01; } .mytable-header .mytable-header-right span:hover{ background: #1C6F36; } .mytable-header .mytable-header-right span{ background: #41A863; margin-right: 10px; } .mytable-header .mytable-header-right input{ border: none; outline:none; height: 24px; border-radius: 5px; width: 200px; padding-left: 5px; } .mytable-bottom{ margin-top: 5px; display: flex; flex-direction: row; font-size: 1.2rem; padding-bottom: 10px; } .mytable-bottom-left{ flex: 1; } .mytable-bottom-right{ flex: 1; text-align: center; height: 40px; } .mytable-bottom-left span, .mytable-bottom-right span{ display: inline-block; margin-left: 10px; height: 30px; line-height: 30px; margin-top: 5px; cursor: pointer; } .mytable-bottom-left span:first-child{ margin-left: none; margin-right: 10px; color: #555; font-weight: bold; } .mytable-bottom-left span input{ width: 2rem; } .mytable-bottom-left span:last-child:hover{ background: #08675F; } .mytable-bottom-left span:last-child{ background: #009688; padding: 2px 5px; height: 30px; line-height: 30px; border-radius: 5px; color: white; } .selected{ background: #BC4827; color: white; padding: 2px 5px; border-radius: 2px; } #page-reset:hover{ background: #BC401F; } #page-reset{ background: #EB7350; margin-left: 0; }
- 安装
-
PDFKit一个适用于Node和浏览器的JavaScriptPDF生成库
2019-08-08 07:13:47PDFKit 一个适用于Node和浏览器的JavaScript PDF生成库 -
python 使用pdfkit生成
2022-04-28 17:20:21import pdfkit import json import requests import time import os from PyPDF2 import PdfFileReader, PdfFileWriter from reportlab.lib.units import cm from reportlab.pdfgen import canvas # 将wkhtmltopdf...用python生成pdf,记录一下。
import pdfkit import json import requests import time import os from PyPDF2 import PdfFileReader, PdfFileWriter from reportlab.lib.units import cm from reportlab.pdfgen import canvas # 将wkhtmltopdf.exe程序绝对路径传入config对象 path_wkthmltopdf = r'D:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) pdfkit_options = {'encoding': 'UTF-8'} filename="daytest.pdf" str_content="" contents="" description="" def start(offset_dynamic_id): global str_content,contents,description url="https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?visitor_uid=283857977&host_uid=192450084&offset_dynamic_id="+str(offset_dynamic_id)+"&need_top=1&platform=web" headers={ "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36" } r=requests.get(url,headers=headers) r.encoding="utf8" j=json.loads(r.text) lens_cards = len(j['data']['cards']) tmp="" for i in range(lens_cards-1,-1,-1): jj=json.loads(j['data']['cards'][i]['card']) if 'item' in jj: if 'timestamp' in jj['item']: timestamp=jj['item']['timestamp'] timeArray = time.localtime(timestamp) formatTime = time.strftime("%Y-%m-%d", timeArray) print (formatTime) if 'upload_time' in jj['item']: timestamp=jj['item']['upload_time'] timeArray = time.localtime(timestamp) formatTime = time.strftime("%Y-%m-%d", timeArray) print (formatTime) if 'content' in jj['item'] and "每日一题" in str(jj['item']['content']): contents=jj['item']['content'].replace("\n","<br>") print(contents) if 'description' in jj['item'] and "解析" in str(jj['item']['description']): description = jj['item']['description'].replace("\n","<br>") print(description) if 'pictures' in jj['item']: pictures= jj['item']['pictures'] lens_pic=len(pictures) print(pictures[0]['img_src']) for pic in range(0,lens_pic): pic_url=pictures[pic]['img_src'] print(pic_url) savepic(formatTime,pic_url,pic) finalcontent = str(contents)+ '<br>' +str(description)+ '<br>' if finalcontent != tmp: str_content = str(str_content)+'<br>' + '<br>' + str(formatTime)+ '<br>' + str(finalcontent) tmp = finalcontent print('--------------------') time.sleep(2) pdfkit.from_string(str_content,filename,configuration=config, options=pdfkit_options) def savepic(filename,imgurl,picname): if os.path.exists("./jx/"+filename): print('exists file!!!') else: os.makedirs("./jx/"+filename) r=requests.get(imgurl).content with open("./jx/"+str(filename)+"/"+str(picname)+'.jpg',"wb") as f: f.write(r) def create_watermark(content): """水印信息""" # 默认大小为21cm*29.7cm file_name = "mark.pdf" c = canvas.Canvas(file_name, pagesize=(21 * cm, 29.7 * cm)) # 移动坐标原点(坐标系左下为(0,0)) c.translate(5 * cm, 10 * cm) # 设置字体 c.setFont("Helvetica", 80) # 指定描边的颜色 c.setStrokeColorRGB(0, 1, 0) # 指定填充颜色 c.setFillColorRGB(0, 1, 0) # 画一个矩形 # c.rect(cm, cm, 7*cm, 17*cm, fill=1) # 旋转45度,坐标系被旋转 c.rotate(30) # 指定填充颜色 c.setFillColorRGB(0, 0, 0, 0.1) # 设置透明度,1为不透明 # c.setFillAlpha(0.1) # 画几个文本,注意坐标系旋转的影响 c.drawString(3 * cm, 0 * cm, content) c.setFillAlpha(0.6) # 关闭并保存pdf文件 c.save() return file_name def add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out): """把水印添加到pdf中""" pdf_output = PdfFileWriter() input_stream = open(pdf_file_in, 'rb') pdf_input = PdfFileReader(input_stream, strict=False) # 获取PDF文件的页数 pageNum = pdf_input.getNumPages() # 读入水印pdf文件 pdf_watermark = PdfFileReader(open(pdf_file_mark, 'rb'), strict=False) # 给每一页打水印 for i in range(pageNum): page = pdf_input.getPage(i) page.mergePage(pdf_watermark.getPage(0)) page.compressContentStreams() # 压缩内容 pdf_output.addPage(page) pdf_output.write(open(pdf_file_out, 'wb')) if __name__ == '__main__': offset_dynamic_id=[ '596643666922248396', '597941412765972945', '599613099937925403','601272168487401677', '602762930168798777','603950931004835873', '605354350221887065','607034021734160739', '610773503734780835','612563418471648514', '613902958643821419','615852422824317201', '616876308669489985','618509839342691948', '620733258013494055','623340530794036514', '625219514568319250','627047177770485970', '628773067432125784','630017972369358854', '632081467918254103','634110127014674434', '635942952759197713','636984997739233283', '638180106740695049','640274045016735745', '642094170555547656','643378455991287863', '645447419045085191','646665497531645972', '648165540655792160','650078922962108425', '652285565245325316','0' ] for i in range(0,len(offset_dynamic_id)): start(offset_dynamic_id[i]) pdf_file_in = filename pdf_file_out = filename+'_watermark.pdf' pdf_file_mark = create_watermark('marks') add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out)
效果
唯一不理想的是,pdfkit不能自己在pdf中插入图片! -
pdfkit 参数解析
2020-12-05 23:48:51前言 总是担心一些被看好的技术文章被删除,一直有想将数据抓取存下来...1、下载wkhtmltopdf安装包,并且安装到电脑上,在系统Path变量中添加wkhtmltopdf的bin路径,以便于pdfkit的调用。 下载地址:https://wkhtmlto前言
总是担心一些被看好的技术文章被删除,一直有想将数据抓取存下来自己想看就看,琢磨看了下抓取存取为pdf,也不做总结了,转载下。
python中将html转化为pdf的常用工具是Wkhtmltopdf工具包,在python环境下,pdfkit是这个工具包的封装类。如何使用pdfkit以及如何配置呢?分如下几个步骤。
1、下载wkhtmltopdf安装包,并且安装到电脑上,在系统Path变量中添加wkhtmltopdf的bin路径,以便于pdfkit的调用。
下载地址:https://wkhtmltopdf.org/downloads.html
请根据自己的系统版本,选择合适的安装包。如果没有装C语言库,建议选择Windows下的第二种。
2、在pycharm中安装pdfkit库,过程就不介绍啦,前面讲过类似的内容。pip install pdfkit
3、在pycharm中安装whtmltopdf库。
pip install wkhtmltopdf
这个和第一步中的安装包是两个东西,请区别开来。
用法简介
对于简单的任务来说,代码很easy,比如:
import pdfkit pdfkit.from_url('http://baidu.com','out.pdf') pdfkit.from_file('test.html','out.pdf') pdfkit.from_string('Hello!','out.pdf')
pdfkit包含的方法很少,主要用的就是这三个,我们简单看一下每个函数的API:
from_ulr()
def from_url(url, output_path, options=None, toc=None, cover=None, configuration=None, cover_first=False): """ Convert file of files from URLs to PDF document :param url: url可以是某一个url也可以是url的列表, :param output_path: 输出pdf的路径,如果设置为False意味着返回一个string Returns: True on success """ r = PDFKit(url, 'url', options=options, toc=toc, cover=cover, configuration=configuration, cover_first=cover_first) return r.to_pdf(output_path)
from_file()
def from_file(input, output_path, options=None, toc=None, cover=None, css=None, configuration=None, cover_first=False): """ Convert HTML file or files to PDF document :param input: 输入的内容可以是一个html文件,或者一个路径的list,或者一个类文件对象 :param output_path: 输出pdf的路径,如果设置为False意味着返回一个string Returns: True on success """ r = PDFKit(input, 'file', options=options, toc=toc, cover=cover, css=css, configuration=configuration, cover_first=cover_first) return r.to_pdf(output_path)
from_string()
def from_string(input, output_path, options=None, toc=None, cover=None, css=None, configuration=None, cover_first=False): #类似的,这里就不介绍了 r = PDFKit(input, 'string', options=options, toc=toc, cover=cover, css=css, configuration=configuration, cover_first=cover_first) return r.to_pdf(output_path)
举几个栗子
我们可以传入列表:
pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf') pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')
我们可以将一个打开的文件对象传进去:
with open('file.html') as f: pdfkit.from_file(f, 'out.pdf')
如果我们想继续操作pdf,可以将其读取成一个变量,其实就是一个string变量。
# Use False instead of output path to save pdf to a variable pdf = pdfkit.from_url('http://google.com', False)
指定pdf的格式
我们可以指定各种选项,就是上面三个方法中的options。
具体的设置可以参考https://wkhtmltopdf.org/usage/wkhtmltopdf.txt 里面的内容。
我们这里只举个栗子:options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'custom-header' : [ ('Accept-Encoding', 'gzip') ] 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'no-outline': None } pdfkit.from_url('http://google.com', 'out.pdf', options=options)
默认的,pdfkit会show出所有的output,如果你不想使用,可以设置为quite:
options = { 'quiet': '' } pdfkit.from_url('google.com', 'out.pdf', options=options)
我们还可以传入任何html标签,比如:
body = """ <html> <head> <meta name="pdfkit-page-size" content="Legal"/> <meta name="pdfkit-orientation" content="Landscape"/> </head> Hello World! </html> """ pdfkit.from_string(body, 'out.pdf') #with --page-size=Legal and --orientation=Landscape
改进
有了上面的知识之后,我们大可以尝试一下,如果将之前的save_file方法做一些改变,就能够实现我们下载PDF的目标啦。
我们将方法名改成save_to_pdf,并且在get_body方法中直接返回str(div),而不是div.text。代码如下:def save_to_pdf(url): ''' 根据url,将文章保存到本地 :param url: :return: ''' title=get_title(url) body=get_Body(url) filename=author+'-'+title+'.pdf' if '/' in filename: filename=filename.replace('/','+') if '\\' in filename: filename=filename.replace('\\','+') print(filename) options = { 'page-size': 'Letter', 'encoding': "UTF-8", 'custom-header': [ ('Accept-Encoding', 'gzip') ] } #本来直接调用pdfkid的from方法就可以了,但是由于我们的wkhtmltopdf安装包有点问题,一直没法搜到,所以只能用本办法,直接配置了wk的地址 #尴尬了,主要是一直没法下载到最新的wk,只能在网上down了旧版本的。有谁能下到的话发我一份。。。 config=pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe') pdfkit.from_string(body,filename,options=options,configuration=config) print('打印成功!')
哈哈,成功了,下载了这么多pdf,回头慢慢看就可以了。
常见错误:
IOError: No wkhtmltopdf executable found:
python使用pdfkit中,如果使用pdfkit.from_url 或者pdfkit.from_string等,就会出现上述错误。而且如果你使用pip安装了 wkhtmltopdf,还是会出现这个问题:
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf -
因此需要去安装windows版本的wkhtmltopdf
此处进入下载网址
安装完成之后需要在代码中添加以下内容:path_wk = r'C:\Python27\wkhtmltopdf\bin\wkhtmltopdf.exe' #安装位置 config = pdfkit.configuration(wkhtmltopdf = path_wk) pdfkit.from_url(url, 'taobao.pdf', configuration=config)
IOError: ‘Command Failed’
如果出现这个错误意味着 PDFKit不能处理一个输入。你可以尝试直接在错误信息后面直接运行一个命令来查看是什么导致了这个错误 (某些版本的 wkhtmltopdf会因为段错误导致处理失败
===============================================
1.首先,使用谷歌浏览器打开要保存的页面,例如本人打开了学习python的一个网页。
2. 在浏览器右上角,点击“自定义及控制Google Chrome”标签,在弹出的下拉菜单中选择“打印”;或使用快捷键“Crtl+P”调出此菜单。
3. 在弹出的打印设置及预览页面,在页面右侧的“目标打印机”选项处点击“更改”,默认为设置连接的实际打印机。
4. 在弹出的“选择打印机”窗口,在本地目标打印机的管理框里面选择“另存为PDF”选项。
5. 之后还可以具体设置打印的细节,如“页码“,”布局“,”纸张尺寸“,”边距“和”选项“的设置。
6. 设置好之后选择”保存“按钮,在弹出的窗口填写好文件名称,就可以保存了。本文参考:https://www.cnblogs.com/xingzhui/p/7887212.html
https://blog.csdn.net/sinat_20280061/article/details/51674605
https://jingyan.baidu.com/article/546ae1853b1eb51148f28c6e.html转载原文: https://blog.csdn.net/xc_zhou/article/details/80952168
-
pdfkit
2019-06-06 15:08:15pdfkit参考:http://blog.sina.com.cn/s/blog_725d6c650102x2k4.html https://www.cnblogs.com/niejinmei/p/8157680.html https://www.cnblogs.com/xingzhui/p/7887212.html 遇到的问题:... -
Tallcomponents_PDFKit.NET_5.0.49.0_Downloadly.ir.rar
2019-05-19 13:02:32Tallcomponents_PDFKit.NET_5.0.49.0_Downloadly.ir.rar` -
Ruby-Pdfkit使用命令行工具wkhtmltopdf将HTMLCSS转成PDF
2019-08-15 11:47:59Pdfkit - 使用命令行工具wkhtmltopdf将HTML CSS转成PDF -
pdfkit:用于Node和浏览器JavaScript PDF生成库
2021-02-27 18:02:44PDFKit是用于Node和浏览器的PDF文档生成库,可轻松创建复杂的多页可打印文档。 该API包含可链接性,并且包括低级功能以及用于高级功能的抽象。 PDFKit API设计得很简单,因此生成复杂的文档通常和几个函数调用一样... -
python包-pdfkit(wkhtmltopdf) 将HTML转换为PDF
2022-04-20 14:30:26pdfkit,把HTML+CSS格式的文件转换成PDF格式文档的一种工具。它就是html转成pdf工具包wkhtmltopdf的Python封装。所以,必须手动安装wkhtmltopdf。 -
1、PDFKit 简介(PDF 中文手册)
2020-08-03 16:30:59对 iOS 版 PDFKit 的介绍 过去这 12 个月里 我们做了许多改动 我们特别激动地想让大家 看到所有的改动 所有的重大改进 但在开始前 先介绍一下自己 我叫 Jeremy Bridon 是 Apple 的软件工程师 负责核心图形的工作 ... -
pdfkit-demo.zip
2021-03-12 16:15:34PDFKit 绘制+签名,iOS 11+(UI适配了iPad,iPhone未做处理) 实现功能: 在PDF文件上任意手写,添加文本图片注释、移动缩放删除复制文本图片注释,撤回、反撤回、保存新PDF等 -
pdfkit批量转换html文件为pdf
2022-04-28 15:18:15本文仅涉及使用pdfkit包的from_file函数将多个HTML文件转换为一个或多个于html文件对应的pdf文件,并给出了解决程序抛出OSError: wkhtmltopdf reported an error:Exit with code 1 due to network error: ... -
pdfkit:Ruby宝石,可使用命令行实用程序wkhtmltopdf将HTML + CSS转换为PDF
2021-02-01 01:05:41PDF套件 ... 支持的版本 Ruby 2.5、2.6 Rails 4.2、5.2、6.0 ...kit = PDFKit . new ( html , :page_size => 'Letter' ) kit . stylesheets << '/path/to/css/file' # Get an inline PDF pdf = kit . to_pdf -
pdfkit生成pdf,可用于notebook
2022-04-06 18:43:391.安装pdfkit库 在命令行中输入如下命令 pip install pdfkit 出现上面的Successfully installed pdfkit-0.6.1提示,说明安装成功了 2.安装wkhtmltopdf.exe文件 pdfkit是基于wkhtmltopdf的python封装,所以需要安装... -
【采坑日记】Linux Server下使用PDFKit生成pdf文件
2021-03-02 11:12:02这个第三方库是Ruby PDFKit库的改编版本,实际上是对wkhtmltopdf进行的一次封装。所以,在使用这个库时,应该也安装上wkhtmltopdf库。 安装 1. Install python-pdfkit: $ pip install pdfkit (or pip3 for python3)... -
〖Python自动化办公篇⑪〗- word文件自动化 - word 转 PDF(pdfkit与pydocx相结合)
2022-05-16 21:54:49代码示例如下: # coding:utf-8 import pdfkit # 需安装 pdfkit 第三方包 "pip install pdfkit" 以及第三方依赖 "wkhtmltopdf" pdfkit.from_url('https://www.163.com', 'test1.pdf') 运行结果如下: 字符串生成pdf... -
pdfkit 中文乱码问题
2021-12-21 16:17:22原文链接: pdfkit 中文乱码问题 上一篇: ...