说起pdf就想到了一款很适用的工具,那就是pdfkit,在前几天的项目中,有一个功能要实现,为了实现这一个功能,于是我大海茫茫中查询各种百科,不负众望的让我找到了我心怡的工具,想必也就是它了。好了废话也不多说了,开始进入高潮部分吧~~~

  1、说明

    pdfkit,把HTML·+ CSS格式的文件转换成PDF格式文档的一种工具。

    其实,它就是html转换成PDF工具包wkhtmltopdf的Python封装,所以,必须安装wkhtmktopdf。一般情况下,wkhtmkltopdf需要手动安装,尤其要注意的是Windows下,需要把wkhtmltopdf的bin执行文件路径添加到PATH变量中。

  2、安装

    请参考《Python抓取网页并保存为PDF》里面各个安装包的安装

  3、API说明   

def from_url(url, output_path, options=None, toc=None, cover=None, configuration=None, cover_first=False):
"""
把从URL获取文件转换为PDF文件 :param url:
URL 或 URL列表
:参数,output_path:
输出PDF文件的路径。如果是参数等于False,意味着文件将会以字符串的形式返回,得到文本文件。
:param options:
(可选) dict with wkhtmltopdf global and page options, with or w/o '--'
:param toc:
(可选) dict with toc-specific wkhtmltopdf options, with or w/o '--'
:param cover:
(可选) string with url/filename with a cover html page
:param configuration:
(可选)实例化 pdfkit.configuration.Configuration()
:param configuration_first:
(optional) if True, cover always precedes TOC 返回值:成功返回True
"""
r = PDFKit(url, 'url', options=options, toc=toc, cover=cover,configuration=configuration, cover_first=cover_first)
return r.to_pdf(output_path)
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:
path to HTML file or list with paths or file-like object
:param output_path:
path to output PDF file. False means file will be returned as string.
:param options:
(optional) dict with wkhtmltopdf options, with or w/o '--'
:param toc:
(optional) dict with toc-specific wkhtmltopdf options, with or w/o '--'
:param cover:
(optional) string with url/filename with a cover html page
:param css:
(optional) string with path to css file which will be added to a single input file
:param configuration:
(optional) instance of pdfkit.configuration.Configuration()
:param configuration_first:
(optional) if True, cover always precedes TOC
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)

  

def from_string(input, output_path, options=None, toc=None, cover=None, css=None, configuration=None, cover_first=False):
"""
Convert given string or strings to PDF document
:param input: string with a desired text. Could be a raw text or a html file
:param output_path: path to output PDF file. False means file will be returned as string.
:param options: (optional) dict with wkhtmltopdf options, with or w/o '--'
:param toc: (optional) dict with toc-specific wkhtmltopdf options, with or w/o '--'
:param cover: (optional) string with url/filename with a cover html page
:param css: (optional) string with path to css file which will be added to a input string
:param configuration: (optional) instance of pdfkit.configuration.Configuration()
:param configuration_first: (optional) if True, cover always precedes TOC
Returns: True on success
""" r = PDFKit(input, 'string', options=options, toc=toc, cover=cover, css=css, configuration=configuration, cover_first=cover_first) return r.to_pdf(output_path)

 

   4、举例说明

   4.1 简单的例子    

import pdfkit 

pdfkit.from_url('https://www.google.com.hk','out1.pdf')
pdfkit.from_file('123.html','out2.pdf')
pdfkit.from_string('Hello!','out3.pdf')

  也可以传递一个url或者文件名列表: 

pdfkit.from_url(['https://www.google.com.hk','https://baidu.com','http://cn.bing.com/'],'out_0.pdf')
pdfkit.from_file(['122.html','123.html'],'out_1.pdf')

  如何你想对生成的PDF作进一步处理,你可以将其读取到一个变量中: 

pdf=pdfkit.from_url('https://www.google.com.hk',False)

  你可以指定所有的 wkhtmltopdf选项 。你可以移除选项名字前面的 ‘–’ .如果选项没有值, 使用None, False或者“*”作为字典值:

在views视图中可以加上options进行页面布局调试 

