poi 3.16 word转PDF
poi 3.16 word转PDF(支持doc和docx)
word转PDF用于在线预览
所需要的jar包
第一个
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
第二个
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
第三个
<groupId>org.Spire</groupId>
<artifactId>Spire</artifactId>
<version>0.0.1</version>
<scope>system</scope>
<systemPath>
${project.basedir}/src/main/resources/lib/Spire.Doc.jar
</systemPath>
第三个包我下载到我本地了 可以上网搜一下
网址: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();
}
}
/**
* doc转docx(用第三个jar包)
* @param path
* @param outPath
* @return
*/
public static void docTodOcx(String path,String outPath){
Document dc = new Document();
dc.loadFromFile(path);
dc.saveToFile(outPath, FileFormat.Docx_2013);
dc.close();
}
/**
* word转pdf
* @param inPath
* @param outPath
* @return
*/
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);
}
}
}
/**
* 清除临时转换的docx
* @param path
*/
public static void deleteDocx(String path){
File file = new File(path);
file.delete();
}
}
##注意事项
1.word文档内尽量使用宋体,如果不使用宋体可以会导致这样空白的情况:
2.word文档内如果包含表格 和第一点一样 宋体! 宋体! 宋体!
3.如果项目放到linux上报错 一般都是linux未安装字体库,把windows字体库安装到linux上就行了(自行百度)