Ubuntu实现word转pdf

本文详细介绍在Ubuntu16.04LTS上使用LibreOffice6.3.5将文档转换为PDF的方法。通过安装特定版本的LibreOffice及unoconv工具,利用Java代码实现自动化转换流程,有效避免了因版本不兼容导致的问题。

系统信息

Ubuntu / 16.04 LTS amd64 (64bit)

服务器版本

采用工具: libreoffice

安装

下载 LibreOffice_6.3.5_Linux_x86-64_deb.tar.gz。 【特别注意】 是 6.3.5 版本。 并解压

ln -s //opt/libreoffice6.3/program/soffice soffice

dpkg -i *.deb

cd /usr/bin
ln -s /opt/libreoffice6.3/program/soffice soffice

安装 unoconv 工具

apt-get update

apt-get install unoconv -y
apt-get -y install fontconfig xfonts-utils
apt-get -y install ttf-wqy-microhei
fc-list :lang=zh

Java 代码

package io.renren.modules.oss.service.impl;

import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import io.renren.modules.oss.service.WordService;
import ooo.connector.BootstrapSocketConnector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author Felix Yan
 * @data 2018/07/19
 */
@Service("unoWordService")
public class LibreOfficeUnoWordServiceImpl implements WordService {

    @Value("${soffice-dir:/usr/bin}")
    private String sofficeDir;

    @Override
    public void word2pdf(String inPath, String outPath) throws Exception {

        if (!outPath.endsWith(".pdf")) {
            outPath += "_result.pdf";
        }

        XComponentContext xContext = BootstrapSocketConnector.bootstrap(sofficeDir);

        XMultiComponentFactory xMCF = xContext.getServiceManager();

        Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);

        XDesktop xDesktop = UnoRuntime.queryInterface(XDesktop.class, oDesktop);

        XComponentLoader xCompLoader = UnoRuntime.queryInterface(XComponentLoader.class, xDesktop);

        XComponent xComp = xCompLoader.loadComponentFromURL(
                "file:///" + inPath, "_blank", 0, new PropertyValue[0]);

        XStorable xStorable = UnoRuntime.queryInterface(XStorable.class, xComp);

        PropertyValue[] propertyValue = new PropertyValue[2];
        propertyValue[0] = new PropertyValue();
        propertyValue[0].Name = "Overwrite";
        propertyValue[0].Value = Boolean.TRUE;
        propertyValue[1] = new PropertyValue();
        propertyValue[1].Name = "FilterName";
        propertyValue[1].Value = "writer_pdf_Export";
        xStorable.storeToURL("file:///" + outPath, propertyValue);

        xDesktop.terminate();
    }

}

测试

命令行监测是否转换成功

unoconv -f pdf 1.doc


// 检测目录是否存在
ls /usr/share/help-langpack/en_GB/evolution/contacts-libreoffice.page


https://blog.youkuaiyun.com/only_jing1314/article/details/48008589

遇到的问题

启动失败
CE> Warning: -nologo is deprecated.  Use --nologo instead.
CE> Warning: -nodefault is deprecated.  Use --nodefault instead.
CE> Warning: -norestore is deprecated.  Use --norestore instead.
CE> Warning: -nolockcheck is deprecated.  Use --nolockcheck instead.
CE> Warning: -accept=socket,host=localhost,port=8100;urp; is deprecated.  Use --accept=socket,host=localhost,port=8100;urp; instead.
2020-05-14 09:41:08.503 ERROR 1940 --- [o-10011-exec-23] i.r.c.exception.RenExceptionHandler      : null
com.sun.star.lang.DisposedException: null
    at com.sun.star.lib.uno.environments.remote.JobQueue.removeJob(JobQueue.java:210)
    at com.sun.star.lib.uno.environments.remote.JobQueue.enter(JobQueue.java:330)
    at com.sun.star.lib.uno.environments.remote.JobQueue.enter(JobQueue.java:303)
    at com.sun.star.lib.uno.environments.remote.JavaThreadPool.enter(JavaThreadPool.java:87)
    at 

【问题原因】 安装了最新版本的 libreoffice

apt-get install libreoffice

【解决办法】 采用文章首页的 安装办法即可。

Ubuntu实现WordPDF,您可以按照以下步骤进行操作: 1. 安装OpenJDK和Maven: ``` sudo apt-get update sudo apt-get install openjdk-8-jdk sudo apt-get install maven ``` 2. 创建一个Spring Boot项目: ``` mvn archetype:generate -DgroupId=com.example -DartifactId=word2pdf -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false ``` 3. 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> ``` 4. 创建一个Controller类,其中包含一个方法,该方法接受一个Word文件并将其换为PDF文件: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class WordToPdfController { @PostMapping("/convert") public String convertToPdf(@RequestParam("file") MultipartFile file) { try { // Read the Word document XWPFDocument docx = new XWPFDocument(new FileInputStream(convert(file))); // Create the PDF document Document pdf = new Document(); PdfWriter.getInstance(pdf, new FileOutputStream("converted.pdf")); pdf.open(); // Read each paragraph from the Word document and write it to the PDF document for (XWPFParagraph para : docx.getParagraphs()) { for (XWPFRun run : para.getRuns()) { // Add the text to the PDF document pdf.add(new Paragraph(run.getText(0))); } } pdf.close(); return "success"; } catch (Exception e) { e.printStackTrace(); return "error"; } } // Convert MultipartFile to File private File convert(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); convFile.createNewFile(); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; } } ``` 此代码将从客户端接收一个MultipartFile对象,将其换为File对象,然后使用Apache POI读取Word文档并使用iText将其写入PDF文件。 5. 启动应用程序并使用Postman或浏览器发送请求,将Word文件作为MultipartFile对象发送到“/convert”端点。在应用程序目录中,您将找到一个名为“converted.pdf”的新文件,其中包含换后的PDF文档。 ``` mvn spring-boot:run ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值