引入jar包

方式一

1、在pom.xml配置aspose的jar包仓库

<repositories>
    <repository>
        <id>AsposeJavaAPI</id>
        <name>Aspose Java API</name>
        <url>https://repository.aspose.com/repo/</url>
    </repository>
</repositories>

2、然后分别加对应的依赖并刷新pom文件进行下载

        <dependency><!--word-->
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>21.11</version>
        <classifier>jdk17</classifier>
        </dependency>
        <dependency><!--pdf-->
            <groupId>com.aspose</groupId>
            <artifactId>aspose-pdf</artifactId>
            <version>21.8</version>
        </dependency>
        <dependency><!--excel-->
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>21.8</version>
        </dependency>
        <dependency><!--pptx-->
            <groupId>com.aspose</groupId>
            <artifactId>aspose-slides</artifactId>
            <version>21.8</version>
            <classifier>jdk16</classifier>
        </dependency>
        <dependency><!--jar破解工具-->
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>

方式二

1、使用加载本地lib目录下jar的方式导入

        <dependency><!--word-->
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>23.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-23.1-jdk17.jar</systemPath>
        </dependency>
        <dependency><!--pdf-->
            <groupId>com.aspose</groupId>
            <artifactId>aspose-pdf</artifactId>
            <version>23.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-pdf-23.1.jar</systemPath>
        </dependency>
        <dependency><!--excel-->
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>23.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-23.1.jar</systemPath>
        </dependency>
        <dependency><!--pptx-->
            <groupId>com.aspose</groupId>
            <artifactId>aspose-slides</artifactId>
            <version>23.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-slides-23.1-jdk16.jar</systemPath>
        </dependency>

2、在引入的springboot的maven插件中告诉maven,将我们的刚刚引入的作用域为system的本地jar也打包进来

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <includeSystemScope>true</includeSystemScope>
                </configuration>
            </plugin>

3、解决tomcat外部lib加载问题

<!--            解决tomcat外部lib加载问题-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>src/main/resources/lib</directory>
                            <targetPath>WEB-INF/lib/</targetPath>
                            <includes>
                                <include>**/*.jar</include>
                            </includes>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>

jar包下载地址:http://pan.darktool.cn/s/zeu6 密码:ihz8lx
参考:https://www.jianshu.com/p/5a90d17852ce

工具类

office转换工具类

import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import com.aspose.words.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * office转换工具类
 */
public class AsposeUtil {

    private static final Logger log = LoggerFactory.getLogger(AsposeUtil.class);

    //校验license
    private static boolean judgeLicense(String type) {
        boolean result = false;
        try {
            InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            if ("word".equals(type) || "txt".equals(type)) {
                com.aspose.words.License aposeLic = new com.aspose.words.License();
                aposeLic.setLicense(is);
                result = true;
            } else if ("excel".equals(type)) {
                com.aspose.cells.License aposeLic = new com.aspose.cells.License();
                aposeLic.setLicense(is);
                result = true;
            } else if ("ppt".equals(type)) {
                com.aspose.slides.License aposeLic = new com.aspose.slides.License();
                aposeLic.setLicense(is);
                result = true;
            } else if ("pdf".equals(type)) {
                com.aspose.pdf.License aposeLic = new com.aspose.pdf.License();
                aposeLic.setLicense(is);
                result = true;
            }
        } catch (Exception e) {
            log.error("office转换时出错:{}", e);
        }
        return result;
    }

    // 转换
    public static boolean trans(String filePath, String pdfPath, String type) {
        if (!judgeLicense(type)) {
            log.error("license错误");
        }
        try {
            log.debug("aspose开始:" + filePath);
            long old = System.currentTimeMillis();
            File file = new File(pdfPath);
            toPdf(file, filePath, type);
            long now = System.currentTimeMillis();
            log.debug("完成:" + pdfPath);
            log.debug("共耗时:" + ((now - old) / 1000.0) + "秒");
            return true;
        } catch (Exception e) {
            log.error("office转换时出错:{}", e);
        }
        return false;
    }

    private static void toPdf(File file, String filePath, String type) {
        if ("word".equals(type) || "txt".equals(type)) {
            wordofpdf(file, filePath);
        } else if ("excel".equals(type)) {
            exceOfPdf(file, filePath);
        } else if ("ppt".equals(type)) {
            pptofpdf(file, filePath);
        } else {
            log.error("暂不支持该类型:"+type);
        }
    }

    private static void wordofpdf(File file, String filePath) {
        FileOutputStream os = null;
        Document doc;
        try {
            os = new FileOutputStream(file);
            doc = new Document(filePath);
            doc.save(os, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf时出错:{}", e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                log.error("office转换时关闭文件出错:{}", e);
            }
        }
    }

    private static void exceOfPdf(File file, String filePath) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            Workbook wb = new Workbook(filePath);
            wb.save(os, com.aspose.cells.SaveFormat.PDF);
        } catch (Exception e) {
            log.error("exce转pdf时出错:{}", e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                log.error("office转换时关闭文件出错:{}", e);
            }
        }
    }

    private static void pptofpdf(File file, String filePath) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            Presentation pres = new Presentation(filePath);// 输入pdf路径
            pres.save(os, SaveFormat.Pdf);
        } catch (Exception e) {
            log.error("ppt转pdf时出错:{}", e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                log.error("office转换时关闭文件出错:{}", e);
            }
        }

    }
}

