package com.zvalley.epp.util;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Stream;
@Slf4j
public class PdfUtil {
// 不保存待定的更改。
private static final int wdDoNotSaveChanges = 0;
// word转PDF 格式
private static final int wdFormatPDF = 17;
// 线程池队列
private static BlockingQueue<Dispatch> dispatchPool = new LinkedBlockingQueue<>();
// 线程池大小
private static int MAX_DISPATCH_SIZE = 10;
static {
for (int i = 0; i < MAX_DISPATCH_SIZE; i++) {
ActiveXComponent axc = new ActiveXComponent("Word.Application");
axc.setProperty("Visible", false);
Dispatch dispatch = axc.getProperty("Documents").toDispatch();
dispatchPool.add(dispatch);
}
}
/**
* @param source word路径
* @param target 生成的pdf路径
* @return
*/
public static boolean word2pdf(String source, String target) {
log.info("Word转PDF开始启动...");
long start = System.currentTimeMillis();
Dispatch dispatch = null;
try {
dispatch = getDispatch();
Dispatch doc = Dispatch.call(dispatch, "Open", source, false, true).toDispatch();
File toFile = new File(target);
if (toFile.exists()) {
toFile.delete();
}
Dispatch.call(doc, "SaveAs", target, wdFormatPDF);
Dispatch.call(doc, "Close", false);
long end = System.currentTimeMillis();
log.info("转换完成,用时:" + (end - start) + "ms");
return true;
} catch (Exception e) {
log.info("Word转PDF出错:" + e.getMessage());
return false;
} finally {
if (dispatch != null) {
relaseDispatch(dispatch);
}
}
}
@SneakyThrows
public static Dispatch getDispatch() {
return dispatchPool.take();
}
@SneakyThrows
public static void relaseDispatch(Dispatch dispatch) {
dispatchPool.add(dispatch);
}
}