Linux Openoffice转换Office为pdf

1、将下面的代码存储为 DocumentConvert.py

2、将该文件拷贝到 $OPENOFFICE/program 中($OPENOFFICE为主目录)

3、进入到program目录后,启动OPENOFFICE服务,启动服务命令如下:

./soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard &

4、执行如下命令进行文档转换:

./python DocumentConverter.py /opt/shanhy/test.doc /opt/shanhy/test.pdf
#第一个参数为要转换的doc文件,第二个参数为转换后的pdf文件位置

5、同样的命令也可以转换其他格式文件,大家查看下面的脚本代码研究研究。

DocumentConvert.py 脚本源码如下:

#
# PyODConverter (Python OpenDocument Converter) v1.1 - 2009-11-14
#
# This script converts a document from one office format to another by
# connecting to an OpenOffice.org instance via Python-UNO bridge.
#
# Copyright (C) 2008-2009 Mirko Nasato <[email protected]>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl-2.1.html
# - or any later version.
#
DEFAULT_OPENOFFICE_PORT = 8100

import uno
from os.path import abspath, isfile, splitext
from com.sun.star.beans import PropertyValue
from com.sun.star.task import ErrorCodeIOException
from com.sun.star.connection import NoConnectException

FAMILY_TEXT = "Text"
FAMILY_WEB = "Web"
FAMILY_SPREADSHEET = "Spreadsheet"
FAMILY_PRESENTATION = "Presentation"
FAMILY_DRAWING = "Drawing"

#---------------------#
# Configuration Start #
#---------------------#

# see http://wiki.services.openoffice.org/wiki/Framework/Article/Filter

# most formats are auto-detected; only those requiring options are defined here
IMPORT_FILTER_MAP = {
    "txt": {
        "FilterName": "Text (encoded)",
        "FilterOptions": "utf8"
    },
    "csv": {
        "FilterName": "Text - txt - csv (StarCalc)",
        "FilterOptions": "44,34,0"
    }
}

EXPORT_FILTER_MAP = {
    "pdf": {
        FAMILY_TEXT: { "FilterName": "writer_pdf_Export" },
        FAMILY_WEB: { "FilterName": "writer_web_pdf_Export" },
        FAMILY_SPREADSHEET: { "FilterName": "calc_pdf_Export" },
        FAMILY_PRESENTATION: { "FilterName": "impress_pdf_Export" },
        FAMILY_DRAWING: { "FilterName": "draw_pdf_Export" }
    },
    "html": {
        FAMILY_TEXT: { "FilterName": "HTML (StarWriter)" },
        FAMILY_SPREADSHEET: { "FilterName": "HTML (StarCalc)" },
        FAMILY_PRESENTATION: { "FilterName": "impress_html_Export" }
    },
    "odt": {
        FAMILY_TEXT: { "FilterName": "writer8" },
        FAMILY_WEB: { "FilterName": "writerweb8_writer" }
    },
    "doc": {
        FAMILY_TEXT: { "FilterName": "MS Word 97" }
    },
    "rtf": {
        FAMILY_TEXT: { "FilterName": "Rich Text Format" }
    },
    "txt": {
        FAMILY_TEXT: {
            "FilterName": "Text",
            "FilterOptions": "utf8"
        }
    },
    "ods": {
        FAMILY_SPREADSHEET: { "FilterName": "calc8" }
    },
    "xls": {
        FAMILY_SPREADSHEET: { "FilterName": "MS Excel 97" }
    },
    "csv": {
        FAMILY_SPREADSHEET: {
            "FilterName": "Text - txt - csv (StarCalc)",
            "FilterOptions": "44,34,0"
        }
    },
    "odp": {
        FAMILY_PRESENTATION: { "FilterName": "impress8" }
    },
    "ppt": {
        FAMILY_PRESENTATION: { "FilterName": "MS PowerPoint 97" }
    },
    "swf": {
        FAMILY_DRAWING: { "FilterName": "draw_flash_Export" },
        FAMILY_PRESENTATION: { "FilterName": "impress_flash_Export" }
    }
}

PAGE_STYLE_OVERRIDE_PROPERTIES = {
    FAMILY_SPREADSHEET: {
        #--- Scale options: uncomment 1 of the 3 ---
        # a) ‘Reduce / enlarge printout‘: ‘Scaling factor‘
        "PageScale": 100,
        # b) ‘Fit print range(s) to width / height‘: ‘Width in pages‘ and ‘Height in pages‘
        #"ScaleToPagesX": 1, "ScaleToPagesY": 1000,
        # c) ‘Fit print range(s) on number of pages‘: ‘Fit print range(s) on number of pages‘
        #"ScaleToPages": 1,
        "PrintGrid": False
    }
}

