官网地址:documents4j - Java 的文档格式转换器
本文中使用的是本地转换器
草率的看了一眼文档,说明使用本地转换器需要在本机有ms work、ms excel (此处部署在linux时需要安装)。
本文使用的documents4j依赖(若有其他格式的文件需要转换则需要引入其他转换器)
com.documents4j
documents4j-local
1.1.1
com.documents4j
documents4j-transformer-msoffice-word
1.1.1
com.documents4j
documents4j-transformer-msoffice-excel
1.1.1
工具类中还有jpg、png转换pdf以及纯文本格式的文件使用的是 itextpdf(有需要也可以看一下这部分)
fr.opensagres.xdocreport org.apache.poi.xwpf.converter.pdf 1.0.6 com.itextpdf.tool xmlworker 5.5.11
import java.io.*;
import com.aams.base.AamsOperatingException;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.itextpdf.text.*;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileTransformUtil {
private Logger log = LoggerFactory.getLogger(FileTransformUtil.class);
public InputStream getPdfStream(String fileEnd, String fileName, InputStream fileInput) throws Exception {
// 输出的PDF流
ByteArrayOutputStream output = new ByteArrayOutputStream();
//纯文本和图片的采用的是itextpdf的方式 有兴趣的也可以使用documents4j完成一下(这里因为写的比较早所以就没改本人也懒的换了)
if ("xml".equalsIgnoreCase(fileEnd) || "html".equalsIgnoreCase(fileEnd) || "txt".equalsIgnoreCase(fileEnd)) {
// 创建PDF文档对象 页大小为A4
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
// 创建PDF写入器
PdfWriter.getInstance(document, output);
// 打开文档对象
document.open();
//读取xml中的内容
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//输出流
byte[] bytes = new byte[1024];
int len;
while ((len = fileInput.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);//将读到的字节写入输出流
}
fileInput.close();
String content=outputStream.toString();
outputStream.close();
this.createPdfContent(document,content);
document.close();
output.close();
return new ByteArrayInputStream(output.toByteArray());
}
else if ("jpg".equalsIgnoreCase(fileEnd) || "png".equalsIgnoreCase(fileEnd)) {
// 创建PDF文档对象 页大小为A4
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
// 创建PDF写入器
PdfWriter.getInstance(document, output);
// 打开文档对象
document.open();
//添加图片
this.createStreamPic(document,fileInput);
document.close();
fileInput.close();
output.close();
return new ByteArrayInputStream(output.toByteArray());
}
else if ("docx".equalsIgnoreCase(fileEnd) || "doc".equalsIgnoreCase(fileEnd) || "xlsx".equalsIgnoreCase(fileEnd) || "xls".equalsIgnoreCase(fileEnd)) {
try {
//本地转换器转换文件
IConverter converter = LocalConverter.builder().build();
if(fileEnd.equals("doc")){
//指定要转格式的文件
converter.convert(fileInput)
//当前文件的格式
.as(DocumentType.DOC)
//输出--这里直接输出到流中 (如果是直接写在本地的可以直接 FileOutPutStream(new File("位置")))
.to(output)
//输出的格式
.as(DocumentType.PDF).execute();
}
else if(fileEnd.equals("docx")){
converter.convert(fileInput)
.as(DocumentType.DOCX)
.to(output)
.as(DocumentType.PDF).execute();
}
else if(fileEnd.equals("xlsx")){
converter.convert(fileInput)
.as(DocumentType.XLSX)
.to(output)
.as(DocumentType.PDF).execute();
}
else if(fileEnd.equals("xls")){
converter.convert(fileInput)
.as(DocumentType.XLS)
.to(output)
.as(DocumentType.PDF).execute();
}
output.close();
fileInput.close();
return new ByteArrayInputStream(output.toByteArray());
} catch (Exception e) {
log.error("[documents4J] word转pdf失败:{}", e.toString());
}finally {
if(output != null){
output.close();
}
}
}
return null;
}
private void createPdfContent(Document document,String text) throws AamsOperatingException {
try {
Paragraph paragraph1 = new Paragraph();
Chunk timeChunk = new Chunk(text);
paragraph1.add(timeChunk);
document.add(paragraph1);
} catch (Exception e) {
throw new AamsOperatingException(e.getMessage());
}
}
private void createStreamPic(Document document, InputStream inputStream) throws AamsOperatingException {
this.createStreamPic(document, inputStream, 0, 0);
}
/**
* @param height 高
* @param width 宽
* @param inputStream 图片流
* pdf中添加图片
**/
private void createStreamPic(Document document, InputStream inputStream, float height, float width) throws AamsOperatingException {
try {
int n;
byte[] buffer = new byte[4096];
ByteArrayOutputStream imgOutPut = new ByteArrayOutputStream();
while (-1 != (n = inputStream.read(buffer))) {
imgOutPut.write(buffer, 0, n);
}
Image image = Image.getInstance(imgOutPut.toByteArray());
height = height != 0 ? height : image.getHeight();
width = width != 0 ? width : image.getWidth();
int percent = getPercent(height, width);
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent);
document.add(image);
}catch (Exception e){
throw new AamsOperatingException(e.getMessage());
}
}
private void createUrlPic(Document document, String path) throws AamsOperatingException {
this.createUrlPic(document, path, 0, 0);
}
/**
*@param height 高
*@param width 宽
*@param path 图片地址
* pdf中添加图片
**/
private void createUrlPic(Document document, String path, float height, float width) throws AamsOperatingException {
try {
Image image = Image.getInstance(path);
height = height != 0 ? height : image.getHeight();
width = width != 0 ? width : image.getWidth();
int percent = getPercent(height, width);
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent);
document.add(image);
} catch (Exception e) {
throw new AamsOperatingException(e.getMessage());
}
}
//图片比例设置
private static int getPercent(float height, float weight) {
float percent = 0.0F;
if (height > weight) {
percent = PageSize.A4.getHeight() / height * 100;
} else {
percent = PageSize.A4.getWidth() / weight * 100;
}
return Math.round(percent);
}
/**
* main方法中截是测试使用
* */
// public static void main(String[] args){
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// // 创建PDF文档对象 页大小为A4
// Document document = new Document(PageSize.A4, 20, 20, 20, 20);
System.err.println("123");
// try {
//
// // 创建PDF写入器
// PdfWriter.getInstance(document, output);
// // 打开文档对象
// document.open();
//
// InputStream is = new FileInputStream(new File("D:\\123.xml"));
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//输出流
// byte[] bytes = new byte[1024];
// int len;
// while ((len = is.read(bytes)) != -1) {
// outputStream.write(bytes, 0, len);//将读到的字节写入输出流
// }
// is.close();
// String content=outputStream.toString();
// outputStream.close();
//
//
//
//
// Paragraph paragraph1 = new Paragraph();
// Chunk timeChunk = new Chunk(content);
//
// paragraph1.add(timeChunk);
// document.add(paragraph1);
// document.close();
// output.close();
// FileOutputStream fileOutputStream = new FileOutputStream("D:\\123.pdf");
// fileOutputStream.write(output.toByteArray());
// }catch (Exception e){
// System.err.println(e);
// }
// }
//public static void main(String[] args) throws FileNotFoundException {
// String fileEnd = "xlsx";
// try {
FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\333.pdf"));
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// InputStream fileInput = new FileInputStream(new File("D:\\qqqq.xlsx"));
//
// IConverter converter = LocalConverter.builder().build();
//
// if(fileEnd.equals("doc")){
// converter.convert(fileInput)
// .as(DocumentType.DOC)
// .to(output)
// .as(DocumentType.PDF).execute();
//
// } else if(fileEnd.equals("docx")){
// converter.convert(fileInput)
// .as(DocumentType.DOCX)
// .to(output)
// .as(DocumentType.PDF).execute();
// }
// else if(fileEnd.equals("xlsx")){
// converter.convert(fileInput)
// .as(DocumentType.XLSX)
// .to(output)
// .as(DocumentType.PDF).execute();
// }
// else if(fileEnd.equals("xls")){
// converter.convert(fileInput)
// .as(DocumentType.XLS)
// .to(output)
// .as(DocumentType.PDF).execute();
// }
// output.close();
// fileInput.close();
// FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\daqyqqqq.pdf"));
// fileOutputStream.write(output.toByteArray());
// fileOutputStream.close();
// } catch (Exception e) {
// System.err.println(e);
// }finally {
// }
//
//}
}