PDF之pdfkit

  说起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 TOCReturns: 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 pdfkitprint "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 = pkt = TemplateResponse(request, 'quotation.html', locals())t.render()# print t.contentfile = 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

    与其他路径用";"隔开  

  

转载于:https://www.cnblogs.com/niejinmei/p/8157680.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/368339.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

015迭代器

注意迭代器和可迭代对象不同#迭代器&#xff1a;1、有iter方法&#xff0c;2、有next方法li[1,2,3,4,5]diter(li) # 等于li.__iter__()print(d) # <list_iteratorobjectat0x00000174316CC3C8>可以通过next方法取出元素。for循环就是这样的。for循环内部做的三件事1、调用…

CSS属性之attr()

attr()准确的说&#xff0c;不应该是一个属性&#xff0c;而是一个CSS的函数&#xff0c;我们先看看MDN上的介绍吧&#xff1a; Summary The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the style sheet. It c…

番石榴15 –新功能

本月初发布了新版本的Guava库&#xff0c;其中包含一些新功能和改进。 以下是此版本中一些重要的API新增功能的概述&#xff1a; 1.逃脱者 Escapers使您可以“转义”字符串中的特殊字符&#xff0c;以使字符串符合特定格式。 例如&#xff0c;在XML中&#xff0c;必须将<字…

MySQL大小写敏感的解决方案

前言&#xff1a;对于MySQL的大小写敏感的影响&#xff0c;笔者在一个小项目中深刻的体会到&#xff1a;当想要查询一条数据时&#xff0c;总是出来两条或多条&#xff0c;后来发现是大小写敏感造成的原因&#xff0c;本文就该问题提出解决方案。 1.MySQL大小写敏感的控制 mysq…

java主类型_Java主类结构:基本数据类型

Java语言是面向对象设计的语言&#xff0c;java车光绪的基本组成单元是类&#xff0c;类体中有包括属性与方法两部分。每一个应用程序都需要main()方法&#xff0c;含有main()方法的类成为主类建立一个java首先要建立包package Number;//建立的package包名为numberpuublic clas…

day3-文件操作之打开模式

r 只能读 r 可读可写&#xff0c;不会创建不存在的文件。如果直接写文件&#xff0c;则从顶部开始写&#xff0c;覆盖之前此位置的内容&#xff0c;如果先读后写&#xff0c;则会在文件最后追加内容。 w 只能写 覆盖整个文件 不存在则创建 w 可读可写 如果文件存在 则覆…

利用border制作三角形原理

网站前端页面中&#xff0c;有时候会使用一些三角形&#xff0c;除了使用图片的方式之外&#xff0c;利用css的border属性也可以做出相对应的三角形。那么&#xff0c;利用border是如何实现三角形的制作的呢&#xff1f; 先看下面一个例子&#xff1a; CSS代码&#xff1a; w…

Java开发中的常见危险信号

在开发&#xff0c;阅读&#xff0c;复审和维护成千上万行Java代码的几年中&#xff0c;我已经习惯于看到Java代码中的某些“ 危险信号 ”&#xff0c;这些信号通常&#xff08;但可能并非总是&#xff09;暗示着代码问题。 我不是在谈论总是错误的做法&#xff0c;而是在有限的…

js判断对象数组中是否存在某个对象

1. 如果要判断数组中是否存在某个元素的话很好判断&#xff0c;直接用数组的indexOf方法就好&#xff0c;存在返回当前索引不存在返回-1 var arr[1,2,3,4] arr.indexOf(3) // 2 arr.indexOf(5) // -1 2. 要只是判断的话是可以遍历后判断对象的属性是否相同的&#xff0c;像这种…

java weblogic 配置_java----weblogic部署应用

安装略创建域在部署过程中&#xff0c;不能用回退按钮&#xff0c;如果输入有误的话只能在该步设置完后重复进行设置。Linux命令和文件(夹)名是区分大小写的。1、进入weblogic的bin目录&#xff1a;#以具体安装目录为准cd /weblogic/Oracle/Middleware/Oracle_Home/wlserver/co…