#-------------------#
# Configuration End #
#-------------------#

class DocumentConversionException(Exception):

    def __init__(self, message):
        self.message = message

    def __str__(self):
        return self.message

class DocumentConverter:

    def __init__(self, port=DEFAULT_OPENOFFICE_PORT):
        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
        try:
            context = resolver.resolve("uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext" % port)
        except NoConnectException:
            raise DocumentConversionException, "failed to connect to OpenOffice.org on port %s" % port
        self.desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)

    def convert(self, inputFile, outputFile):

        inputUrl = self._toFileUrl(inputFile)
        outputUrl = self._toFileUrl(outputFile)

        loadProperties = { "Hidden": True }
        inputExt = self._getFileExt(inputFile)
        if IMPORT_FILTER_MAP.has_key(inputExt):
            loadProperties.update(IMPORT_FILTER_MAP[inputExt])

        document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(loadProperties))
        try:
            document.refresh()
        except AttributeError:
            pass

        family = self._detectFamily(document)
        self._overridePageStyleProperties(document, family)

        outputExt = self._getFileExt(outputFile)
        storeProperties = self._getStoreProperties(document, outputExt)

        try:
            document.storeToURL(outputUrl, self._toProperties(storeProperties))
        finally:
            document.close(True)

    def _overridePageStyleProperties(self, document, family):
        if PAGE_STYLE_OVERRIDE_PROPERTIES.has_key(family):
            properties = PAGE_STYLE_OVERRIDE_PROPERTIES[family]
            pageStyles = document.getStyleFamilies().getByName(‘PageStyles‘)
            for styleName in pageStyles.getElementNames():
                pageStyle = pageStyles.getByName(styleName)
                for name, value in properties.items():
                    pageStyle.setPropertyValue(name, value)

    def _getStoreProperties(self, document, outputExt):
        family = self._detectFamily(document)
        try:
            propertiesByFamily = EXPORT_FILTER_MAP[outputExt]
        except KeyError:
            raise DocumentConversionException, "unknown output format: ‘%s‘" % outputExt
        try:
            return propertiesByFamily[family]
        except KeyError:
            raise DocumentConversionException, "unsupported conversion: from ‘%s‘ to ‘%s‘" % (family, outputExt)

    def _detectFamily(self, document):
        if document.supportsService("com.sun.star.text.WebDocument"):
            return FAMILY_WEB
        if document.supportsService("com.sun.star.text.GenericTextDocument"):
            # must be TextDocument or GlobalDocument
            return FAMILY_TEXT
        if document.supportsService("com.sun.star.sheet.SpreadsheetDocument"):
            return FAMILY_SPREADSHEET
        if document.supportsService("com.sun.star.presentation.PresentationDocument"):
            return FAMILY_PRESENTATION
        if document.supportsService("com.sun.star.drawing.DrawingDocument"):
            return FAMILY_DRAWING
        raise DocumentConversionException, "unknown document family: %s" % document

    def _getFileExt(self, path):
        ext = splitext(path)[1]
        if ext is not None:
            return ext[1:].lower()

    def _toFileUrl(self, path):
        return uno.systemPathToFileUrl(abspath(path))

    def _toProperties(self, dict):
        props = []
        for key in dict:
            prop = PropertyValue()
            prop.Name = key
            prop.Value = dict[key]
            props.append(prop)
        return tuple(props)

if __name__ == "__main__":
    from sys import argv, exit

    if len(argv) < 3:
        print "USAGE: python %s <input-file> <output-file>" % argv[0]
        exit(255)
    if not isfile(argv[1]):
        print "no such input file: %s" % argv[1]
        exit(1)

    try:
        converter = DocumentConverter()
        converter.convert(argv[1], argv[2])
    except DocumentConversionException, exception:
        print "ERROR! " + str(exception)
        exit(1)
    except ErrorCodeIOException, exception:
        print "ERROR! ErrorCodeIOException %d" % exception.ErrCode
        exit(1)
时间: 2024-11-09 04:50:18

Linux Openoffice转换Office为pdf的相关文章

OpenOffice实现Office转Pdf(支持自定义添加水印、页眉、页脚)

