实现思路:
1,由于现有的插件读取word的页数不是很准确,于是将word文件转换为PDF文件
2,读取PDF文件的页数以获取word文件的页数
需要的插件:链接:https://pan.baidu.com/s/1GTk890eKl1D4Izk03kyPPg
提取码:6535
1,word文件转PDF文件的插件 SaveAsPDFandXPS.exe
2,jacob插件 jacob dll文件以及jar包
3,itextpdf jar包
实现过程:
1,在Windows环境下安装word文件,不是WPS
2,安装SaveAsPDFandXPS
3,把dll文件放在Java的运行环境,jre的bin目录下,为了防止报错,JDK的bin目录下也放一个,注意与自己的电脑匹配就行(32位还是64位)
4,Java 运行环境1.7以上
5,创建Java Project,将itextpdf和jacob的两个jar包复制进去
6,word转换PDF的代码是:
package javaReadWordPage;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import org.omg.PortableInterceptor.DISCARDING;
import java.io.File;
/**
* 该方法实现word文件转换成PDF文件的功能
*/
public class Word2PdfUtil {
static final int wdDoNotSaveChanges = 0;
static final int wdFormatPDF = 17;
public static boolean word2pdf(String source,String target){
System.out.println("word 转PDF开始启动.....");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
try{
app = new ActiveXComponent("word.Application");
app.setProperty("Visible",false);
Dispatch docs = app.getProperty("Documents").toDispatch();
System.out.println("打开文档.....");
Dispatch doc = Dispatch.call(docs, "Open", source, false, true).toDispatch();
System.out.println("转换成PDF文件......"+target);
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();
System.out.println("文件转换用时:"+(end-start)+"ms");
return true;
}catch(Exception e ){
System.out.println("word 转换 PDF 出错:"+e.getMessage());
return false;
}finally {
if(app != null){
app.invoke("Quit",wdDoNotSaveChanges);
}
}
}
}
7,读取PDF文件页码的代码是:
package javaReadWordPage;
import com.itextpdf.text.pdf.PdfReader;
import java.io.File;
/**
* 该方法实现的是查看PDF文件页数的功能
*/
public class GetPdfPageNumber {
public static int getPdfPage(File file){
int pageCount = 0;
PdfReader reader;
try {
reader = new PdfReader("e://论证报告.pdf");
pageCount = reader.getNumberOfPages();
}catch (Exception e){
e.printStackTrace();
}
System.out.println(pageCount);
return pageCount;
}
}
8,测试