3

使用python将word文档和pdf电子书进行格式互转(兼容Windows/Linux)

 1 year ago
source link: https://v3u.cn/a_id_96
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用python将word文档和pdf电子书进行格式互转(兼容Windows/Linux)

首页 - Python/2019-07-10

    一些重要文档格式之间的互转在目前显得尤为重要,pdf作为通用格式在现在各个平台上兼容性是最好的,所以写python脚本将这些word文档批量转换pdf是最好的解决方案。

    由于windows系统对于word文档有天然的兼容性优势,所以转换起来很简单,普遍上是通过comtypes模块。

pip3 install comtypes



from comtypes.client import CreateObject
import os

def wd_to_pdf(folder):
        #获取指定目录下面的所有文件
        files = os.listdir(folder)
        #获取word类型的文件放到一个列表里面
        wdfiles = [f for f in files if f.endswith((".doc", ".docx"))]
        for wdfile in wdfiles:
            #将word文件放到指定的路径下面
            wdPath = os.path.join(folder, wdfile)
            #设置将要存放pdf文件的路径
            pdfPath = wdPath
            #判断是否已经存在对应的pdf文件,如果不存在就加入到存放pdf的路径内
            if pdfPath[-3:] != 'pdf':
                pdfPath = pdfPath + ".pdf"
            #将word文档转化为pdf文件,先打开word所在路径文件,然后在处理后保存pdf文件,最后关闭
            pdfCreate = self.wdToPDF.Documents.Open(wdPath)
            pdfCreate.SaveAs(pdfPath, self.wdFormatPDF)

    其实难点还是在Linux系统下如何转换,因为comtypes依赖的win32com模块在linux下是无法使用的,所以在linux下面推荐另外一套解决方案也就是LibreOffice,LibreOffice 能够与 Microsoft Office 系列以及其它开源办公软件深度兼容,且支持的文档格式相当全面。

    首先卸载当前系统的libreoffice,因为大多数系统默认安装的都是低版本,我们要使用的是最新稳定版

yum remove libreoffice-*

    在https://www.libreoffice.org/download/download/上下载最新的稳定版gz压缩包

    安装java依赖

yum -y install java-1.8.0-openjdk*

    然后将刚才下载的gz压缩包解压后安装

tar xvf LibreOffice_6.2.5.2_Linux_x86-64_rpm.tar.gz
 
cd LibreOffice_6.2.5.2_Linux_x86-64_rpm/RPMS/
 
yum localinstall *.rpm

    最后安装一些依赖

yum install cairo cups-libs libSM
yum install ibus
yum install libreoffice-headless

    在命令行输入

libreoffice -help

    会显示帮助文档就没问题了

    

20190710024859_63307.png

    解决中文乱码问题

    安装windows字体(不装,会有乱码)将windows的字体复制到linux上C:WindowsFonts* windows上所有的字体(尝试过只复制部分,还是有乱码,全部字体就不会乱码了),上传到linux的/usr/share/fonts/chinese('chinese'目录是我自己建的,mkdir chinese)

chmod -R 755 /usr/share/fonts/chinese    // 修改权限

fc-cache -fv        // 建立字体缓存

fc-list | grep chinese        // 可以查看到已安装新增的字体了

    如果你嫌麻烦,也可以修改系统语言来支持中文

执行命令:

yum groupinstall "fonts"

安装成功后,

打开

vim /etc/locale.conf

按键 i 进入编辑模式, 把内容改为

LANG="zh_CN.UTF-8"

wq 存盘

然后重启服务器reboot

之后也可以支持中文转换了

    

libreoffice6.2 --headless --convert-to pdf /root/4321.docx

    

20190710025759_13195.png

    

    此时,我们要改造一下转换脚本,做到可以兼容windows和Linx双系统,任意系统下都可以调用脚本进行转换

import subprocess
import os
try:
    from comtypes import client
except ImportError:
    client = None

def doc2pdf(doc):
    """
    convert a doc/docx document to pdf format
    :param doc: path to document
    """
    doc = os.path.abspath(doc) # bugfix - searching files in windows/system32
    if client is None:
        return doc2pdf_linux(doc)
    name, ext = os.path.splitext(doc)
    try:
        word = client.DispatchEx("Word.Application")
        worddoc = word.Documents.Open(doc)
        worddoc.SaveAs(name + '.pdf', FileFormat=17)
    except Exception:
        raise
    finally:
        worddoc.Close()
        word.Quit()


def doc2pdf_linux(doc):
    """
    convert a doc/docx document to pdf format (linux only, requires libreoffice)
    :param doc: path to document
    """
    cmd = 'libreoffice6.2 --headless --convert-to pdf'.split() + [doc]
    p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    p.wait(timeout=10)
    stdout, stderr = p.communicate()
    if stderr:
        raise subprocess.SubprocessError(stderr)

    简直完美,可以收工了


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK