依赖
<!--word转pdf-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.12</version>
</dependency>
//license.xml 加上这个可以去除水印
<?xml version="1.0" encoding="UTF-8" ?>
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
//如果需要替换图片的工具类
ReplaceAndInsertImage
package cc.mrbird.febs.common.utils;
/**
* @author sunye
* @date 2022/9/15--16:52
*/
import com.aspose.words.*;
public class ReplaceAndInsertImage implements IReplacingCallback {
private String url;
public ReplaceAndInsertImage(String url)
{
this.url = url;
}
@Override
public int replacing(ReplacingArgs e) throws Exception {
//获取当前节点
Node node = e.getMatchNode();
//获取当前文档
Document doc = (Document)node.getDocument();
DocumentBuilder builder = new DocumentBuilder(doc);
//将光标移动到指定节点
builder.moveTo(node);
//插入图片
builder.insertImage(url);
return ReplaceAction.REPLACE;
}
}
//word转pdf主类
package cc.mrbird.febs.common.utils;
import com.aspose.words.*;
import java.io.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author sunye
* @date 2022/9/15--13:13
*/
public class Word2PdfAsposeUtil {
private static final Logger log = LoggerFactory.getLogger(Word2PdfAsposeUtil.class);
/**
* * 水印验证 * @return
*/
public static boolean getLicense() {
boolean result = false;
InputStream is = null;
try {
/*Resource resource = new ClassPathResource("license.xml");
is = resource.getInputStream();*/
//InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license/license.xml");
// license.xml应放在..\WebRoot\WEB-INF\classes路径下
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* * word转换pdf * @param inPath * @param outPath * @return
*/
public static boolean doc2pdf(String inPath, String outPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return false;
}
FileOutputStream os = null;
try {
long old = System.currentTimeMillis();
File file = new File(outPath); // 新建一个空白pdf文档
os = new FileOutputStream(file);
Document doc = new Document(inPath); // Address是将要被转化的word文档
doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
// EPUB, XPS, SWF 相互转换
long now = System.currentTimeMillis();
System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* * 创建pdf文件 * @param pdfPath
*/
public static void createPdf(String pdfPath) {
// Creating PDF document object
PDDocument document = new PDDocument();
// Add an empty page to it
document.addPage(new PDPage());
// Saving the document
try {
document.save(pdfPath);
//document.save("E:/BlankPdf.pdf");
// Closing the document
document.close();//
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("PDF created");
}
//参考 https://blog.csdn.net/CDWLX/article/details/123678265
public static boolean docpdf(String inPath, String outPath, Map<String, String> map) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return false;
}
FileOutputStream os = null;
try {
long old = System.currentTimeMillis();
File file = new File(outPath); // 新建一个空白pdf文档
os = new FileOutputStream(file);
Document doc = new Document(inPath); // Address是将要被转化的word文档
for (Map.Entry<String, String> entry : map.entrySet()) {
if ("img".equals(entry.getKey())) {
ReplaceAndInsertImage replaceAndInsertImage = new ReplaceAndInsertImage(entry.getValue());
doc.getRange().replace(Pattern.compile("img"), replaceAndInsertImage, false);//将指定内容位置的内容替换成新的图片,这个指定内容,需要传正则表达式
} else {
doc.getRange().replace(Pattern.compile(entry.getKey()), entry.getValue());
}
}
doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
// EPUB, XPS, SWF 相互转换
long now = System.currentTimeMillis();
System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static void removeMark() {
try {
log.info("【开始加载去除水印】");
Class<?> aClass = Class.forName("com.aspose.words.zzXyu");
java.lang.reflect.Field zzYAC = aClass.getDeclaredField("zzZXG");
zzYAC.setAccessible(true);
java.lang.reflect.Field modifiersField = zzYAC.getClass().getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(zzYAC, zzYAC.getModifiers() & ~Modifier.FINAL);
zzYAC.set(null, new byte[]{76, 73, 67, 69, 78, 83, 69, 68});
log.info("【加载去除水印完成】");
} catch (Exception e) {
log.error("apose word :{}", e);
}
}
public static void main(String[] arg) {
//直接转换
// String doc2Path = "D:\\opt\\sunyejianli.doc";
// String pdf2Path = "D:\\opt\\sunyejianli.pdf";
// Word2PdfAsposeUtil.doc2pdf(doc2Path, pdf2Path);
//可以替换文字和图片
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("mobile", "137********");
valuesMap.put("name", "酒井法子");
// valuesMap.put("img", "******.jpg");
String pdfPath = "F:\\test\\jin.pdf";
String docPath = "F:\\test\\jin.docx";
Word2PdfAsposeUtil.docpdf(docPath, pdfPath, valuesMap);
}
}