您的位置:首页 > 其它

word文档 pdf在线预览方案

2016-06-29 11:34 393 查看
word转pdf  

往java jdk的bin 目录下加文件jacob-1.18-M3-x64.dll或者jacob-1.18-M3-x86.dll 不记得自己jdk啥版本的就都加好了 

word转pdf的代码

public class Word2PDF {

  static final int wdDoNotSaveChanges = 0;

  static final int wdFormatPDF = 17;// PDF 格式

  public static void main(String[] args) {

    List<File> words = listWordFiles(new File("G:\\chen"));

    for (File file : words) {

      word2pdf(file);

    }

  }

  public static void word2pdf(File file) {

    if (file.exists() && file.canExecute() && file.isFile()) {

      String fileName = file.getName();

      int lastDotIndex = fileName.lastIndexOf(".");

      String toFileName = fileName.substring(0, lastDotIndex) + ".pdf";

      String toFilePath = file.getParent() + "/" + toFileName;

      System.out.println("启动Word...");

      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("打开文档..." + file.getAbsolutePath());

        Dispatch doc = Dispatch.call(docs, "Open",  file.getAbsolutePath(), false,true ).toDispatch();

        System.out.println("转换文档到PDF..." + toFilePath);

        File tofile = new File(toFilePath);

        if (tofile.exists()) {

          tofile.delete();

        }

        Dispatch.call(doc,"SaveAs", toFilePath,  wdFormatPDF);

        Dispatch.call(doc, "Close", false);

        long end = System.currentTimeMillis();

        System.out.println("转换完成..用时:" + (end - start) + "ms.");

      } catch (Exception e) {

        e.printStackTrace();

        System.out.println("文档转换失败:" + e.getMessage());

      } finally {

        if (app != null)

          app.invoke("Quit", wdDoNotSaveChanges);

      }

    }

  }

}

public class LineFileWriter {

  private final static String TAG = "\t";

  private String separator;

  private BufferedWriter writer;

  public LineFileWriter(File toFile) throws IOException {

    this(toFile, TAG);

  }

  public LineFileWriter(File toFile, String separator) throws IOException {

    this.separator = separator;

    if (!toFile.getParentFile().exists()) {

      toFile.getParentFile().mkdirs();

    }

    writer = new BufferedWriter(new FileWriter(toFile));

  }

  public void write(String... terms) throws IOException {

    for (String term : terms) {

      writer.write(term);

      writer.write(separator);

    }

    writer.newLine();

  }

  public void close() throws IOException {

    writer.flush();

    writer.close();

  }

}

转成pdf后 有两种预览方式 

 一种 直接用pdf.js   只了解过 没实际用过 哈哈

一种 用  flexpaper  这个麻烦些   他需要把pdf转成swf格式 才行 可以下个swfTools  

辅助代码

public class PDF2SWF {

  public final static String replaceBase = "G:\\chen\\";

  public final static String CMD_PDF_2_SWF = "E:\\Program Files (x86)\\SWFTools\\pdf2swf.exe";

  public static void main(String[] args) throws IOException {

    List<File> words = listWordFiles(new File("G:\\chen\\"));

    LineFileWriter infoWriter = new LineFileWriter(new File("E:\\chen\\info.log"));

    LineFileWriter errWriter = new LineFileWriter(new File("E:\\chen\\err.log"));

    for (File word : words) {

      pdf2swf(word, infoWriter, errWriter);

    }

    infoWriter.close();

    errWriter.close();

  }

