word转pdf java linux,Java word转pdf Linux/windows跨平台 格式完美(利用命令行调用libreoffice)...

需求描述

最近在作word报表的自动生成,甲方要求要有pdf格式,且对样式要求特别严格。

上网搜了不少,发如今对word样式要求特别高的状况下,用libreoffice是特别好的选择。

基本上几秒钟10多页就出来。若是对样式要求不高,能够尝试其余的方法(aspose是个很好用的word->pdf的库)。linux

步骤

2.验证安装是否成功

黑窗口直接敲命令,windows下:soffice --convert-to pdf example.docx

linux下: doc2pdf example.docx, windows须要添加path系统变量(C:\Program Files\LibreOffice 5\program),否则没法识别soffice命令apache

3.写代码:windows

WordPdfUtils类:Word转Pdf主类app

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.List;

import java.util.Map;

import org.apache.commons.collections4.MapUtils;

import org.apache.poi.xwpf.converter.pdf.PdfConverter;

import org.apache.poi.xwpf.converter.pdf.PdfOptions;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import org.apache.poi.xwpf.usermodel.XWPFRun;

import org.apache.poi.xwpf.usermodel.XWPFTable;

import org.apache.poi.xwpf.usermodel.XWPFTableCell;

import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import fr.opensagres.xdocreport.utils.StringUtils;

/**

* @author Rocca

*

*/

public class WordPdfUtils {

protected static final Logger logger = LoggerFactory.getLogger(WordPdfUtils.class);

public boolean wordConverterToPdf(String docxPath) throws IOException {

File file = new File(docxPath);

String path = file.getParent();

try {

String osName = System.getProperty("os.name");

String command = "";

if (osName.contains("Windows")) {

//soffice --convert-to pdf -outdir E:/test.docx

command = "soffice --convert-to pdf -outdir " + path + " " + docxPath;

} else {

command = "doc2pdf --output=" + path + File.separator + file.getName().replaceAll(".(?i)docx", ".pdf") + " " + docxPath;

}

String result = CommandExecute.executeCommand(command);

// LOGGER.info("result==" + result);

System.out.println("生成pdf的result==" + result);

if (result.equals("") || result.contains("writer_pdf_Export")) {

return true;

}

} catch (Exception e) {

e.printStackTrace();

throw e;

}

return false;

}

//测试用

public static void main(String[] args) {

try {

new WordPdfUtils().wordConverterToPdf("E:/test.docx");

} catch (IOException e) {

System.out.println("word转换成pdf时出错");

e.printStackTrace();

}

}

}

CommandExecute类:执行linux或windows命令行dom

package com.bupt.nctc.utils;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import org.apache.commons.io.IOUtils;

/**

* linux或windows命令执行

*/

public class CommandExecute {

// public static void main(String[] args) {

// CommandExecute obj = new CommandExecute();

// String domainName = "www.baidu.com";

// //in mac oxs

// String command = "ping " + domainName;

// //in windows

// //String command = "ping -n 3 " + domainName;

// String output = obj.executeCommand(command);

// System.out.println(output);

// }

public static String executeCommand(String command) {

StringBuffer output = new StringBuffer();

Process p;

InputStreamReader inputStreamReader = null;

BufferedReader reader = null;

try {

p = Runtime.getRuntime().exec(command);

p.waitFor();

inputStreamReader = new InputStreamReader(p.getInputStream(), "UTF-8");

reader = new BufferedReader(inputStreamReader);

String line = "";

while ((line = reader.readLine()) != null) {

output.append(line + "\n");

}

//p.destroy();//这个通常不须要

} catch (IOException e) {

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

IOUtils.closeQuietly(reader);

IOUtils.closeQuietly(inputStreamReader);

}

System.out.println(output.toString());

return output.toString();

}

}

备注:里面的main(0方法去掉注释后,能够用来作测试svg

4.解决中文乱码问题测试

复制windows的经常使用字体到linux下(经常使用字体如宋体、黑体)

能够先把字体文件夹复制到linux下的某个文件夹下,而后复制到目标位置:

如:sudo cp -r dir1 dir2

在个人电脑上是:sudo cp -r /home/nctc/fonts /usr/share/fonts就能够完成了。(试过2次都行)

上面是参考了这个https://blog.csdn.net/frylion/article/details/8207259把字体复制到/usr/share/fonts下。字体

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node.js 是一种在服务器端运行的 JavaScript 运行环境,可以用于实现各种各样的应用程序。而 LibreOffice 是一款免费、开源的办公软件套件,其中包括了 Writer、Calc、Impress 等应用程序,支持多种文档格式。下面是一个基于 Node.js 和 LibreOffice 的实现 Word PDF 的简单方法: 1.安装 LibreOffice:首先需要在服务器上安装 LibreOffice,可以通过命令行或者图形界面进行安装。 2.使用 Node.js 的 child_process 模块:在 Node.js 中可以通过 child_process 模块来执行系统命令,在本例中可以使用该模块执行 LibreOffice命令行工具来进行 Word PDF 的操作。 3.编写 Node.js 代码:可以通过 Node.js 编写一个简单的脚本来实现 Word PDF。以下是一个简单的示例代码: ```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 脚本即可进行 Word PDF 的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值