如何利用Python将html转为pdf、word文件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

如何利用Python将html转为pdf、word文件

Python妙妙屋   2022-12-19 我要评论

前言

在日常中有时需将 html 文件转换为 pdf、word 文件。网上免费的大多数不支持多个文件转换的情况,而且在转换几个后就开始收费了。

转 pdf

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

安装 pdfkit 库

pip3 install pdfkit

安装 wkhtmltopdf 文件

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

在windows 系统中,需要将 wkhtmltopdf.exe 文件路径配置在系统环境变量中。

url 生成 pdf

这里使用 baidu 首页和 bing 首页作为示例

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

本地 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 的转换类型。

使用

将 html 文件提前存储在本地,也可以用爬虫将需要转换的 html 文件在代码中抓取后使用。

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

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

补充:用python把pdf文件转换为word文件

安装pip install pdf2docx:

pip install pdf2docx

如果安装过程出现报错,可能是版本匹配问题,先安装PyMuPDF这个库即可正常安装pip install PyMuPDF。

pip install PyMuPDF

安装好后,把需要转换的PDF文档放到和python代码同一个文件夹内。

python代码:

import os
from pdf2docx import Converter
 
def pdf_docx():
 
    # 获取当前工作目录
    file_path = os.getcwd()
 
    # 获取所有文件
    files = os.listdir(file_path)
 
    # 遍历所有文件
    for file in files:
 
        # 过滤临时文件
        if '~$' in file:
            continue
 
        # 过滤非pdf格式文件
        if file.split('.')[-1] != 'pdf':
            continue
        # 获取文件名称
        file_name = file.split('.')[0]
        # pdf文件名称
        pdf_name = os.getcwd() + '\\' + file
        # docx文件名称
        docx_name = os.getcwd() + '\\' + file_name + '.docx'
        # 加载pdf文档
        cv = Converter(pdf_name)
        cv.convert(docx_name, start=0, end=12)
        cv.close()
 
if __name__ == '__main__':
    pdf_docx()

start是pdf转换的起始页,end是结束页。如果不传入start和end这两个参数,默认就是从第一页转换到最后一页。也可以通过pages方法确定转换页数,方法为:cv.convert(docx_file, pages=[0,2, 5])

总结

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们