O
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.7 KiB

  1. package com.xujie.sys.common.utils;
  2. import com.aspose.cells.PageOrientationType;
  3. import com.aspose.cells.PageSetup;
  4. import com.aspose.cells.PaperSizeType;
  5. import com.aspose.cells.SaveFormat;
  6. import com.aspose.cells.Workbook;
  7. import com.aspose.cells.Worksheet;
  8. import com.aspose.words.Document;
  9. import java.io.File;
  10. /**
  11. * Office文件转PDF工具类使用Aspose
  12. */
  13. public class OfficeConverter {
  14. public static String getFileExtension(File file) {
  15. String fileName = file.getName();
  16. int lastDot = fileName.lastIndexOf('.');
  17. return (lastDot == -1) ? "" : fileName.substring(lastDot + 1);
  18. }
  19. public static void convertExcelToPdf(File file) throws Exception {
  20. Workbook workbook;
  21. String filePath = file.getAbsolutePath();
  22. if (filePath.endsWith(".xlsx")) {
  23. workbook = new Workbook(file.getAbsolutePath());
  24. } else {
  25. workbook = new Workbook(filePath);
  26. }
  27. Worksheet worksheet = workbook.getWorksheets().get(0);
  28. PageSetup pageSetup = worksheet.getPageSetup();
  29. pageSetup.setOrientation(PageOrientationType.PORTRAIT);
  30. pageSetup.setPaperSize(PaperSizeType.PAPER_A_4);
  31. pageSetup.setZoom(50);
  32. pageSetup.setLeftMargin(0);
  33. pageSetup.setRightMargin(0);
  34. pageSetup.setTopMargin(0.5);
  35. pageSetup.setBottomMargin(0.5);
  36. String pdfPath = filePath.replaceAll("\\.xlsx|\\.xls", ".pdf");
  37. workbook.save(pdfPath, SaveFormat.PDF);
  38. }
  39. public static void convertWordToPdf(File file) throws Exception {
  40. Document document = new Document(file.getAbsolutePath());
  41. String pdfPath = file.getAbsolutePath().replace(".docx", ".pdf").replace(".doc", ".pdf");
  42. document.save(pdfPath);
  43. }
  44. }