使用python脚本完成word转pdf(兼容linux)

参考:https://v3u.cn/a_id_96

起因:看到一个需求是用java把word转成pdf,在windows上使用Jacob可以实现,但linux上比较麻烦,  性能等综合考虑使用OpenOffice比较好。

          感觉可以用java调用python脚本实现,这里做个记录。

 

          在原博客中,作者在windows环境下使用了comtypes实现的转换,我本地换成了pywin32实现,另,增加了一个输出目录的参数,用于指定生成pdf的路径。

环境:本地:win10 + jdk1.8 + python3.7  linux服务器:centos7 + jdk1.8 + python3.6

          jdk和python3的安装可百度,这里不做记录。

 

具体实现:

         1)windows环境安装comtypes,用于脚本中判断是windows环境还是linux环境

         2)windows环境安装pywin32库:pip install pywin32

         3)linux中需要使用LibreOffice,安装依赖:

                     yum remove libreoffice-*

                    从https://www.libreoffice.org/download/download/上下载最新版本的linux rpm版本的LibreOffice,上传到自己的linux环境中,我这里下载的是LibreOffice_6.2.5_Linux_x86-64_ rpm.tar.gz

 

                    解压:tar -zxvf  LibreOffice_6.2.5_Linux_x86-64_ rpm.tar.gz

                      cd LibreOffice_6.2.5.2_Linux_x86-64_rpm/RPMS

                       yum localinstall *.rpm

          4)安装其他依赖:

                  yum install cairo cups-libs libSM

                  yum install ibus

                  yum install libreoffice-headless

          5)查看是否安装成功:libreoffice -help

          6)将window环境字体拷贝至linux中 

                  windows文件夹 C:\\windows\\Fonts文件夹中所有内容拷贝至 linux中/usr/share/fonts/chinese文件夹下,没有就新建

          7)修改字体缓存、权限

                 chmod -R 755 /usr/share/fonts/chinese

                 fc-cache -fv

                 fc-list | grep chinese //查看安装的新字体

           8)linux下测试Libreoffice是否可用

                   libreoffice6.2 --headless --convert-to pdf /root/xxx.docx         ------直接生成在了docx文件同目录下,有同名的文件会覆盖掉

                  libreoffice6.2 --headless --convert-to pdf /root/xxx.docx --outdir /root     -------指定了输出路径     

 

 

一切都OK的话,就可以执行脚本了:

 

import subprocess
import os
import sys

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

try:
    from win32com.client import constants, gencache
except ImportError:
    constants = None
    gencache = None


def doc2pdf(docPath, pdfPath):
    """
        convert a doc/docx document to pdf format
        :param doc: path to document
        """
    docPathTrue = os.path.abspath(docPath)  # bugfix - searching files in windows/system32
    if client is None:#判断环境,linux环境这里肯定为None
        return doc2pdf_linux(docPathTrue, pdfPath)
    # 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()
    word = gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(docPathTrue, ReadOnly=1)
    doc.ExportAsFixedFormat(pdfPath,
                            constants.wdExportFormatPDF,
                            Item=constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
    word.Quit(constants.wdDoNotSaveChanges)


def doc2pdf_linux(docPath, pdfPath):
    """
    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() + [docPath] + ['--outdir'] + [pdfPath]
    p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    p.wait(timeout=30)
    stdout, stderr = p.communicate()
    if stderr:
        raise subprocess.SubprocessError(stderr)


if __name__ == '__main__':
    doc2pdf(sys.argv[1], sys.argv[2])

 

 

Java测试代码如下:

 

 

          

                

 

 

         

 

posted @ 2019-07-15 17:25  阿竹  阅读(12535)  评论(1编辑  收藏  举报