import com.aspose.cells.*;
import com.aspose.cells.PdfSaveOptions;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* 在项目创建一个libs目录,aspose-cells的包放入该目录(aspose-cells的包无法直接拉取依赖)
* 在build.gradle引入libs的包:compile fileTree(dir:'libs',include:['*.jar'])
* jar
* 1: aspose-cells-20.6.jar
* 2: itextpdf-5.5.1.jar
* 3: lombok-1.18.10.jar
*
* @Description
* @Author 不爱写代码的码农
* @Date 2020/6/28 14:02
*/
@Slf4j
public class ISPTest {
// Excel转PDF,支持多sheet页,水印覆盖
public static void main(String[] args) throws Exception {
String sourceFilePath = "D:/test/质量系数以及缺陷分析表V2_0.xls";
String tmpFilePath = "D:/test/tmp.pdf";
String taskFilePathd = "D:/test/result.pdf";
excel2pdf(sourceFilePath,tmpFilePath, taskFilePathd);
}
public static void excel2pdf(String sourceFilePath,String tmpFilePath ,String taskFilePathd) throws Exception {
try {
Workbook wb = new Workbook(sourceFilePath);
wb.save(tmpFilePath,SaveFormat.PDF);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);
// 所有sheet页都设置可见和自动缩放
allSheetVisibleAndAutoZoom(wb);
FileOutputStream fileOS = new FileOutputStream(tmpFilePath);
wb.save(fileOS, pdfSaveOptions);
fileOS.flush();
fileOS.close();
PdfReader reader = new PdfReader(tmpFilePath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(taskFilePathd));
// 处理水印
waterMaker(reader, stamper);
} catch (Exception e) {
log.info("Excel to PDF task fail");
}
}
// 处理水印
private static void waterMaker(PdfReader reader, PdfStamper stamper) throws DocumentException, IOException {
int numberOfPages = reader.getNumberOfPages();
System.out.println(numberOfPages);
// 覆盖每一页的水印
if (numberOfPages > 0){
for (int i = 1; i <= numberOfPages; i++) {
System.out.println("a: "+i);
PdfContentByte canvas = stamper.getOverContent(i);// 获取PDF内容
Rectangle pageSize = reader.getPageSize(i);
float height = pageSize.getHeight();
System.out.println(canvas.getHorizontalScaling());
float x,y,w,h;
x = 0;
y = height -15;
w = 430;
h = 15;
canvas.saveState();
canvas.setColorFill(BaseColor.WHITE); //遮挡层颜色:白色
canvas.rectangle(x, y, w, h);
canvas.fill();
canvas.restoreState();
}
}
stamper.close();
reader.close();
}
/**
* 所有sheet页都设置可见
* 所有sheet页都等比缩放
* @param wb
*/
private static void allSheetVisibleAndAutoZoom(Workbook wb){
for (int i= 1; i < wb.getWorksheets().getCount(); i++) {
// 每个sheet文件都设置可见
wb.getWorksheets().get(i).setVisible(true);
// 设置等比缩放
wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
}
}
}
还没有评论,来说两句吧...