使用pdfkit将HTML转为PDF

环境

Ubuntu Server 18.04
Python 3.6.9

安装依赖

pdfkit是Python的一个轮子,不过依赖系统中的wkhtmltopdf应用,所以需要分别来安装

$ sudo apt update	# 更新一下防后面安装出现问题
$ sudo apt install wkhtmltopdf
$ pip3 install pdfkit

安装中文字体

默认安装完成后是无法正常渲染中文字体的(Ubuntu Server最小化安装的,显然没有中文字体,就算有也肯定和网页css中定义的不一样),所以需要从Windows系统中找到需要用到的TTF字体怼到Ubuntu里面.
我要渲染的HTML里面主要用到了Windows中的仿宋黑体两个字体,可以在Windows系统中C:\Windows\Fonts\里面分别找到仿宋 常规黑体 常规(对应文件名:SIMFANG.TTFSIMHEI.TTF)上传到Ubuntu的/usr/share/fonts/里面(最好新建个文件夹)

$ cd /usr/share/fonts
$ sudo mkdir winFonts
$ cp ~/*.TTF ./winFonts		# 用SSH先上传到用户~目录中,然后再sudo复制到fonts/winFonts里面
$ fc-cache		# 重建字体缓存

使用方法

直接在ipython里面测试了

import pdfkit
pdfkit.from_url('http://192.168.3.60/report/1', '1.pdf')

将当前目录下生成的1.pdf下载回来在Windows上打开,和原始的HTML显示效果一模一样,棒棒哒!
在这里插入图片描述

其他问题1

Windows环境下输出的pdf中文乱码问题参考这篇文章:

https://blog.csdn.net/warlocker1982/article/details/83552010

其他问题2

又装了台Minimal的CentOS7进行测试,由于没有图形界面,运行会报错:

OSError: wkhtmltopdf: cannot connect to X server

You will need to run wkhtmltopdf within a "virtual" X server.
Go to the link below for more information
https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server

查了下官方提供的解决方案,使用虚拟X server xvfb来解决:

CentOS7
xvfb的安装与Ubuntu不太一样

yum install xorg-x11-server-Xvfb
printf '#!/bin/bash\nxvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf -q $*' > /usr/bin/wkhtmltopdf.sh
chmod a+x /usr/bin/wkhtmltopdf.sh
ln -s /usr/bin/wkhtmltopdf.sh /usr/local/bin/wkhtmltopdf

可以执行了,但是安装的字体没法正确都调用,跟上面操作一样只安装了黑体和仿宋两个字体,但是输出的pdf中全部都使用的是黑体,应该是虚拟X server中对字体配置的问题,继续研究:

yum install -y xorg-x11-font-utils
mkfontdir /usr/share/fonts/winFonts
mkfontscale /usr/share/fonts/winFonts
fc-cache -vf

还是不行,不折腾了,重新装个带GUI的Ubuntu吧


官方原文解决方案(针对Ubuntu系统)

wkhtmltopdf needs a X server. If you’re running your application on a VPS, you probably don’t have one installed. The solution is install a “virtual” X server.

Linux
Debian/Ubuntu
To install wkhtmltopdf in a Debian/Ubuntu server, follow this steps(as root):

apt-get install wkhtmltopdf
apt-get install xvfb
printf '#!/bin/bash\nxvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf -q $*' > /usr/bin/wkhtmltopdf.sh
chmod a+x /usr/bin/wkhtmltopdf.sh
ln -s /usr/bin/wkhtmltopdf.sh /usr/local/bin/wkhtmltopdf
wkhtmltopdf http://www.google.com output.pdf
发布了181 篇原创文章 · 获赞 82 · 访问量 41万+

猜你喜欢

转载自blog.csdn.net/lpwmm/article/details/103467851