  public static void pdf2swf(File docFile, LineFileWriter infoWriter, LineFileWriter errWriter) {

    try {

      long startTime = System.currentTimeMillis();

      String docAbsolutePath = docFile.getAbsolutePath();

      String fileKey = docAbsolutePath.replace(replaceBase, "");

      String pdfAbsolutePath = docAbsolutePath.replace(".docx", ".pdf").replace(".doc", ".pdf");

      File pdfFile = new File(pdfAbsolutePath);

      String swfBasePath = pdfAbsolutePath.replace(".pdf", "");

      PDDocument doc = PDDocument.load(pdfFile);

      int pageCount = doc.getNumberOfPages();

      doc.close();

      boolean result = true;

      System.out.println("处理:" + pdfAbsolutePath + ",页数:" + String.valueOf(pageCount) + "");

      for (int i = 1; i <= pageCount; i++) {

        String command = CMD_PDF_2_SWF + " " + pdfFile.getAbsolutePath() + " -o " + swfBasePath + "_" + i

            + ".swf -f -T 9 -t -s storeallcharacters -s linknameurl -p " + i;

        ArrayList commands = commandLineAsList(command);

        ProcessBuilder pb = new ProcessBuilder(commands);

        pb.redirectErrorStream(true);

        Process p = pb.start();

        BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line;

        while ((line = is.readLine()) != null) {

          if (line.toLowerCase().startsWith("warning")) {

            errWriter.write(pdfAbsolutePath, "WARNING: " + line, String.valueOf(i));

          } else if (line.toLowerCase().startsWith("error")) {

            errWriter.write(pdfAbsolutePath, "ERROR:" + line, String.valueOf(i));

            result = false;

          } else if (line.toLowerCase().startsWith("fatal")) {

            errWriter.write(pdfAbsolutePath, "FATAL:" + line, String.valueOf(i));

            result = false;

          } else {

            // infoWriter.write(pdfFile.getAbsolutePath(), pageCount + "");

            // System.out.println("\t" + line);

          }

          try {

            p.waitFor();

          } catch (InterruptedException e) {

            e.printStackTrace();

            errWriter.write(pdfAbsolutePath, "FATAL:" + line, String.valueOf(i));

            result = false;

          }

        }

      }

      if (result) {

        infoWriter.write(fileKey, String.valueOf(pageCount));

      }

      System.out.println("用时:" + (System.currentTimeMillis() - startTime) + "毫秒");

      System.out.println();

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

  public static ArrayList commandLineAsList(String commandLine) {

    ArrayList commands = new ArrayList();

    String elt = "";

    boolean insideString = false;

    for (int i = 0; i < commandLine.length(); i++) {

      char c = commandLine.charAt(i);

      if (!insideString && (c == ' ' || c == '\t')) {

        if (elt.length() > 0) {

          commands.add(elt);

          elt = "";

        }

        continue;

      } else
4000
if (c == '"') {

        insideString = !insideString;

      }

      elt += c;

    }

    if (elt.length() > 0) {

      commands.add(elt);

    }

    return commands;

  }

  public static List<File> listWordFiles(File file) {

    List<File> fs = new ArrayList<>();

    if (file.isDirectory()) {

      File[] files = file.listFiles();

      for (File f : files) {

        if (f.isFile() && isWordFile(f)) {

          fs.add(f);

        } else if (f.isDirectory()) {

          fs.addAll(listWordFiles(f));

        }

      }

    }

    return fs;

  }

  public static boolean isWordFile(File file) {

    return file != null && file.isFile() && (file.getName().endsWith(".doc") || file.getName().endsWith(".docx"));

  }

}

前端使用  

先去下载 flexpaper.js 和FlexPaperViewer.swf

<div id="documentViewer" class="flexpaper_viewer" style="width:760px;height:1000px"></div>

js:

function getDocumentUrl(document){
var numPages = ${paper.swfCount};
var id = ${paper.id};
var url = "{"+ id +"/swf?pageNum=[*,0],{numPages}}";
url = url.replace("{numPages}",numPages);
return url;
}

$('#documentViewer').FlexPaperViewer(
           { config : {

               SWFFile :  escape(getDocumentUrl()),
               Scale : 1.0,
               ZoomTransition : 'easeOut',
               ZoomTime : 0.5,
               ZoomInterval : 0.1,
               FitPageOnLoad : false,
               FitWidthOnLoad : true,
               FullScreenAsMaxWindow : false,
               ProgressiveLoading : false,
               MinZoomSize : 0.1,
               MaxZoomSize : 5,
               SearchMatchAll : false,
               InitViewMode : 'Portrait',
               RenderingOrder : 'flash',
               StartAtPage : '',
               ViewModeToolsVisible : true,
               ZoomToolsVisible : true,
               NavToolsVisible : true,
               CursorToolsVisible : true,
               SearchToolsVisible : true,
               WMode : 'opaque',
               key : 'XXXXXXX',
               localeChain: 'zh_CN'
           }}
   );

大致如此 都是前人的智慧,掏出来做个笔记
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  word pdf