| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- package com.izouma.awesomeAdmin.web;
- import com.izouma.awesomeAdmin.exception.BusinessException;
- import com.izouma.awesomeAdmin.utils.FileUtils;
- import com.jacob.activeX.ActiveXComponent;
- import com.jacob.com.Dispatch;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.poi.util.TempFile;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.multipart.MultipartFile;
- import javax.annotation.PostConstruct;
- import javax.annotation.PreDestroy;
- import java.io.*;
- @Controller
- @Slf4j
- public class Word2PDFController {
- @PostMapping(value = "/word2pdf", produces = "application/pdf")
- @ResponseBody
- synchronized public byte[] word2pdf(@RequestParam("file") MultipartFile file) {
- log.info("开始转换");
- // 开始时间
- long start = System.currentTimeMillis();
- ActiveXComponent app = null;
- try {
- File word = TempFile.createTempFile("word2pdf", FileUtils.getExtension(file.getOriginalFilename()));
- File target = TempFile.createTempFile("word2pdf", ".pdf");
- FileUtils.write(file.getInputStream(), word);
- app = new ActiveXComponent("Word.Application");
- Dispatch documents = app.getProperty("Documents").toDispatch();
- System.out.println("打开文件: " + word.getPath());
- Dispatch document = Dispatch.call(documents, "Open", word.getPath(), false, true).toDispatch();
- if (target.exists()) {
- target.delete();
- }
- log.info("另存为: " + target.getPath());
- Dispatch.call(document, "SaveAs", target.getPath(), 17);
- Dispatch.call(document, "Close", false);
- long end = System.currentTimeMillis();
- log.info("转换成功,用时:" + (end - start) + "ms");
- return org.apache.commons.io.FileUtils.readFileToByteArray(target);
- } catch (Exception e) {
- log.error("转换失败", e);
- throw new BusinessException("转换失败" + e.getMessage());
- } finally {
- if (app != null) {
- app.invoke("Quit", 0);
- }
- }
- }
- }
|