Java实现windows,linux服务器word,excel转为PDF;aspose-words,Documents4j
Java实现windows,linux服务器word,excel转为PDF;aspose-words,Documents4j
需求描述:要使用Java语言开发,实现word,excel转为pdf,经测试发现大部分都是在windows服务器上好使,支持linux的较少,且aspose还使用的是破解版。不过最终还是实现了相关功能,再次记录。
友情参考博文:
CSDN:通过aspose-words将word,Excel文档转为PDF
码农教程:记录下JAVA LINUX,WORD转PDF,用Documents4j
博客园:java 文件转成pdf文件 预览
博客园:用java实现word转pdf
一、通过aspose-words将word,Excel文档转为PDF
1.1 引入相关的jar
word转pdf需要引入 aspose-words-15.8.0-jdk16.jar
下载JAR包
Word
http://note.youdao.com/noteshare?id=1e73ab1c91abad338271d50a881165c2
excel转pdf需要引入aspose-cells-8.5.2.jar
Excel
http://note.youdao.com/noteshare?id=f75d87445106ea6ca6b54cfa58bc4fb2
1.2 将两个jar包,放入项目resources/lib目录下
在项目resouces目录下,新建一个lib的package,然后将下载的jar包放入其中。
1.3 配置pom.xml
<dependency>
<groupId>com.aspose</groupId>
<artifactId>words</artifactId>
<!--version,在本地跑项目时,不加不会报错,但是通过jenkins可持续集成构建时,需加version-->
<!--version可以随便指定,因为下面指定了该依赖是从项目之中加载,不从maven仓库下载-->
<!--jenkins可持续集成发布时,会更新依赖,若不指定version会报错-->
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/aspose-words.jar</systemPath>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>cells</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath>
</dependency>
这样操作完成后,经测试运行,在本地调试好使,但是放在linux服务器上时,会出现依赖找不到的错误,故还需要在Maven打包的时候,将项目里的两个依赖也打进包之中。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 将项目本地依赖也打包在项目之中 -->
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
</build>
1.4 测试代码
package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.License;
/**
* Word或Excel 转Pdf 帮助类
* @author lenovo
* 备注:需要引入 aspose-words-15.8.0-jdk16.jar / aspose-cells-8.5.2.jar
*/
public class PdfUtil {
private static boolean getLicense() {
boolean result = false;
try {
InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param wordPath 需要被转换的word全路径带文件名
* @param pdfPath 转换之后pdf的全路径带文件名
*/
public static void doc2pdf(String wordPath, String pdfPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
long old = System.currentTimeMillis();
File file = new File(pdfPath); //新建一个pdf文档
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(wordPath); //Address是将要被转化的word文档
doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
long now = System.currentTimeMillis();
os.close();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param excelPath 需要被转换的excel全路径带文件名
* @param pdfPath 转换之后pdf的全路径带文件名
*/
public static void excel2pdf(String excelPath, String pdfPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
long old = System.currentTimeMillis();
Workbook wb = new Workbook(excelPath);// 原始excel路径
FileOutputStream fileOS = new FileOutputStream(new File(pdfPath));
wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
fileOS.close();
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//word 和excel 转为pdf
String filePaths="D:/t.docx";
String fileName="zsqexcel78";
String pdfPath="D:/t.pdf";
// doc2pdf(filePaths, pdfPath);//filePaths需要转换的文件位置 pdfPath为存储位置
String excel2pdf="D:/t.xlsx";
excel2pdf(excel2pdf,pdfPath);
}
}
二、记录下JAVA LINUX,WORD转PDF,用Documents4j
2.1 添加依赖
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
这个有可能会存在guava包冲突的情况,spring cloud 里面也引用了guava,启动项目若报guava有关的错误,解决下依赖冲突即可。
我通过下面exclustions排除依赖时,一直不成功
<exclusions>
<exclusion>
.....guava
</exclusion>
</exclusions>
故,后来直接在里面重新添加了guava依赖,指定版本为20,成功解决问题。
2.2 word转pdf实践代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
public class Document4jApp {
public static void main(String[] args) {
File inputWord = new File("C:/Users/avijit.shaw/Desktop/testing/docx/Account Opening Prototype Details.docx");
File outputFile = new File("Test_out.pdf");
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
outputStream.close();
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
}
}
三、java 文件转成pdf文件 预览
3.1 前端代码
//预览功能
preview: function () {
//判断选中状态
var ids ="";
var num = 0;
$(".checkbox").each(function () {
if($(this).is(':checked')){
ids +=$(this).val() + ",";
num++;
}
});
if(num <=0 ){
toastr.error('请选择需要预览的文件!');
return;
}
if(num > 1){
toastr.error('页面下载只支持单个文件预览!');
return;
}
ids = ids.slice(0,ids.length-1);
$.ajax({
type: "post",
url: backbasePath+'/apia/v1/file/queryById',
dataType:"json",
data:{
token:$("#token").val(),
id:ids,
},
success: function(data) {
if('000000'==data.code){
// 文件路径
var path=data.data.file_path;
// 文件名称
var fileName=data.data.file_name;
// 获取文件后缀名
var suffix=fileName.substring(fileName.lastIndexOf(".")+1);
//如果对应的是文档
if(suffix == 'doc' || suffix == 'docx' || suffix == 'txt'|| suffix == 'pdf'){
//打开跳转页面
window.open(frontTemplatesPath + 'previewFile.html?suffix='+suffix+'&path='+path+'&fileName='+fileName,"_blank");
} else{
toastr.error('当前文件类型暂不支持预览!');
}
} else if (('900000' == data.code) || ('999999'== data.code)) {
toastr.error('查询文件信息失败!');
} else {
toastr.error(data.msg);
}
},
error: function () {
toastr.error('查询文件信息失败!');
}
});
},
3.2 html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件预览界面</title>
</head>
<body>
<div class="container">
<div>
<div >
<iframe style="width: 100%;height: 1000px;" src="" id="pdf"></iframe>
</div>
</div>
</div>
</body>
</html>
<script src="/coalminehwaui/static/js/jquery-3.1.1.min.js"></script>
<script src="/coalminehwaui/static/js/project/common.js"></script>
<script src="/coalminehwaui/static/js/plugins/toastr/toastr.min.js"></script>
<!-- slimscroll把任何div元素包裹的内容区加上具有好的滚动条-->
<script src="/coalminehwaui/static/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script>
'use strict';
$(function () {
LookPlan.getUrlString();
LookPlan.init();
});
var LookPlan = new Object({
getUrlString:function(name){
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return '';
},
init:function() {
var suffix =LookPlan.getUrlString('suffix');
var path =LookPlan.getUrlString('path');
var fileName =LookPlan.getUrlString('fileName');
var src=backbasePath + '/apia/v1/file/previewFile?path='+path+'&fileName='+fileName+'&suffix='+suffix;
setTimeout(function () {
document.getElementById("pdf").src=src;
}, 500);
}
});
</script>
3.3 后端代码
<!-- 文件转换成pdf--> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-local</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-transformer-msoffice-word</artifactId> <version>1.1.1</version> </dependency>
import com.documents4j.api.DocumentType;import com.documents4j.api.IConverter;import com.documents4j.job.LocalConverter;
/**
* 文档文件预览
*/
@RequestMapping(path = "/previewFile")
public void preview(HttpServletResponse response, @RequestParam(required = true)String path, @RequestParam(required = true)String fileName, @RequestParam(required = true)String suffix) throws Exception {
// 读取pdf文件的路径
String pdfPath="";
// 将对应的后缀转换成小写
String lastSuffix=suffix.toLowerCase();
//读取文件内容,获取文件存储的路径
String orgPath = filePath + path;
// 生成pdf文件的路径
String toPath = filePath + "pdf/";
// 判断对应的pdf是否存在,不存在则创建
File folder = new File(toPath);
if (!folder.exists()) {
folder.mkdirs();
}
// doc类型
if (lastSuffix.equals("pdf")) {
// pdf 文件不需要转换,直接从上传文件路径读取即可
pdfPath=orgPath;
} else {
// 转换之后的pdf文件
String newName=fileName.replace(lastSuffix,"pdf");;
File newFile = new File( toPath+"/"+newName);
// 如果转换之后的文件夹中有转换后的pdf文件,则直接从里面读取即可
if (newFile.exists()) {
pdfPath =toPath+"/"+newName;
}else {
pdfPath = wordToPdf(fileName,orgPath, toPath,lastSuffix);
}
}
// 读取文件流上
FileInputStream fis = new FileInputStream(pdfPath);
//设置返回的类型
response.setContentType("application/pdf");
//得到输出流,其实就是发送给客户端的数据。
OutputStream os = response.getOutputStream();
try {
int count = 0;
//fis.available()返回文件的总字节数
byte[] buffer = new byte[fis.available()];
//read(byte[] b)方法一次性读取文件全部数据。
while ((count = fis.read(buffer)) != -1)
os.write(buffer, 0, count);
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null)
os.close();
if (fis != null)
fis.close();
}
}
/**
* 将之前对应的word文件转换成pdf,然后预览pdf文件
*/
public String wordToPdf(String orgFile,String orgPath, String toPath, String suffix ){
// 转换之后的pdf文件
String targetFile=orgFile.replace(suffix,"pdf");
File inputWord = new File(orgPath);
File outputFile = new File(toPath+targetFile);
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
if(suffix.equals("doc")){
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("docx")){
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("txt")){
converter.convert(docxInputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute();
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return toPath+targetFile;
}
四、用java实现word文档转pdf
- 使用工具(Jar包)
aspose-words-15.11.0.jar(用于PDF转换 )
public static void main(String[] args) {
doc2pdf("/Users/lzl/Desktop/a.docx","/Users/lzl/Desktop/test.pdf");
}
public static void doc2pdf(String inPath, String outPath) {
FileOutputStream os =null;
try {
File file = new File(outPath); // 新建一个空白pdf文档
os = new FileOutputStream(file);
Document doc = new Document(inPath); // Address是将要被转化的word文档
//insertWatermarkText(doc, "四叶草的诗雨");
doc.save(os, SaveFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
加水印(升级版)
private static void insertWatermarkText(Document doc, String watermarkText) throws Exception
{
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
//水印内容
watermark.getTextPath().setText(watermarkText);
//水印字体
watermark.getTextPath().setFontFamily("宋体");
//水印宽度
watermark.setWidth(500);
//水印高度
watermark.setHeight(100);
//旋转水印
watermark.setRotation(-40);
//水印颜色
watermark.getFill().setColor(Color.lightGray);
watermark.setStrokeColor(Color.lightGray);
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
watermark.setWrapType(WrapType.NONE);
watermark.setVerticalAlignment(VerticalAlignment.CENTER);
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
Paragraph watermarkPara = new Paragraph(doc);
watermarkPara.appendChild(watermark);
for (Section sect : doc.getSections())
{
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
}
System.out.println("Watermark Set");
}
private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception
{
HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
if (header == null)
{
header = new HeaderFooter(sect.getDocument(), headerType);
sect.getHeadersFooters().add(header);
}
header.appendChild(watermarkPara.deepClone(true));
}
Java实现windows,linux服务器word,excel转为PDF;aspose-words,Documents4j的更多相关文章
- Atitit.office word excel ppt pdf 的web在线预览方案与html转换方案 attilax 总结
Atitit.office word excel ppt pdf 的web在线预览方案与html转换方案 attilax 总结 1. office word excel pdf 的web预览要求 ...
- 微信小程序云开发-云存储-下载并打开文件文件(word/excel/ppt/pdf)
一.wxml文件 1.写文本框,用来获取文件链接. 2.按钮,点击下载文件 <!-- 下载文件(word/excel/ppt/pdf等) --> <view class=" ...
- 微信小程序云开发-云存储-上传文件(word/excel/ppt/pdf)到云存储
说明 word/excel/ppt/pdf是从客户端会话选择文件.使用chooseMessageFile中选择文件. 一.wxml文件 上传按钮,绑定chooseFile <!--上传文件(wo ...
- C# 将Excel转为PDF时设置内容适应页面宽度
将Excel转为PDF格式时,通常情况下转换出来的PDF页面都是默认的宽度大小:如果Excel表格数据的设计或布局比较宽或者数据内较少的情况,转出来的PDF要么会将原本的一个表格分割显示在两个页面,或 ...
- 使用POI把Word Excel转为HTML
此方法是针对Office2003的,但是word中如果有图片,图片能够解析出来但是HTML文件中不显示.也不支持excel中的图片解析. 所需jar包如下如下: 1:PoiUtil.java pack ...
- java项目部署Linux服务器几种启动方式总结经验
一:两种部署包: 部署之前先说下两种包,java项目部署到服务器一般有用war包的,也有用jar包的,微服务spring-cloud普及后大部分打包都是jar,部署之前先搞清楚自己要打war包还是ja ...
- Windows & Linux服务器如何禁用ping总结
有时候你ping一些服务器或网站,你会发现ping不通,这个是因为对方出于安全因素(security reason)或避免网络拥堵(avoid network congestion)等原因,禁用了 ...
- Java 连接远程Linux 服务器执行 shell 脚本查看 CPU、内存、硬盘信息
pom.xml jar 包支持 <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch& ...
- Java 基于Spire.Cloud.Excel 将Excel转为PDF
Spire.Cloud.Excel Sdk 提供GeneralApi接口和WorkbookApi接口,支持将本地Excel和云端Excel文档转换为ODS, PDF, XPS, PCL, PS等格式. ...
随机推荐
- JavaDailyReports10_05
1 package varycode; 2 3 import java.util.ArrayList; 4 import java.util.Random; 5 6 public class Vary ...
- Socket.io详解
socket.io是一个跨浏览器支持WebSocket的实时通讯的JS. http://socket.io/docs/ 由于HTTP是无状态的协议,要实现即时通讯非常困难.因为当对方发送一条消息时,服 ...
- Docker技术
- git基础-撤销操作
---恢复内容开始--- 撤销操作 在任何阶段,你都有可能想要撤销某些操作. 当我们提交完了代码,发现漏掉了几个文件没有添加,后者提交信息写错了,此时,可以运行--amend选项的提交命令尝试重新提交 ...
- JS内存
内存是用来存什么的 通俗的来说呢,就是用来存 var let function const 声明的变量. 内存的大小 与操作系统有关,64位1.4G 32位0.7G. 为啥内存大小要这么设计,为啥不是 ...
- 温故而知新--day1
温故而知新--day1 变量类型 变量是计算机存储数据的内存空间,由于计算机可以处理不同的数据,不同的数据就要定义不同的数据类型.python的数据类型很多,还可以自定义数据类型,常用的一般数据类型有 ...
- Mysql中的语句优化
1.EXPLAIN 做MySQL优化,我们要善用EXPLAIN查看SQL执行计划. 下面来个简单的示例,标注(1.2.3.4.5)我们要重点关注的数据: type列,连接类型.一个好的SQL语句至少要 ...
- Spring(3) --事务,隔离级别,设计模式
什么是事务?事物的四大特性? 事务是指单个逻辑工作单元执行的一系列操作(ACID),这些操作要么全部执行,要么全部不执行,是不可中断的. (1)原子性(Atomicity)是指事务所有操作是不可中断的 ...
- 【Java基础】反射
反射 反射的概述 反射(Reflection)是被视为动态语言的关键,反射机制允许程序在执行期借助 Reflection API 取得任何类的内部信息,并能直接操作任意对象的内部属性和方法. 加载完类 ...
- 剑指offer 面试题4:二维数组中的查找
题目描述 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数 ...