说明
该工具类是基于poi包的流式文件(如doc、excel等)和版式文件(如pdf、ofd等)的操作工具类。
因为自己在开发相关功能的时候踩过一些坑,网上也很多例子都不适用,不是jar版本不对,要么就是各个jar不兼容,要么就是某些属性过时等等问题,所以在这里整合了一下。
相关链接
- aspos官网,可以查阅相关的api文档。
- doc、docx转html的功能。
使用前提
<dependency>
<groupId>com.aspose.cells</groupId>
<artifactId>cells-8.5.2 </artifactId>
<scope>system</scope>
<systemPath>${basedir}/lib/aspose-cells-8.5.2.jar</systemPath>
<version>8.5.2</version>
</dependency>
<dependency>
<groupId>com.aspose.words</groupId>
<artifactId>words-15.8.0-jdk16</artifactId>
<scope>system</scope>
<systemPath>${basedir}/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
<version>15.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
其中,cells-8.5.2需要在src同级的lib目录下添加下面的jar包:
相关jar包和配置
同理,words相关的jar包也是放在lib目录下。
代码
PS:因为这是实际项目需要到的功能才去编写的(针对本人遇到的问题整合的功能点
),所以只记录了使用过的功能,后续会更新其他功能…
目前已经整合好的功能
excel转pdf
pdf添加水印
word转图片
- 持续更新中…
import com.aspose.cells.*;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 基于poi包的流式文件和版式文件操作工具
*/
public class PoiUtil {
/**
* 获取license
* @return
*/
public static boolean getLicense(){
boolean result = false;
try {
InputStream is = PoiUtil.class.getClassLoader().getResourceAsStream("/file/license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
}catch (Exception e){
System.out.println(e);
}
return result;
}
/**
* excel转pdf
* @param excelFilePath excel文件全路径
* @param pdfFilePath pdf文件全路径
*/
public static boolean excelToPdf(String excelFilePath, String pdfFilePath){
if (!getLicense()){
return false;
}
try {
//创建excel工作簿
Workbook wb = new Workbook(excelFilePath);
//设置纸张水平居中打印
Worksheet worksheet = wb.getWorksheets().get(0);
PageSetup pageSetup = worksheet.getPageSetup();
pageSetup.setCenterHorizontally(true);
//设置保存PDF操作参数
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//pdfSaveOptions.setOnePagePerSheet(false);//把内容放在一张PDF 页面上
FileOutputStream fileOS = new FileOutputStream(new File(pdfFilePath));
wb.save(fileOS, pdfSaveOptions);
fileOS.close();
return true;
}catch (Exception e){
System.out.println(e);
}
return false;
}
/**
* pdf添加水印
* @param pdfFilePath pdf原文件全路径
* @param outPutFilePath 添加水印后的文件全路径
* @param waterMark 水印
* @return
*/
public static boolean addWaterMarkToPdf(String pdfFilePath, String outPutFilePath, String waterMark){
try {
PdfReader reader = new PdfReader(pdfFilePath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outPutFilePath));
//这里的字体设置比较关键,这个设置是支持中文的写法
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
int total = reader.getNumberOfPages() + 1;
PdfContentByte under;
com.itextpdf.text.Rectangle pageRect = null;
for (int i = 1; i < total; i++) {
pageRect = stamper.getReader().getPageSizeWithRotation(i);
int yNum = (int)(pageRect.getHeight() / (waterMark.length() * 15));
int xNum = (int)(pageRect.getWidth() / (waterMark.length() * 15));
int px = waterMark.length() * 25;
//x,y为水印的坐标
float x = 0l;
float y = 0l;
for (int j = 0; j < yNum; j++){
for (int r = 0; r < xNum; r++){
x = px * r;
y = px * j;
// 获得PDF最顶层
under = stamper.getOverContent(i);
under.saveState();
// set Transparency
PdfGState gs = new PdfGState();
// 设置透明度为0.5
gs.setFillOpacity(0.4f);
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 15);
under.setColorFill(BaseColor.GRAY);
// 水印文字成45度角倾斜
under.showTextAligned(Element.ALIGN_CENTER, waterMark, x, y, 45);
// 添加水印文字
under.endText();
under.setLineWidth(1f);
under.stroke();
under.restoreState();
}
}
}
stamper.close();
reader.close();
return true;
}catch (Exception e){
System.out.println(e);
}
return false;
}
/**
* word转图片
* @param wordFile word文件的输入流
* @param imageOutPutPath 生成图片保存在的文件目录
* @return
*/
public static boolean wordToImage(InputStream wordFile, String imageOutPutPath){
if (!getLicense()){
return false;
}
try {
com.aspose.words.Document doc = new com.aspose.words.Document(wordFile);
ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
options.setPrettyFormat(true);
options.setUseAntiAliasing(true);
options.setUseHighQualityRendering(true);
int pageCount = doc.getPageCount();
List<BufferedImage> pageImageList = new ArrayList<BufferedImage>();
for (int i = 0; i < pageCount; i++) {
ByteArrayOutputStream outps = new ByteArrayOutputStream();
options.setPageIndex(i);
doc.save(outps, options);
ImageInputStream imageInputStream = ImageIO.createImageInputStream(parse(outps));
pageImageList.add(ImageIO.read(imageInputStream));
}
for (int i = 0; i < pageImageList.size(); i++) {
byte[] bytes = imageToBytes(pageImageList.get(i));
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
inputstreamToFile(stream, imageOutPutPath + File.separator + String.valueOf(i) + ".jpeg");
}
return true;
}catch (Exception e){
System.out.println(e);
}
return false;
}
/**
* ByteArrayOutputStream转ByteArrayInputStream
* @param out
* @return
*/
public static ByteArrayInputStream parse(OutputStream out) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos = (ByteArrayOutputStream) out;
ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
return swapStream;
}catch (Exception e){
System.out.println(e);
}
return null;
}
/**
* BufferedImage转byte
* @param bImage
* @return
*/
private static byte[] imageToBytes(BufferedImage bImage) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(bImage, "jpeg", out);
} catch (IOException e) {
//log.error(e.getMessage());
}
return out.toByteArray();
}
/**
* inputStream转File
* @param input 文件的输入流
* @param fileName 文件名
* @return file
*/
private static File inputstreamToFile(InputStream input, String filePath){
File file = null;
try {
file = new File(filePath);
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = input.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
input.close();
return file;
}catch (Exception e){
System.out.println(e);
}
return file;
}
}
后续有新的功能开发,也会更新在这里,需要的伙伴可以收藏起来喔!
更新记录:
- 2022-09-05:第一次发布该文章,增加了
excel转pdf
、pdf添加水印
、word转图片
。