@Override public Map<String,Object> addImg(MultipartFile file) throws Exception { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1); String getNowDate= FileUtil.getNowDate("yyyyMMdd"); String getNowDateNew= FileUtil.getNowDate("yyyyMMddHHmmssSSS"); AttchmentEntity attechment = new AttchmentEntity(); String newName=""; if(suffix.toLowerCase(Locale.ROOT).equals("gif") || suffix.toLowerCase(Locale.ROOT).equals("jpg") || suffix.toLowerCase(Locale.ROOT).equals("jepg")||suffix.toLowerCase(Locale.ROOT).equals("png")) { newName=saveFile(file,imgDir,getNowDate); attechment.setPngPath(getNowDate+"/"+newName); attechment.setPreviewAll(1); attechment.setPreview(1); }else{ newName= saveImgFile(file, imgDir, getNowDate); } attechment.setFilePath("/"+getNowDate+"/"+newName); attechment.setFileName(newName); // attechment.setTrxTypeName("拍卖申请表"); attechment.setOriginFileName(file.getOriginalFilename()); attechment.setFileSize(String.valueOf(file.getSize())); attchmentDao.saveReviewComments(attechment); Map<String,Object> map =new HashMap<>(); try { if (suffix.toLowerCase(Locale.ROOT).equals("doc") || suffix.toLowerCase(Locale.ROOT).equals("docx")) { String toFileName = imgDir + getNowDate + "/" + getNowDateNew + ".pdf"; WordToPdf d = new WordToPdf(); d.wordToPDF(imgDir + getNowDate + "/" + newName, toFileName); Map<String, Object> mps = pdf2Pic(toFileName, imgDir + "/pdfFile", attechment.getId()); //是否支持完整预览 attechment.setPreviewAll(Integer.parseInt(mps.get("previewAll").toString())); attechment.setPngPath(mps.get("pngPath").toString()); attechment.setPreview(1); } else if (suffix.toLowerCase(Locale.ROOT).equals("pdf")) { Map<String, Object> mps = pdf2Pic(imgDir + getNowDate + "/" + newName, imgDir + "/pdfFile", attechment.getId()); attechment.setPreviewAll(Integer.parseInt(mps.get("previewAll").toString())); attechment.setPngPath(mps.get("pngPath").toString()); attechment.setPreview(1); }else if(suffix.toLowerCase(Locale.ROOT).equals("xls") || suffix.toLowerCase(Locale.ROOT).equals("xlsx")){ String toFileName = imgDir + getNowDate + "/" + getNowDateNew + ".pdf"; WordToPdf d = new WordToPdf(); d.jacobExcelToPDF(imgDir + getNowDate + "/" + newName,toFileName); Map<String, Object> mps = pdf2Pic(toFileName, imgDir + "/pdfFile", attechment.getId()); attechment.setPreviewAll(Integer.parseInt(mps.get("previewAll").toString())); attechment.setPngPath(mps.get("pngPath").toString()); attechment.setPreview(1); } if (attechment.getPreview() != 1) { attechment.setPreview(0); } Map<String, Object> mp = new HashMap<>(); mp.put("previewAll", attechment.getPreviewAll()); mp.put("preview",attechment.getPreview()); mp.put("id", attechment.getId()); replayDao.updateFilePath(mp); map.put("id", attechment.getId()); map.put("filePath", attechment.getPngPath()); map.put("previewAll", attechment.getPreviewAll()); map.put("preview", attechment.getPreview()); }catch (IOException e){ e.printStackTrace(); } return map; } public Map<String,Object> pdf2Pic(String pdfPath, String path,Long id) throws Exception { String getNowDate = FileUtil.getNowDate("yyyyMMdd"); String getNowDateNew = FileUtil.getNowDate("yyyyMMddHHmmssSSS"); Document document = new Document(); document.setFile(pdfPath); //缩放比例 float scale = 2.5f; //旋转角度 float rotation = 0f; List<File> files = new ArrayList<>(); Map<String,Object> map=new HashMap<>(); int num = 0; if(document.getNumberOfPages()>30) { num = 30; map.put("previewAll",0); }else{ num=document.getNumberOfPages(); map.put("previewAll",1); map.put("preview",1); } String imgName=""; for (int i = 0; i < num; i++) { BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale); try { imgName = getNowDateNew + i + ".png"; File file1 = new File(path + "/" + imgName); files.add(file1); File file = new File(path + "/" + imgName); ImageIO.write(image, "png", file); } catch (IOException e) { e.printStackTrace(); } image.flush(); } String path1 = imgDir+getNowDate+"/"+getNowDateNew+".png"; String path2 = getNowDate+"/"+getNowDateNew+".png"; map.put("pngPath",path2); map.put("id",id); replayDao.updateFilePath(map); mergeVertical(files, path1); document.dispose(); Map<String,Object> mp=new HashMap<>(); mp.put("previewAll",Integer.parseInt(map.get("previewAll").toString())); mp.put("pngPath",path2); return mp; } //竖向合成 public static void mergeVertical(List<File> files, String path){ try { Integer allWidth = 0; //计算画布总宽 Integer allHeight = 0; //计算画布总高 List<BufferedImage> imgs = new ArrayList<>(); for(int i=0; i<files.size(); i++){ imgs.add(ImageIO.read(files.get(i))); //因为是竖向合成,拿图片里最大的一个宽度就行 allWidth = Math.max(allWidth,imgs.get(i).getWidth()); allHeight += imgs.get(i).getHeight(); } BufferedImage combined = new BufferedImage(allWidth, allHeight,BufferedImage.TYPE_INT_RGB); Graphics g = combined.getGraphics(); //设置画布背景颜色 ,默认黑色 g.setColor(Color.white); g.fillRect(0, 0, allWidth, allHeight); Integer height = 0; for(int i=0; i< imgs.size(); i++){ g.drawImage(imgs.get(i), 0, height,null); //+10为了设置上下两个图片间距 height += imgs.get(i).getHeight()+10; } ImageIO.write(combined, "jpg", new File(path)); System.out.println("===合成成功===="); } catch (Exception e) { System.out.println("===合成失败===="); e.printStackTrace(); } }
//返回新的文件名 private String saveImgFile(MultipartFile multipartFile, String imgDir,String getNowDate) throws IOException { String originFileName = multipartFile.getOriginalFilename(); String ext = originFileName.substring(originFileName.lastIndexOf(".")); //图片名称和编号一致唯一 //String newName = code+"_"+getNowDate+ext; String newName = System.currentTimeMillis()+String.valueOf(Math.random()).replaceAll("0\\.","")+ext; File dir = new File(imgDir); if (!dir.isDirectory() || !dir.exists()) { dir.mkdirs(); } //String getNowDate=FileUtil.getNowDate("yyyyMMdd"); File file = new File(imgDir+getNowDate+"/"); if (!file.exists()) { file.mkdir(); } File transFile = new File(imgDir+getNowDate+"/"+newName); multipartFile.transferTo(transFile); return newName; /* File file = new File(imgDir+newName); if (!file.exists()) { file.createNewFile(); } BufferedOutputStream bos = null; InputStream is = null; try { is = multipartFile.getInputStream(); bos = new BufferedOutputStream(new FileOutputStream(file)); int len = 0; byte[] buf = new byte[1024]; while ((len = is.read(buf))!=-1) { bos.write(buf,0,len); } bos.flush(); } finally { if (bos!=null) bos.close(); if (is!=null) is.close(); } return newName;*/ } //返回新的文件名 private String saveFile(MultipartFile multipartFile, String imgDir,String getNowDate) throws IOException { String ext = ".png"; //图片名称和编号一致唯一 String newName = System.currentTimeMillis()+String.valueOf(Math.random()).replaceAll("0\\.","")+ ext; File dir = new File(imgDir); if (!dir.isDirectory() || !dir.exists()) { dir.mkdirs(); } //String getNowDate=FileUtil.getNowDate("yyyyMMdd"); File file = new File(imgDir+getNowDate+"/"); if (!file.exists()) { file.mkdir(); } File transFile = new File(imgDir+getNowDate+"/"+newName); multipartFile.transferTo(transFile); return newName; }
------word转pdf工具类-------
https://www.jb51.net/article/236221.htm
public class WordToPdf { private static final int wdFormatPDF = 17; // PDF 格式 public void wordToPDF(String sfileName, String toFileName) { System.out.println("启动 Word..."); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch doc = null; try { app = new ActiveXComponent("Word.Application"); app.setProperty("Visible", new Variant(false)); Dispatch docs = app.getProperty("Documents").toDispatch(); doc = Dispatch.call(docs, "Open", sfileName).toDispatch(); File tofile = new File(toFileName); if (tofile.exists()) { tofile.delete(); } Dispatch.call(doc, "SaveAs", toFileName, // FileName wdFormatPDF); long end = System.currentTimeMillis(); System.out.println("转换完成..用时:" + (end - start) + "ms."); } catch (Exception e) { System.out.println("========Error:文档转换失败:" + e.getMessage()); } finally { Dispatch.call(doc, "Close", false); System.out.println("关闭文档"); if (app != null) app.invoke("Quit", new Variant[]{}); } // 如果没有这句话,winword.exe进程将不会关闭 ComThread.Release(); } /** * 使用jacob实现excel转PDF * * @param inputFilePath 导入Excel文件路径 * @param outputFilePath 导出PDF文件路径 */ @RequestMapping("/relic/fileExcel") public void jacobExcelToPDF(String inputFilePath, String outputFilePath) { ActiveXComponent ax = null; Dispatch excel = null; try { ComThread.InitSTA(); ax = new ActiveXComponent("Excel.Application"); ax.setProperty("Visible", new Variant(false)); // 禁用宏 ax.setProperty("AutomationSecurity", new Variant(3)); Dispatch excels = ax.getProperty("Workbooks").toDispatch(); Object[] obj = { inputFilePath, new Variant(false), new Variant(false) }; excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch(); // 转换格式 Object[] obj2 = { // PDF格式等于0 new Variant(0), outputFilePath, // 0=标准(生成的PDF图片不会模糊),1=最小的文件 new Variant(0) }; Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (excel != null) { Dispatch.call(excel, "Close", new Variant(false)); } if (ax != null) { ax.invoke("Quit", new Variant[]{}); ax = null; } ComThread.Release(); } } }