python+libreoffice实现转换word,pdf,html等并生成目录

这段代码展示了如何在服务器端启动一个指定端口2083的LibreOffice服务,然后在客户端使用Python通过UNO接口连接到该服务,进行无头模式的文档操作,如内容提取和文件转换。主要涉及的技术包括Python的subprocess模块和com.sun.star库。
摘要由CSDN通过智能技术生成

server端:指定端口为2083

        soffice --accept="socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" --nologo --headless

client端:

#!/usr/bin/python3
import argparse
import os
import sys
from os.path import abspath, basename, isdir, join, splitext
import uno
from com.sun.star.beans import PropertyValue
from com.sun.star.connection import NoConnectException
import subprocess
import time
PORT = 2083
PROG = "$OFFICE_PROGRAM_PATH/python {}".format(basename(sys.argv[0]))
SOFFICE_CONNECTION_URI = "uno:socket,host=localhost,port=%d;urp;StarOffice.ComponentContext" % PORT



def startServer():
    """
    Start a headless instance of OpenOffice.
    """
    args = ['soffice',
            '--accept=socket,host=localhost,port=%d;urp;StarOffice.ServiceManager' % PORT,
            '--norestore',
            '--nofirststartwizard',
            '--nologo',
            '--headless',
            ]
    try:

        # pid = os.spawn(os.P_NOWAIT, args[0], args,env)
        subprocess.Popen(args, shell=False)
    except Exception:
        print("Cannot establish a connection to LibreOffice.")

def connect_soffice():
    """Connect to remote running LibreOffice"""
    local_context = uno.getComponentContext()
    resolver = local_context.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", local_context
    )
    
    startSevered = True
    n=0
    while n < 6:
        try:
            remote_context = resolver.resolve(SOFFICE_CONNECTION_URI)
            break
        except NoConnectException:
            pass
        if startSevered:
            startServer()
            startSevered = False
        time.sleep(2)     
        n += 1
    if n ==6:
       
        return False

    return remote_context


def createProp(name, value):
    prop = PropertyValue()
    prop.Name = name
    prop.Value = value
    return prop


def convert(src_file, dest_file, to_type,contents=False,contentTitle="Contents"):


    src_url =   "file:///{}".format(src_file).replace("\\", "/")
    dest_url =  "file:///{}".format(dest_file).replace("\\", "/")

    context = connect_soffice()
    soffice = context.ServiceManager.createInstanceWithContext(
        "com.sun.star.frame.Desktop", context)
    doc = soffice.loadComponentFromURL(src_url, "_blank", 0, 
                                         (PropertyValue(Name="Hidden", Value=True),)
                                         # conversion_props
                                        )
    


    # 获取内容
    text = doc.getText()
    cursor = text.createTextCursor()


    # 设置目录深度
    if contents=="True":
        index = doc.createInstance("com.sun.star.text.ContentIndex")
        index.setPropertyValue("Level", 10)
        index.setPropertyValue("CreateFromOutline", True)

        # 设置目录标题
        index.setPropertyValue("Title", contentTitle)
        doc.getText().insertTextContent(cursor, index, False)
        # doc.refresh()
        # 目录更新
        index.update()

    # 插入目录
    doc.storeToURL(dest_url,(createProp("FilterName",to_type),createProp("CharacterSet","UTF-8"),createProp("Overwrite",True)))
    doc.dispose()

def is_dir(value):
    if not isdir(value):
        raise argparse.ArgumentTypeError("{} is not a directory.".format(value))
    return value


def main():
    parser = argparse.ArgumentParser(description="Document Converter", prog=PROG)
    parser.add_argument("from_dir",
                        #type=is_dir,
                        help="Convert documents searched from this directory recursively")
    parser.add_argument("to_type", help="Type to convert to, example: MS Word 97.")
    parser.add_argument("extension",
                        help="Extension of the converted document, examples: doc, docx")
    parser.add_argument("content",
                        help="Extension of the converted document, examples: doc, docx")
    parser.add_argument("contentTitle",
                        help="Extension of the converted document, examples: doc, docx")
    parser.add_argument("output_dir",
                        #type=is_dir,
                        help="Converted document is stored into this directory")
    

    args = parser.parse_args()
    convert(args.from_dir, args.output_dir, args.to_type, args.content,args.contentTitle)

if __name__ == "__main__":
    main()

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node.js 是一种在服务器端运行的 JavaScript 运行环境,可以用于实现各种各样的应用程序。而 LibreOffice 是一款免费、开源的办公软件套件,其中包括了 Writer、Calc、Impress 等应用程序,支持多种文档格式。下面是一个基于 Node.js 和 LibreOffice实现 WordPDF 的简单方法: 1.安装 LibreOffice:首先需要在服务器上安装 LibreOffice,可以通过命令行或者图形界面进行安装。 2.使用 Node.js 的 child_process 模块:在 Node.js 中可以通过 child_process 模块来执行系统命令,在本例中可以使用该模块执行 LibreOffice 的命令行工具来进行 WordPDF 的操作。 3.编写 Node.js 代码:可以通过 Node.js 编写一个简单的脚本来实现 WordPDF。以下是一个简单的示例代码: ```javascript const { spawn } = require('child_process'); const inputFilePath = '/path/to/input.docx'; const outputFilePath = '/path/to/output.pdf'; const libreoffice = spawn('libreoffice', [ '--headless', '--convert-to', 'pdf', inputFilePath, '--outdir', outputFilePath, ]); libreoffice.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); libreoffice.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); libreoffice.on('close', (code) => { console.log(`child process exited with code ${code}`); }); ``` 以上代码中,spawn 方法会启动一个新的进程来执行 LibreOffice 命令行工具。'--headless' 参数表示以无头模式运行,'--convert-to pdf' 参数表示转换PDF 格式,inputFilePath 参数表示输入文件的路径,'--outdir' 参数表示输出文件的路径。 4.运行 Node.js 代码:在终端中运行 Node.js 脚本即可进行 WordPDF 的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值