用java统计pdf,ppt,pptx,doc,docx文件的总页码

来源:互联网 发布:网络流量监测软件 编辑:程序博客网 时间:2024/04/30 11:51

(说明: 全文的path是指文件的全路径,也可以直接写文件名,看你的文件所在的位置)

一.   对于pdf文件是最好操作的,直接调用iText库的相关函数

    iText是sourceforge上的一个项目,一个开源的用于生成pdf文档的java和c#类库。

   代码如下:

   PdfReader reader = new PdfReader(path);

  int pages = reader.getNumberOfPages();

二.    对于office类文件的处理, 选择的是用POI来实现目的.

    1. 先下载好POI所用到的jar包

    我这边是下载了8个jar包,分别是dom4j-1.6.1.jar,geronimo-stax-api_1.0_spec-1.0.jar,ooxml-schemas-1.0.jar,openxml4j-bin-beta.jar,poi-3.5-beta6-20090622.jar,poi-ooxml-3.5-beta6-20090622.jar,poi-scratchpad-3.5-beta6-20090622.jar,xmlbeans-2.3.0.jar.

    2.代码如下:

       对于ppt文件,

         FileInputStream fis = new FileInputStream(path);
 SlideShow pptfile = new SlideShow(new HSLFSlideShow(fis));
 int  pages = pptfile.getSlides().length;

       对于pptx文件:

        XSLFSlideShow fis = new XSLFSlideShow(path);
XMLSlideShow pptxfile = new XMLSlideShow(fis);
int pages = pptxfile.getSlides().length;

       对于docx文件

         FileInputStream docx = new FileInputStream(path);
XWPFDocument docxfile = new XWPFDocument(docx);
int pages = docxfile.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();

        对于doc文件,由于很多doc文件不在SummaryInformation部分存储页码信息,导致用POI计算的总页码出问题,所以此处采用先转为pdf文件,然后计算总页码

      String pdfName = docToPdf(path);
PdfReader reader = new PdfReader(pdfName);
int pages = reader.getNumberOfPages();
File file = new File(pdfName);
if(file.exists()){
file.delete();
}

   3.doc转为pdf

     采用jacob.jar来调用activeX控件

      1)配置环境

          只需要一个jar文件 --->jacob.jar,把jacob.dll文件放入到c:/windows/system32中

    2)代码如下:

   public String docToPdf(String filename) {
int wdDoNotSaveChanges = 0;// 不保存待定的更改
int wdFormatPDF = 17;// PDF 格式
String toFilename = filename.substring(0, filename.lastIndexOf(".")) + ".pdf";
ActiveXComponent app = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);


Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs,//
"Open", //
filename,// FileName
false,// ConfirmConversions
true // ReadOnly
).toDispatch();


File tofile = new File(toFilename);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,//
"SaveAs", //
toFilename, // FileName
wdFormatPDF);


Dispatch.call(doc, "Close", false);
long end = System.currentTimeMillis();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (app != null)
app.invoke("Quit", wdDoNotSaveChanges);
}
return toFilename;
}

  


0 0