天翼云代理,天翼云代理商,北京代理商
天翼云折扣专线:400-150-1900(全国市话)

用 Python 将 html 转为 pdf、word

2022-02-21 03:05:39
简介: 在日常中有时需将 html 文件转化为 pdf、word 文件。网上免费的大多数不支撑多个文件转化的状况,而且在转化几个后就开始收费了。

转 pdf

转 pdf 中运用 pdfkit 库,它能够让 web 网页直接转为 pdf 文件,多个 url 能够合并成一个文件。

装置 pdfkit 库

pip3 install pdfkit

装置 wkhtmltopdf 文件

pdfkit 是基于 wkhtmltopdf 的 python 封装库,所以需求装置 wkhtmltopdf 软件。

下载地址:https://wkhtmltopdf.org/downloads.html

53.jpg在windows 体系中,需求将 wkhtmltopdf.exe 文件途径装备在体系环境变量中。

url 生成 pdf

这里运用 baidu 主页和 bing 主页作为示例

import pdfkit # 第一个参数能够是列表,放入多个域名,第二个参数是生成的 PDF 称号 pdfkit.from_url(['www.baidu.com','www.bing.com'],'search.pdf')

55.jpg


本地 html 文件生成 pdf

提前将需求转化的 html 存储到本地,也能够运用 python 爬虫代码抓取 html 文件到本地。

import pdfkit pdfkit.from_file('/Users/xx/Desktop/html/baidu.html', 'search.pdf')

转 word

运用 pypandoc 库将 html 转化为 word 文件,pypandoc 是一个支撑多种文件格式转化的 Python 库,它用到了 pandoc 软件,所以需求在电脑上装置 pandoc 软件

装置 pypandoc 库

pip install pypandoc

装置 pandoc 软件

pypandoc 是基于 pandoc 软件的库,所以要装置一下 pandoc (https://github.com/jgm/pandoc/releases/tag/2.11.4),pandoc 支撑多种类型转化。下图是 pandoc 的转化类型。


56.jpg

运用

将 html 文件提前存储在本地,也能够用爬虫将需求转化的 html 文件在代码中抓取后运用。

import pypandoc # convert_file('原文件','方针格式','方针文件') output = pypandoc.convert_file('/Users/xx/Desktop/html/baidu.html', 'docx', outputfile="baidu.doc")

pypandoc 无法对 word 进行排版,所以需求小伙伴们进行 2 次排版。

57.jpg

总结

利用好 Python 第三方库类,能够为小伙伴写出各种个性化定制的小程序

12年经验 · 提供上云保障

服务热线:132-6161-6125(手机) 400-150-1900(全国市话)

站内导航: 天翼云服务器价格| 天翼云购买流程| 天翼云代理| 北京天翼云代理商| 杭州天翼云代理| 深圳天翼云代理商| 钉钉代理商| 阿里云代理| 公司官网

我公司收款账号| 天翼云备案系统

CopyRight © 2019 天翼云代理商. All Rights Reserved 京ICP备11011846号-15 管理-北京志远天辰科技有限公司