Excel转pdf时自动设置打印宽度

private static void exceOfPdf(File file, String filePath) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            Workbook wb = new Workbook(filePath);

            for (int i = 0;i < wb.getWorksheets().getCount();i++) {
                Worksheet worksheet = wb.getWorksheets().get(i);
                PageSetup pageSetup = worksheet.getPageSetup();
                int maxRow = autoMaxRow(worksheet, worksheet.getCells().getMaxColumn());
                int maxColumn = autoMaxColumn(worksheet, maxRow);
                pageSetup.setPrintArea("A1:" + CellsHelper.columnIndexToName(maxColumn) + CellsHelper.rowIndexToName(maxRow));

                pageSetup.setPrintGridlines(false);
                // 设置打印纸张为A4
                pageSetup.setPaperSize(PaperSizeType.PAPER_A_4);
                // 设置每页打印的列数
//                pageSetup.setFitToPagesWide(maxColumn + 1);

                int countColumnWidth = 0;
                for (int j = 0; j < maxColumn + 1; j++) {
                    double columnWidth = worksheet.getCells().getColumnWidthInch(j); // 英寸为单位
                    countColumnWidth = countColumnWidth + (int) Math.ceil(columnWidth * 25.4);// 转换成毫米,且向上取整,用于减少误差产生的影响(列数越多右边会空出越多距离)
                }
//                countColumnWidth = countColumnWidth * 2.54; // 转换成厘米
                if (countColumnWidth > 0) {
                    int leftMargin = (int) Math.ceil(pageSetup.getLeftMargin()) * 10; // 获取左边距(厘米为单位) 向上取整,且转换为毫米
                    int rightMargin = (int) Math.ceil(pageSetup.getRightMargin()) * 10; // 获取右边距(厘米为单位) 向上取整,且转换为毫米
                    double temp = (maxColumn + 1) * 1.5; // 根据列数动态减去相关长度用于兼容误差,单位毫米
                    if (temp < 15) {
                        temp = 15; // 设置用于兼容误差的最小值;
                    }
                    double body = 210 - (leftMargin + rightMargin) - temp;

                    pageSetup.setZoom((int) Math.floor(body * 100 / countColumnWidth));
                }
                wb.calculateFormula();
            }

            wb.save(os, com.aspose.cells.SaveFormat.PDF);
        } catch (Exception e) {
            log.error("exce转pdf时出错:{}", e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                log.error("office转换时关闭文件出错:{}", e);
            }
        }
    }

    // 遍历找到最终的列
    private static int autoMaxColumn(Worksheet worksheet, int maxRow) {
        int min = worksheet.getCells().getMaxDataColumn();
        int max = worksheet.getCells().getMaxColumn();
        for (int i = max;i > min;i--) {
            for(int j = 0;j <= maxRow;j++) {
                Cell cell = worksheet.getCells().get(j, i);
                // 获取单元格所在的合并单元格数据
                Range mergedRange = cell.getMergedRange();
                if (mergedRange != null) {
                    return i;
                }
            }
        }
        return min;
    }

    // 遍历找到最终的行
    private static int autoMaxRow(Worksheet worksheet, int maxColumn) {
        int min = worksheet.getCells().getMaxDataRow();
        int max = worksheet.getCells().getMaxRow();
        for (int i = max;i > min;i--) {
            for(int j = 0;j <= maxColumn;j++) {
                Cell cell = worksheet.getCells().get(i, j);
                // 获取单元格所在的合并单元格数据
                Range mergedRange = cell.getMergedRange();
                if (mergedRange != null) {
                    return i;
                }
            }
        }
        return min;
    }

license.xml

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

解决Linux中文乱码问题(安装中文字体)

  1. 首先你要有字体文件,ttf或者ttc格式的均可以我们可以从windows的 C:\WINDOWS\Fonts 这个目录下的字体文件复制出来,例如我们得到的字体文件是 segoui.ttf
  2. 将这个字体文件上传到随便一个Linux目录下。例如我们复制到/usr/share/fonts/win这个目录下。
  3. 切换到我们上一步复制的字体所在的目录(/usr/share/fonts/win)创建字体索引
sudo mkfontscale

该命令执行完之后可以发现在当前目录下生成了一个名为 fonts.scale 的文本文件

  1. 在目录中创建字体文件的索引
sudo mkfontdir

该命令执行完之后会在当前目录下生成名为 fonts.dir 的文本文件

  1. 构建字体信息缓存文件
sudo fc-cache
  1. 使用fc-list进行字体确认。这个命令会输入现在安装的所有字体。当我们看到我们上传的中文字体,再去执行aspose的代码就不会出现乱码了
最后修改:2024 年 09 月 19 日
如果觉得我的文章对你有用,请随意赞赏