java OpenOffice officetopdf最近项目需要实现下载Office文档时自动转成PDF文档,以下代码支持2003及2007版的Word,PPT,Excel转换,并支持自定义添加水印.页眉.页脚实现需要事先安装OpenOffice(我这里安装的是OpenOffice 4)OpenOffice 下载: http://www.openoffice.org/JodConverter 下载地址 http://sourceforge.net/projects/jodconverter/f

openoffice+pdf2swf+FlexPaper在线显示office和pdf

前提:本人的系统为Ubuntu 13.10 64位系统.本篇是我在配置好环境后一段时间写的,所以操作上可能会有也错误,因此仅供参考. 搜索在线显示office和pdf,最常见的方法就是把都转为swf,然后通过FlexPaper显示.这个方法有缺点,FlexPaper不支持所有浏览器(我只能在chrome中使用,firefox要进行设置) 我用的系统是Ubuntu 13.10 64位 一下所提到的软件,我都会在附件中分享 一.openoffice安装 下载附件中的Apache_OpenOffice

记录libreoffice实现office转pdf(适用于windows、linux)

由于目前的工作跟office打交道比较多,所以才有了此篇blog,需求是实现word转换pdf方便页面展示.之前lz采用的是jacob(仅支持windows)进行转换的,但是现在服务器改成linux显然不能用了,于是网上搜罗一圈,最终决定采用LibreOffice.(前提:需要安装jdk环境) LibreOffice中文官网:https://zh-cn.libreoffice.org/   下载合适的版本,本文下载的是6.1.6 已上传百度网盘(链接: https://pan.baidu.com

使用jacob调用Windows的com对象,转换Office文件为pdf、html等

1.介绍 Jacob 是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁.使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用.至于什么是COM组件,大家自己Google吧. 2.安装和配置 Jacob是一个开源软件,它的官方站点是:http://danadler.com/jacob/ 大家可以到上面下载源代码研究,也可以直接下载编译后的二进制文件. 下载包jacob_x.x.zip,解压后有几个文件:jacob.j

office转pdf windows-linux-java工具类

概述 该文档详细描述了在windows和Linux环境下安装openoffice的全过程以及用java代码实现office转pdf文件的操作,文档中以Apache_OpenOffice_4.1.5_Win_x86_install_zh-CN.exe和Apache_OpenOffice_4.1.3_Linux_x86-64_install-rpm_zh-CN.tar.gz为例. Windows: 1.安装Apache_OpenOffice_4.1.5_Win_x86_install_zh-CN.e

Fedora 25 (linux平台)开源的PDF文件编辑工具——PDF mod

Fedora 25 (linux平台)开源的PDF文件编辑工具--PDF mod PDF文件具有非常好的跨平台属性,无论你在哪个平台用哪个PDF阅读器打开,其格式是永远不变的.但是缺点也很明显,文本文件或者图文混排文件,要想再次编辑就有很大难度了. Document viewer作为fedora 25默认PDF阅读器,用来阅读PDF文件没什么大问题,但是如果要修改一下PDF就显得不够强大了. PDF Mod是一款编辑 PDF 文件很方便的工具.包名:pdfmod PDF Mod 让用户可以移除页

ASP.NET VS2013 Office 转 PDF

本文适用于VS2013 项目中的Word转换为PDF.Excel转换为PDF.PPT转换为PDF 1.添加Using 1.在后台添加using using Microsoft.Office.Interop.Word; using Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; using Microsoft.Office.Interop.PowerPoint; 2.添加引用 1.添加引用 3.添加代码 1.在后台添加代码

java操作office和pdf文件java读取word,excel和pdf文档内容

在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下Java对word.excel.pdf文件的读取.本篇博客只是讲解简单应用.如果想深入了解原理.请读者自行研究一些相关源码. 首先我们来认识一下读取相关文档的jar包: 1. 引用POI包读取word文档内容 poi.jar 下载地址 http://apache.freelamp.com/poi/release/bin/poi-bin-3.6-20091214.zip 

libreoffice转换文件为pdf文件乱码问题解决办法

最近系统需要一个office文件预览功能 解决方案为使用libreoffice将office文件转换为pdf文件,然后使用swftools将pdf文件转换为swf文件 最后在前台使用flexpaper浏览swf文件,即可实现预览 环境搭建完成,转换也没有问题,但是预览效果看到所有中文全部为乱码 下载转换后的pdf文件也是乱码,由此可见时libreoffice转换这一步出现了问题 服务器转换文件乱码主要是由于没有中文字体导致的,我在ubuntu desktop系统下使用libreoffice打开o