gpt4 book ai didi

python pdfkit 中文乱码问题的解决方案

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 56 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章python pdfkit 中文乱码问题的解决方案由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

使用python pdfkit生成pdf文件中遇到中文乱码问题 。

1.生成的文件名不能带有中文字符 。

2.生成的pdf内容中文为乱码 。

生成的文件名不能带有中文字符

解决方法:

我暂时想到的处理方式是先生成英文文件名,再将这个文件重命名为中文的文件名 。

#coding=utf8import osimport pdfkitfrom uuid import uuid1ret = '<html><head><meta charset="UTF-8"></head><body><h1>测试pdf内容部分</h1></body></html>'.decode('utf8')file_name = str(uuid1())pdfkit.from_string(ret, file_name) # file_name不能带有中文 如果有会报错file_name_new = '测试.pdf'os.rename(file_name, file_name_new)

生成的pdf内容中文为乱码

原因1:

因为pdfkit生成pdf功能其实调用的是webkit的子模块wkhtmltopdf(通过命令行方式),所以pdfkit生成中文乱码其实是wkhtmltopdf中文乱码导致的;而wkhtmltopdf中文乱码是因为系统中不存在中文字体导致的 。

解决方法:

在系统中添加中文字体 。

我的本地电脑是ubuntu14.04的字体文件保存在/usr/share/fonts下(包含了中文字体文件具体哪一个我也不知道汗。),我的服务器是redhat系统(没有中文字体),所以在我的电脑上操作如下

cd /usr/share/fontszip -r fonts.zip ./*scp fonts.zip 服务器用户名@服务器ip:/usr/share/fonts

在服务器上操作如下

cd /usr/share/fontsunzip fonts.zipfc-cache -fvfc-list # 查看新添加的字体

你需要找一台有安装了中文字体的电脑复制一份字体文件(就是/usr/share/fonts下的文件),然后如我以上操作就可以了.

原因2:

需要在html的字符集设置为utf8 。

<head><meta charset="UTF-8"></head> 。

补充:python写入html文件中文乱码-解决办法 。

使用open函数将爬虫爬取的html写入文件,有时候在控制台不会乱码,但是写入文件的html中的中文是乱码的 。

案例分析

看下面一段代码:

# 爬虫未使用cookiefrom urllib import requestif __name__ == '__main__': url = "http://www.renren.com/967487029/profile" rsp = request.urlopen(url) html = rsp.read().decode() with open("rsp.html","w")as f: # 将爬取的页面 print(html) f.write(html)

看似没有问题,并且在控制台输出的html也不会出现中文乱码,但是创建的html文件中 。

python pdfkit 中文乱码问题的解决方案

解决方案

使用open方法的一个参数,名为encoding=” “,加入encoding=”utf-8”即可 。

# 爬虫未使用cookiefrom urllib import requestif __name__ == '__main__': url = "http://www.renren.com/967487029/profile" rsp = request.urlopen(url) html = rsp.read().decode() with open("rsp.html","w",encoding="utf-8")as f: # 将爬取的页面 print(html) f.write(html)

运行结果 。

python pdfkit 中文乱码问题的解决方案

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我。如有错误或未考虑完全的地方,望不吝赐教.

原文链接:https://blog.csdn.net/piaotiejun/article/details/51064710 。

最后此篇关于python pdfkit 中文乱码问题的解决方案的文章就讲到这里了,如果你想了解更多关于python pdfkit 中文乱码问题的解决方案的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com