Python实现将HTML转成PDF的方法分析


Posted in Python onMay 04, 2019

本文实例讲述了Python实现将HTML转成PDF的方法。分享给大家供大家参考,具体如下:

主要使用的是wkhtmltopdf的Python封装——pdfkit

安装

1. Install python-pdfkit:

$ pip install pdfkit

2. Install wkhtmltopdf:

  • Debian/Ubuntu:
$ sudo apt-get install wkhtmltopdf
  • Redhat/CentOS
sudo yum intsall wkhtmltopdf
  • MacOS
brew install Caskroom/cask/wkhtmltopdf

使用

一个简单的例子:

import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')

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

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作进一步处理, 你可以将其读取到一个变量中:

# 设置输出文件为False,将结果赋给一个变量
pdf = pdfkit.from_url('http://google.com', False)

你可以制定所有的 wkhtmltopdf 选项 <http://wkhtmltopdf.org/usage/wkhtmltopdf.txt>. 你可以移除选项名字前面的 '--' .如果选项没有值, 使用None, Falseor * 作为字典值:

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('http://google.com', 'out.pdf', options=options)

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

options = {
    'quiet': ''
    }
  pdfkit.from_url('google.com', 'out.pdf', options=options)

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

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

当你转换文件、或字符串的时候,你可以通过css选项指定扩展的 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)

你也可以通过你的HTML中的meta tags传递任意选项:

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

配置

每个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)

问题

  • IOError: 'No wkhtmltopdf executable found':

确保 wkhtmltopdf 在你的系统路径中($PATH), 会通过 configuration进行了配置 (详情看上文描述)。 在Windows系统中使用where wkhtmltopdf命令 或 在 linux系统中使用 which wkhtmltopdf 会返回 wkhtmltopdf二进制可执行文件所在的确切位置.

  • IOError: 'Command Failed'

如果出现这个错误意味着 PDFKit不能处理一个输入。你可以尝试直接在错误信息后面直接运行一个命令来查看是什么导致了这个错误 (某些版本的 wkhtmltopdf会因为段错误导致处理失败)

  • 正常生成,但是出现中文乱码

确保两项:

1)、你的系统中有中文字体

2)、在html中加入<meta charset="UTF-8">

下面是我随便写的一个HTML表格:

<html>
<head><meta charset="UTF-8"></head>
<body>
<table width="400" border="1">
 <tr>
 <th align="left">Item....</th>
 <th align="right">1</th>
 </tr>
 <tr>
 <td align="left">衣服</td>
 <td align="right">$241.10</td>
 </tr>
 <tr>
 <td align="left">化妆品</td>
 <td align="right">$30.00</td>
 </tr>
 <tr>
 <td align="left">食物</td>
 <td align="right">$730.40</td>
 </tr>
 <tr>
 <th align="left">tOTAL</th>
 <th align="right">$1001.50</th>
 </tr>
</table>
</body>
</html>

下面是生成的PDF截图

Python实现将HTML转成PDF的方法分析

另:https://pdfcrowd.com/#convert_by_input

更多Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python with statement 进行文件操作指南
Aug 22 Python
Python如何快速上手? 快速掌握一门新语言的方法
Nov 14 Python
Python2.X/Python3.X中urllib库区别讲解
Dec 19 Python
对tensorflow 的模型保存和调用实例讲解
Jul 28 Python
python多进程并行代码实例
Sep 30 Python
python小项目之五子棋游戏
Dec 26 Python
Python中url标签使用知识点总结
Jan 16 Python
Python ORM编程基础示例
Feb 02 Python
Python Tkinter Entry和Text的添加与使用详解
Mar 04 Python
Python virtualenv虚拟环境实现过程解析
Apr 18 Python
使用keras内置的模型进行图片预测实例
Jun 17 Python
通用的Django注册功能模块实现方法
Feb 05 Python
Python第三方库face_recognition在windows上的安装过程
May 03 #Python
Python人脸识别第三方库face_recognition接口说明文档
May 03 #Python
Python使用到第三方库PyMuPDF图片与pdf相互转换
May 03 #Python
利用python将图片版PDF转文字版PDF
May 03 #Python
Python3.0中普通方法、类方法和静态方法的比较
May 03 #Python
Python Flask框架模板操作实例分析
May 03 #Python
Python Flask框架扩展操作示例
May 03 #Python
You might like
php smarty模版引擎中变量操作符及使用方法
2009/12/11 PHP
Google Voice 短信发送接口PHP开源版(2010.5更新)
2010/07/22 PHP
PDO版本问题 Invalid parameter number: no parameters were bound
2013/01/06 PHP
php调用新浪短链接API的方法
2014/11/08 PHP
PHP利用APC模块实现文件上传进度条的方法
2015/01/26 PHP
CI映射(加载)数据到view层的方法
2016/03/28 PHP
Yii2.0 RESTful API 基础配置教程详解
2018/12/26 PHP
IE和FireFox(FF)中js和css的不同
2009/04/13 Javascript
jQuery lazyLoad图片延迟加载插件的优化改造方法分享
2013/08/13 Javascript
js判断ie版本号的简单实现代码
2014/03/05 Javascript
JQuery 在线引用及测试引用是否成功
2014/06/24 Javascript
javascript中利用柯里化函数实现bind方法
2016/04/29 Javascript
JS给swf传参数的实现方法
2016/09/13 Javascript
Three.js获取鼠标点击的三维坐标示例代码
2017/03/24 Javascript
node.js中grunt和gulp的区别详解
2017/07/17 Javascript
JavaScript实现二叉树的先序、中序及后序遍历方法详解
2017/10/26 Javascript
微信小程序实现图片放大预览功能
2020/10/22 Javascript
优雅的将ElementUI表格变身成树形表格的方法步骤
2019/04/11 Javascript
Nodejs异步流程框架async的方法
2019/06/07 NodeJs
[03:03]DOTA2校园争霸赛 济南城市决赛欢乐发奖活动
2013/10/21 DOTA
Python 数据结构之队列的实现
2017/01/22 Python
Python matplotlib通过plt.scatter画空心圆标记出特定的点方法
2018/12/13 Python
Python去除字符串前后空格的几种方法
2019/03/04 Python
如何使用pyinstaller打包32位的exe程序
2019/05/26 Python
html5生成柱状图(条形图)效果的实例代码
2016/03/25 HTML / CSS
Made in Design德国:设计师家具、灯具和装饰
2019/10/31 全球购物
戴尔荷兰官方网站:Dell荷兰
2020/10/04 全球购物
50道外企软件测试面试题
2014/08/18 面试题
长辈证婚人证婚词
2014/01/09 职场文书
简历的自我评价
2014/02/03 职场文书
党风廉设责任书
2014/04/16 职场文书
优秀的应届生自荐信
2014/05/23 职场文书
纪念九一八事变演讲稿:勿忘国耻
2014/09/14 职场文书
交警作风整顿剖析材料
2014/10/11 职场文书
体育教师教学随笔
2015/08/15 职场文书
会计专业2019暑假实习报告
2019/06/21 职场文书