
poi 3.16 word转PDF
poi 3.16 word转PDF(支持doc和docx)word转PDF用于在线预览
所需要的jar包第一个org.apache.poi poi3.16 第二个org.apache.poi poi3.16 第三个org.Spire Spire0.0.1 system ${project.basedir}/src/main/resources/lib/Spire.Doc.jar 第三个包我下载到我本地了 可以上网搜一下 网址:https://repo.e-iceblue.cn/#browse/browse:maven-public:e-iceblue%2Fspire.office%2F3.4.1%2Fspire.office-3.4.1.jar 如果用这个jar包转 是带水印的 而且只能转3页 或者500行 超过就不显示了 这里只是用它把doc转成docx 我自己这个jar包转格式时不带水印 不知道网上下载的带不带 如果需要去水印的jar包可以加我QQ找我要:279625695 (如果用官网上的jar包提示下载不下来 它这个需要配一下指向的私服 要不下载不下来)
代码:
package chzy.test.zipORrar;
import com.spire.doc.document;
import com.spire.doc.FileFormat;
import fr.opensagres.poi.xwpf.converter.core.utils.StringUtils;
import org.apache.commons.collections4.MapUtils;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordtoPDF {
public static void main(String[] args) {
String url ="C:\Users\Administrator\Desktop\新建文件夹\褚中义-java7年.docx";
File file=new File(url);
String filenameMax=file.getName();
String filename=filenameMax.substring(0, filenameMax.indexOf("."));
try {
doc2pdf(url, "D:\"+filename+".pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void docTodOcx(String path,String outPath){
document dc = new document();
dc.loadFromFile(path);
dc.saveToFile(outPath, FileFormat.Docx_2013);
dc.close();
}
public static void doc2pdf(String inPath, String outPath)throws IOException {
// 是否需清除中间转换的docx文档
Boolean isDelete = false;
String fileType = inPath.substring(inPath.lastIndexOf(".")).toLowerCase();
if ("doc".equals(fileType)){
docTodOcx(inPath,inPath+"x");
inPath = inPath+"x";
isDelete = true;
}
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream=null;
try {
fileInputStream = new FileInputStream(inPath);
XWPFdocument xwpfdocument = new XWPFdocument(fileInputStream);
PdfOptions pdfOptions = PdfOptions.create();
fileOutputStream = new FileOutputStream(outPath);
PdfConverter.getInstance().convert(xwpfdocument,fileOutputStream,pdfOptions);
} catch (IOException e) {
e.printStackTrace();
}finally {
fileInputStream.close();
fileOutputStream.close();
if (isDelete){
deleteDocx(inPath);
}
}
}
public static void deleteDocx(String path){
File file = new File(path);
file.delete();
}
}
##注意事项
1.word文档内尽量使用宋体,如果不使用宋体可以会导致这样空白的情况:
2.word文档内如果包含表格 和第一点一样 宋体! 宋体! 宋体!
3.如果项目放到linux上报错 一般都是linux未安装字体库,把windows字体库安装到linux上就行了(自行百度)