sass 基础——回顾

1.webstorm 自动编译SASS  下载安装包 http://rubyinstaller.org/downloads/  然后点击安装&#xff0c;路径为默认路径就行&#xff0c; 勾选以下两项    add Ruby executables to your PATH    Associate .rb and rbw files with this Ruby information  安装完…

这么多年第一次自己去用游标和临时表

汗颜&#xff0c;做了这么多年开发自己第一次用游标和临时表 还是借助度娘才写出来的&#xff0c;请大家给指点下。。。 1 CREATE PROCEDURE [dbo].[sp_LaodDefaultFM]2 (3 ExhID int ,4 DefaultExhID INT,5 Result INT6 )7 AS 8 BEGIN 9 --判断当前会话中临时表是…

设置MongoDB副本集分为4个步骤

介绍 在详细介绍配置MongoDB副本集之前&#xff0c;让我简要介绍一下它们&#xff1a; 副本集是Mongodb数据库提供的功能&#xff0c;可实现高可用性和自动故障转移。 它是一种传统的主从配置&#xff0c;但具有自动故障转移功能。 基本上&#xff0c;它是mongod实例的组/集…

PHP ajax跨域问题最佳解决方案

一、本文通过设置Access-Control-Allow-Origin来实现跨域。 例如&#xff1a;客户端的域名是client.runoob.com&#xff0c;而请求的域名是server.runoob.com。 如果直接使用ajax访问&#xff0c;会有以下错误&#xff1a; XMLHttpRequest cannot load http://server.runoob.co…

java jpa 注解_Java : JPA相关以及常用注解

SpringDataJPA自定义的查询方法 定义规范And 并且Or     或Is,Equals    等于Between     两者之间LessThan      小于LessThanEqual   小于等于GreaterThan     大于GreaterThanEqual  大于等于After    之后(时间) >Before    之前(时间)…

一篇文章搞定css3 3d效果

css3 3d学习心得 卡片反转魔方banner图 首先我们要学习好css3 3d一定要有一定的立体感 通过这个图片应该清楚的了解到了x轴 y轴 z轴是什么概念了。 首先先给大家看一个小例子&#xff1a; 卡片反转 这个例子只是简单的纯css3 3d 关于y轴旋转 下面是代码&#xff1a; 这是HT…

5个编码技巧以减少GC开销

在本文中&#xff0c;我们将介绍五种方法&#xff0c;这些方法可以使用有效的编码来帮助垃圾回收器减少分配和释放内存的CPU时间&#xff0c;并减少GC开销。 较长的GC通常会导致我们的代码在回收内存时被停止&#xff08;也称为“停止世界”&#xff09;。 一些背景 GC的建立…

c#阿里云服务器发送邮件

public static void SendMailUse(){string host "smtp.lotusest.com";// 邮件服务器smtp.163.com表示网易邮箱服务器 string userName "s********t.com";// 发送端账号 string password "11111111";// 发送端密码(这个客户端重置后的密码…

java usb 无驱打印_Windows Usb 无驱动打印

\?\USB#VID_8866&PID_0100#0001B0000000#{a5dcbf10-6530-11d2-901f-00c04fb951ed}USB小票打印解决办法一、需要驱动&#xff0c;无需更改程序安装USB打印驱动&#xff0c;然后共享打印机&#xff0c;通过 “\\计算机\打印机名”的形式&#xff0c;按端口方式写。1二、直接…

需要学习的东西列表

1.Python2.webservice3.requirejs4.idea5.webService6.redis7.doubble8.mongDB9.zookper 大数据学习曲线&#xff1a;课程一、大数据运维之Linux基础课程二、大数据开发核心技术-Hadoop 2.x从入门到精通课程三、大数据开发核心技术-大数据仓库Hive精讲课程四、大数据协作框架-S…