Word2PDFController.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package com.izouma.awesomeAdmin.web;
  2. import com.izouma.awesomeAdmin.exception.BusinessException;
  3. import com.izouma.awesomeAdmin.utils.FileUtils;
  4. import com.jacob.activeX.ActiveXComponent;
  5. import com.jacob.com.Dispatch;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.apache.poi.util.TempFile;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestParam;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import javax.annotation.PostConstruct;
  15. import javax.annotation.PreDestroy;
  16. import java.io.*;
  17. @Controller
  18. @Slf4j
  19. public class Word2PDFController {
  20. @PostMapping(value = "/word2pdf", produces = "application/pdf")
  21. @ResponseBody
  22. synchronized public byte[] word2pdf(@RequestParam("file") MultipartFile file) {
  23. log.info("开始转换");
  24. // 开始时间
  25. long start = System.currentTimeMillis();
  26. ActiveXComponent app = null;
  27. try {
  28. File word = TempFile.createTempFile("word2pdf", FileUtils.getExtension(file.getOriginalFilename()));
  29. File target = TempFile.createTempFile("word2pdf", ".pdf");
  30. FileUtils.write(file.getInputStream(), word);
  31. app = new ActiveXComponent("Word.Application");
  32. Dispatch documents = app.getProperty("Documents").toDispatch();
  33. System.out.println("打开文件: " + word.getPath());
  34. Dispatch document = Dispatch.call(documents, "Open", word.getPath(), false, true).toDispatch();
  35. if (target.exists()) {
  36. target.delete();
  37. }
  38. log.info("另存为: " + target.getPath());
  39. Dispatch.call(document, "SaveAs", target.getPath(), 17);
  40. Dispatch.call(document, "Close", false);
  41. long end = System.currentTimeMillis();
  42. log.info("转换成功,用时:" + (end - start) + "ms");
  43. return org.apache.commons.io.FileUtils.readFileToByteArray(target);
  44. } catch (Exception e) {
  45. log.error("转换失败", e);
  46. throw new BusinessException("转换失败" + e.getMessage());
  47. } finally {
  48. if (app != null) {
  49. app.invoke("Quit", 0);
  50. }
  51. }
  52. }
  53. }