FileHandlerService.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package cn.keking.service;
  2. import cn.keking.config.ConfigConstants;
  3. import cn.keking.model.FileAttribute;
  4. import cn.keking.model.FileType;
  5. import cn.keking.service.cache.CacheService;
  6. import cn.keking.utils.FileUtils;
  7. import cn.keking.utils.WebUtils;
  8. import com.aspose.cad.Color;
  9. import com.aspose.cad.fileformats.cad.CadDrawTypeMode;
  10. import com.aspose.cad.imageoptions.CadRasterizationOptions;
  11. import com.aspose.cad.imageoptions.PdfOptions;
  12. import org.apache.pdfbox.pdmodel.PDDocument;
  13. import org.apache.pdfbox.rendering.ImageType;
  14. import org.apache.pdfbox.rendering.PDFRenderer;
  15. import org.apache.pdfbox.tools.imageio.ImageIOUtil;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import org.springframework.beans.factory.annotation.Value;
  19. import org.springframework.stereotype.Component;
  20. import org.springframework.util.StringUtils;
  21. import javax.servlet.http.HttpServletRequest;
  22. import java.awt.image.BufferedImage;
  23. import java.io.*;
  24. import java.net.URLEncoder;
  25. import java.nio.charset.StandardCharsets;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import java.util.Map;
  29. /**
  30. * @author yudian-it
  31. * @date 2017/11/13
  32. */
  33. @Component
  34. public class FileHandlerService {
  35. private final Logger logger = LoggerFactory.getLogger(FileHandlerService.class);
  36. private static final String DEFAULT_CONVERTER_CHARSET = System.getProperty("sun.jnu.encoding");
  37. private final String fileDir = ConfigConstants.getFileDir();
  38. private final CacheService cacheService;
  39. @Value("${server.tomcat.uri-encoding:UTF-8}")
  40. private String uriEncoding;
  41. public FileHandlerService(CacheService cacheService) {
  42. this.cacheService = cacheService;
  43. }
  44. /**
  45. * @return 已转换过的文件集合(缓存)
  46. */
  47. public Map<String, String> listConvertedFiles() {
  48. return cacheService.getPDFCache();
  49. }
  50. /**
  51. * @return 已转换过的文件,根据文件名获取
  52. */
  53. public String getConvertedFile(String key) {
  54. return cacheService.getPDFCache(key);
  55. }
  56. /**
  57. * @param key pdf本地路径
  58. * @return 已将pdf转换成图片的图片本地相对路径
  59. */
  60. public Integer getConvertedPdfImage(String key) {
  61. return cacheService.getPdfImageCache(key);
  62. }
  63. /**
  64. * 从路径中获取文件负
  65. *
  66. * @param path 类似这种:C:\Users\yudian-it\Downloads
  67. * @return 文件名
  68. */
  69. public String getFileNameFromPath(String path) {
  70. return path.substring(path.lastIndexOf(File.separator) + 1);
  71. }
  72. /**
  73. * 获取相对路径
  74. *
  75. * @param absolutePath 绝对路径
  76. * @return 相对路径
  77. */
  78. public String getRelativePath(String absolutePath) {
  79. return absolutePath.substring(fileDir.length());
  80. }
  81. /**
  82. * 添加转换后PDF缓存
  83. *
  84. * @param fileName pdf文件名
  85. * @param value 缓存相对路径
  86. */
  87. public void addConvertedFile(String fileName, String value) {
  88. cacheService.putPDFCache(fileName, value);
  89. }
  90. /**
  91. * 添加转换后图片组缓存
  92. *
  93. * @param pdfFilePath pdf文件绝对路径
  94. * @param num 图片张数
  95. */
  96. public void addConvertedPdfImage(String pdfFilePath, int num) {
  97. cacheService.putPdfImageCache(pdfFilePath, num);
  98. }
  99. /**
  100. * 获取redis中压缩包内图片文件
  101. *
  102. * @param fileKey fileKey
  103. * @return 图片文件访问url列表
  104. */
  105. public List<String> getImgCache(String fileKey) {
  106. return cacheService.getImgCache(fileKey);
  107. }
  108. /**
  109. * 设置redis中压缩包内图片文件
  110. *
  111. * @param fileKey fileKey
  112. * @param imgs 图片文件访问url列表
  113. */
  114. public void putImgCache(String fileKey, List<String> imgs) {
  115. cacheService.putImgCache(fileKey, imgs);
  116. }
  117. /**
  118. * 对转换后的文件进行操作(改变编码方式)
  119. *
  120. * @param outFilePath 文件绝对路径
  121. */
  122. public void doActionConvertedFile(String outFilePath) {
  123. StringBuilder sb = new StringBuilder();
  124. try (InputStream inputStream = new FileInputStream(outFilePath);
  125. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CONVERTER_CHARSET))) {
  126. String line;
  127. while (null != (line = reader.readLine())) {
  128. if (line.contains("charset=gb2312")) {
  129. line = line.replace("charset=gb2312", "charset=utf-8");
  130. }
  131. sb.append(line);
  132. }
  133. // 添加sheet控制头
  134. sb.append("<script src=\"js/jquery-3.0.0.min.js\" type=\"text/javascript\"></script>");
  135. sb.append("<script src=\"js/excel.header.js\" type=\"text/javascript\"></script>");
  136. sb.append("<link rel=\"stylesheet\" href=\"bootstrap/css/bootstrap.min.css\">");
  137. } catch (IOException e) {
  138. e.printStackTrace();
  139. }
  140. // 重新写入文件
  141. try (FileOutputStream fos = new FileOutputStream(outFilePath);
  142. BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8))) {
  143. writer.write(sb.toString());
  144. } catch (IOException e) {
  145. e.printStackTrace();
  146. }
  147. }
  148. /**
  149. * pdf文件转换成jpg图片集
  150. * @param pdfFilePath pdf文件路径
  151. * @param pdfName pdf文件名称
  152. * @param baseUrl 基础访问地址
  153. * @return 图片访问集合
  154. */
  155. public List<String> pdf2jpg(String pdfFilePath, String pdfName, String baseUrl) {
  156. List<String> imageUrls = new ArrayList<>();
  157. Integer imageCount = this.getConvertedPdfImage(pdfFilePath);
  158. String imageFileSuffix = ".jpg";
  159. String pdfFolder = pdfName.substring(0, pdfName.length() - 4);
  160. String urlPrefix;
  161. try {
  162. urlPrefix = baseUrl + URLEncoder.encode(URLEncoder.encode(pdfFolder, uriEncoding).replaceAll("\\+", "%20"), uriEncoding);
  163. } catch (UnsupportedEncodingException e) {
  164. logger.error("UnsupportedEncodingException", e);
  165. urlPrefix = baseUrl + pdfFolder;
  166. }
  167. if (imageCount != null && imageCount > 0) {
  168. for (int i = 0; i < imageCount; i++)
  169. imageUrls.add(urlPrefix + "/" + i + imageFileSuffix);
  170. return imageUrls;
  171. }
  172. try {
  173. File pdfFile = new File(pdfFilePath);
  174. PDDocument doc = PDDocument.load(pdfFile);
  175. int pageCount = doc.getNumberOfPages();
  176. PDFRenderer pdfRenderer = new PDFRenderer(doc);
  177. int index = pdfFilePath.lastIndexOf(".");
  178. String folder = pdfFilePath.substring(0, index);
  179. File path = new File(folder);
  180. if (!path.exists() && !path.mkdirs()) {
  181. logger.error("创建转换文件【{}】目录失败,请检查目录权限!", folder);
  182. }
  183. String imageFilePath;
  184. for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
  185. imageFilePath = folder + File.separator + pageIndex + imageFileSuffix;
  186. BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 105, ImageType.RGB);
  187. ImageIOUtil.writeImage(image, imageFilePath, 105);
  188. imageUrls.add(urlPrefix + "/" + pageIndex + imageFileSuffix);
  189. }
  190. doc.close();
  191. this.addConvertedPdfImage(pdfFilePath, pageCount);
  192. } catch (IOException e) {
  193. logger.error("Convert pdf to jpg exception, pdfFilePath:{}", pdfFilePath, e);
  194. }
  195. return imageUrls;
  196. }
  197. /**
  198. * cad文件转pdf
  199. * @param inputFilePath cad文件路径
  200. * @param outputFilePath pdf输出文件路径
  201. * @return 转换是否成功
  202. */
  203. public boolean cadToPdf(String inputFilePath, String outputFilePath) {
  204. com.aspose.cad.Image cadImage = com.aspose.cad.Image.load(inputFilePath);
  205. CadRasterizationOptions cadRasterizationOptions = new CadRasterizationOptions();
  206. cadRasterizationOptions.setLayouts(new String[]{"Model"});
  207. cadRasterizationOptions.setNoScaling(true);
  208. cadRasterizationOptions.setBackgroundColor(Color.getWhite());
  209. cadRasterizationOptions.setPageWidth(cadImage.getWidth());
  210. cadRasterizationOptions.setPageHeight(cadImage.getHeight());
  211. cadRasterizationOptions.setPdfProductLocation("center");
  212. cadRasterizationOptions.setAutomaticLayoutsScaling(true);
  213. cadRasterizationOptions.setDrawType(CadDrawTypeMode.UseObjectColor);
  214. PdfOptions pdfOptions = new PdfOptions();
  215. pdfOptions.setVectorRasterizationOptions(cadRasterizationOptions);
  216. File outputFile = new File(outputFilePath);
  217. OutputStream stream;
  218. try {
  219. stream = new FileOutputStream(outputFile);
  220. cadImage.save(stream, pdfOptions);
  221. cadImage.close();
  222. return true;
  223. } catch (FileNotFoundException e) {
  224. logger.error("PDFFileNotFoundException,inputFilePath:{}", inputFilePath, e);
  225. return false;
  226. }
  227. }
  228. /**
  229. * 获取文件属性
  230. *
  231. * @param url url
  232. * @return 文件属性
  233. */
  234. public FileAttribute getFileAttribute(String url, HttpServletRequest req) {
  235. FileAttribute attribute = new FileAttribute();
  236. String suffix;
  237. FileType type;
  238. String fileName;
  239. String fullFileName = WebUtils.getUrlParameterReg(url, "fullfilename");
  240. if (StringUtils.hasText(fullFileName)) {
  241. fileName = fullFileName;
  242. type = FileType.typeFromFileName(fullFileName);
  243. suffix = FileUtils.suffixFromFileName(fullFileName);
  244. } else {
  245. fileName = WebUtils.getFileNameFromURL(url);
  246. type = FileType.typeFromUrl(url);
  247. suffix = WebUtils.suffixFromUrl(url);
  248. }
  249. attribute.setType(type);
  250. attribute.setName(fileName);
  251. attribute.setSuffix(suffix);
  252. attribute.setUrl(url);
  253. if (req != null) {
  254. String officePreviewType = req.getParameter("officePreviewType");
  255. String fileKey = WebUtils.getUrlParameterReg(url,"fileKey");
  256. if (StringUtils.hasText(officePreviewType)) {
  257. attribute.setOfficePreviewType(officePreviewType);
  258. }
  259. if (StringUtils.hasText(fileKey)) {
  260. attribute.setFileKey(fileKey);
  261. }
  262. }
  263. return attribute;
  264. }
  265. }