options = {
'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.google.com.hk','out1.pdf',options=options)

  默认情况下, PDFKit 将会显示所有的wkhtmltopdf输出. 如果你不想看到这些信息,你需要传递一个quiet选项:

options = {'quiet':''}
pdfkit.from_url('https://www.google.com.hk','out1.pdf',options=options)

   由于wkhtmltopdf的命令语法 ,TOC和Cover选项必须分开指定: 

toc={'xsl-style-sheet':'toc.xsl'}
cover='124.html'
pdfkit.from_file('122.html', options=options, toc=toc, cover=cover)

   当你转换文件、或字符串的时候,你可以通过css选项指定扩展的 CSS 文件。

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)

  配置 
       每个API调用都有一个可选的参数。这应该是pdfkit.configuration() API 调用的一个实例。采用configuration 选项作为初始化参数。可用的选项有: 
       wkhtmltopdf——wkhtmltopdf二进制文件所在的位置。默认情况下pdfkit会尝试使用which(在类UNIX系统中) 或where(在Windows系统中)来判断。 
       meta_tag_prefix–pdfkit的前缀指定 meta tags(元标签) - 默认情况是pdfkit- 
       示例 :针对wkhtmltopdf不在系统路径中(不在$PATH里面)  

config=pdfkit.configuration(wkhtmltopdf='/opt/bin/wkhtmltopdf'))   

pdfkit.from_string(html_string, output_file, configuration=config)

配置文件路劲是你当时下载wkhtmltopdf安装的路径,然后把它加入在里面,''out.pdf''可以更改名字,属于pdf文件名。

config = pdfkit.configuration(wkhtmltopdf='C:\\Python27\\wkhtmltopdf\bin\\wkhtmltopdf.exe')
pdfkit.from_url('http://google.com', 'out.pdf')

为了在前端一点击生成pdf下面就是显示pdf文件直接点击查看

#pdf版本导入
def html_str(html_str):
import pdfkit
print "in export pdf"
options = {
'page-size': 'A3',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'no-outline': None
}
# css = {}
config = pdfkit.configuration(wkhtmltopdf='D:\\pdf\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')
file = pdfkit.from_string(html_str, False, options=options, configuration=config)#字符串方式
return file

里面还运用到了django 模板渲染功能,如果是使用字符串方式的话,可以使用这个方法,简单方便。。。。

#pdf调用方式
def export_pdf(request, pk):
quotation_id = pk
t = TemplateResponse(request, 'quotation.html', locals())
t.render()
# print t.content
file = html_str(t.content)
response = StreamingHttpResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="product.pdf"'
return response  

 ps:

  win7 64位系统下,

  第一步:

  下载下面链接中

  https://wkhtmltopdf.org/downloads.html

Windows (MinGW)	0.12.4	32-bit / 64-bit	for Windows XP/2003 or later; standalone
pip install pdfkit    

  安装到路径:

  D:\software\wkhtmltopdf

    打开控制面板

    系统变量Path中加入

  D:\software\wkhtmltopdf\bin

    与其他路径用";"隔开  

  

