package com.lingxu.base.common.util;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* <p>
* word 转 pdf 工具类
* </p>
*/
@Slf4j
public class Word2PdfUtil {
/**
* `word` 转 `pdf`
*
* @param wordBytes: word字节码
* @return 生成的`pdf`字节码
* @author li
* @date 2020/11/26 13:39
*/
@SneakyThrows(Exception.class)
public static byte[] wordBytes2PdfBytes(byte[] wordBytes) {
Document document = new Document(new ByteArrayInputStream(wordBytes));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
document.save(outputStream, SaveFormat.PDF);
// 返回生成的`pdf`字节码
return outputStream.toByteArray();
}
/**
* `word` 转 `pdf`
*
* @param wordBytes: word字节码
* @param pdfFilePath: 需转换的`pdf`文件路径
* @return 生成的`pdf`文件数据
* @author li
* @date 2020/11/26 13:39
*/
@SneakyThrows(Exception.class)
public static File wordBytes2PdfFile(byte[] wordBytes, String pdfFilePath) {
Document document = new Document(new ByteArrayInputStream(wordBytes));
document.save(pdfFilePath, SaveFormat.PDF);
return new File(pdfFilePath);
}
/**
* 将文件转换成byte数组
* @param filePath 文件File类 通过new File(文件路径)
* @return byte数组
*/
public static byte[] File2byte(File filePath) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
/**
* 将Byte数组转换成文件
* @param bytes 字节码
* @param filePath 文件路径
* @param fileName 文件名
*/
public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
word字节码数组转成pdf字节码数组
于 2022-02-21 17:14:01 首次发布