Python编程:使用wkhtmltopdf将html网页转成pdf文件

简介: Python编程:使用wkhtmltopdf将html网页转成pdf文件

官网:https://wkhtmltopdf.org/

github: https://github.com/wkhtmltopdf/wkhtmltopdf

Mac环境:

brew install Caskroom/cask/wkhtmltopdf

linux环境(CentOS)

cat /proc/version  #  查看系统版本信息

yum install wkhtmltopdf

测试

$ wkhtmltopdf www.baidu.com 1.pdf

效果还行,不过部分内容没有被保存

11.png

Python接口包

pdfkit: https://github.com/JazzCore/python-pdfkit

pip install pdfkit

使用

import pdfkit

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

报错及解决

问题一

报错信息

You will need to run wkhtmltopdf within a "virtual" X server

或者

wkhtmltopdf: cannot connect to X server

解决:

(1)安装 xvfb 重命名 wkhtmltopdf

yum install xorg-x11-server-Xvfb

mv /usr/bin/wkhtmltopdf /usr/bin/wkhtmltopdf_bin

(2)新建/usr/bin/wkhtmltopdf.sh 文件

#! /usr/bin/bash
xvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf_bin $*

(3)赋予权限创建链接

chmod a+x /usr/bin/wkhtmltopdf.sh
ln -s /usr/bin/wkhtmltopdf.sh /usr/bin/wkhtmltopdf

4)测试效果

wkhtmltopdf https://www.baidu.com 1.pdf

问题二

报错信息

/usr/bin/xvfb-run: 第 186 行:kill: (7772) - 没有那个进程

解决:

在/usr/bin/wkhtmltopdf.sh 文件中 加入 -a 参数

#! /usr/bin/bash
xvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf_bin $*


参考

1.https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

2.使用python把html网页转成pdf文件

3.html转pdf工具wkhtmltopdf

4.Centos7安装使用wkhtmltopdf实现html页面转换成pdf文档的具体操作

5.https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server

6.https://stackoverflow.com/questions/9604625/wkhtmltopdf-cannot-connect-to-x-server

7.https://stackoverflow.com/questions/30504274/xvfb-run-line-171-kill-25939-no-such-process


            </div>
目录
相关文章
|
14天前
|
数据采集 存储 API
网络爬虫与数据采集:使用Python自动化获取网页数据
【4月更文挑战第12天】本文介绍了Python网络爬虫的基础知识,包括网络爬虫概念(请求网页、解析、存储数据和处理异常)和Python常用的爬虫库requests(发送HTTP请求)与BeautifulSoup(解析HTML)。通过基本流程示例展示了如何导入库、发送请求、解析网页、提取数据、存储数据及处理异常。还提到了Python爬虫的实际应用,如获取新闻数据和商品信息。
|
3天前
|
人工智能 Python
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
21 0
|
14天前
|
开发者 索引 Python
实践:如何使用python在网页的表格里抓取信息
实践:如何使用python在网页的表格里抓取信息
|
14天前
|
数据采集 JSON 网络协议
「Python系列」Python urllib库(操作网页URL对网页的内容进行抓取处理)
`urllib` 是 Python 的一个标准库,用于打开和读取 URLs。它提供了一组模块,允许你以编程方式从网络获取数据,如网页内容、文件等。
36 0
|
1月前
|
前端开发 JavaScript API
基于ElectronEgg&Python,从零开始打造一款免费的PDF桌面工具
基于ElectronEgg&Python,从零开始打造一款免费的PDF桌面工具
|
1月前
|
Python
如何使用Python的Requests库进行网络请求和抓取网页数据?
如何使用Python的Requests库进行网络请求和抓取网页数据?
13 0
|
1月前
|
JSON 数据可视化 Linux
安利3款Python三方库!轻松实现PDF转图片,最快的只需一行代码!
安利3款Python三方库!轻松实现PDF转图片,最快的只需一行代码!
|
1月前
|
数据采集 移动开发 前端开发
springboot使用html模版导出pdf文档
springboot使用html模版导出pdf文档
|
1月前
|
数据挖掘 数据安全/隐私保护 开发者
使用Spire.PDF for Python插件从PDF文件提取文字和图片信息
使用Spire.PDF for Python插件从PDF文件提取文字和图片信息
83 0
|
1月前
|
存储 缓存 Python
如何使用Python抓取PDF文件并自动下载到本地
如何使用Python抓取PDF文件并自动下载到本地
34 0