PDF之pdfkit的更多相关文章

  1. pdfkit html转pdf

    pdfkit的通用option选项 参考:https://cloud.tencent.com/developer/ask/202116https://www.cnblogs.com/taceywong ...

  2. 爬取博主的所有文章并保存为PDF文件

    继续改进上一个项目,上次我们爬取了所有文章,但是保存为TXT文件,查看不方便,而且还无法保存文章中的代码和图片. 所以这次保存为PDF文件,方便查看. 需要的工具: 1.wkhtmltopdf安装包, ...

  3. 学以致用:Python爬取廖大Python教程制作pdf

    当我学了廖大的Python教程后,感觉总得做点什么,正好自己想随时查阅,于是就开始有了制作PDF这个想法. 想要把教程变成PDF有三步: 先生成空html,爬取每一篇教程放进一个新生成的div,这样就 ...

  4. 导出 VuePress构建的网站为 PDF

    前言 学 Rust 也有一段时间了,网上也有不少官方文档的中文翻译版,但是似乎只有 Rust中文网站 文档一直是最新的,奈何并没有 PDF 供直接下载,是在是不太方便,为了方便阅读以及方便后续文档更新 ...

  5. Python将HTML转换为PDF

    Python将HTML转换为PDF 使用pdfkit库和wkhtmltopdf, pip install pdfkit wkhtmltopdflinux中一般需要添加sudo权限. Windows安装 ...

  6. pdfkit

    官方文档 0.准备 需要引入两个包,首先要npm install pdfkit安装pdfkit包 const PDF = require('pdfkit'); const fs = require(' ...

  7. python 爬虫,网页转PDF:OSError: No wkhtmltopdf executable found

    解决办法: 代码中设置参数: path_wk = r‘D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe‘ #wkhtmltopdf安装位置 config ...

  8. 常用的NodeJS模块

    图片处理 1.Manipulate images 官网:http://github.com/aheckmann/gm ImageMagick和GraphicsMagick主要用于图片的创建.编辑.合成 ...

  9. Python之数据处理

    一.CSV数据处理 CSV文件格式:逗号分隔值(Comma-Separated Value,CSV,有时也称为字符分隔值,因为分隔符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本).纯文 ...

随机推荐

  1. EOS 的世界里可能再也没有小偷了

    EOS 针对以下两种情况设计了应急措施: 1. 账户被盗(私钥被盗或有权限的其他账户被盗) 2. 账户遗失(私钥遗失或有权限的其他账户遗失) ## 1.账户被盗 EOS 有可能会强制要求所有账户的 O ...

  2. Java设计模式(五)Prototype原型模式

    一.场景描述 创建型模式中,从工厂方法模式,抽象工厂模式,到建造者模式,再到原型模式,我的理解是,创建对象的方式逐步从编码实现转向内存对象处理. 例如,在“仪器数据采集器”的子类/对象“PDF文件数据 ...

  3. 【转载】Perl中的引用

    为什么使用引用? 在perl4中,hash表中的value字段只能是scalar,而不能是list,这对于有些情况是很不方便的,比如有下面的数据: Chicago, USAFrankfurt, Ger ...

  4. IntelliJ IDEA 2017.1.5迁移eclipse,SSM项目,通过jrebel实现热部署

    1.首先打开idea,配置SVN版本控制器的路径 2.配置maven 3.配置jrebel热部署的路径 4.从svn到出项目 5.配置配置tomacat参数-server -XX:PermSize=1 ...

  5. Acer Aspire E1 471G 加装SSD+机械盘后无法启动的问题

    老笔记本 Acer Aspire E1 471G 加装了一块 SSD 作为系统盘(win10),原机械盘格式化后,装在光驱托架上作为数据盘. 可能会出现: 系统无法启动,显示找不到启动设备,并且在F2 ...

  6. 使用了旧版nuget的.net项目在git中的问题

    曾几何时,使用nuget包管理项目依赖还需要将nuget执行程序及其配置文件包含在项目中. 如上图所示,在解决方案文件夹中,有专门为nuget程序设置的 .nuget 子目录. 当将项目纳入git管理 ...

  7. Mysql的执行计划各个参数详细说明

    执行计划各个参数的说明 1.id 主要是用来标识sql的执行顺序,如果没有子查询,一般来说id只有一个,执行顺序也是从上到下 2.select_type 每个select子句的类型 a:  simpl ...

  8. java.util.zip

    使用java自带的类 java.util.zip进行文件/目录的压缩的话,有一点不足,不支持中文的名件/目录命名,如果有中文名,那么打包就会失败.本人经过一段时间的摸索和实践,发现在一般的Ant.ja ...

  9. 【总结】关于YUV-RGB格式转换的一些个人理解

    这段时间一直在研究YUV的格式问题例如YUV422.YUV420,在网上搜索了很多这方面的资料,发现很多资料讲的东西是重复的,没有比较深入的讲解,所以看了之后印象不是很深,过了一段时间之后又对它们有了 ...

  10. 关于C语言的第0次作业

    1.你认为大学的学习生活.同学关系.师生关系应该是怎样的?请一个个展开描述. 我认为的大学学习生活是充实的,丰富多彩的,与高中快节奏.繁忙的生活有所不同.在上了大学我们都成熟了很多,懂得了包容与忍让, ...