Word转PDF

681 阅读1分钟

pom.xml依赖

<!--word转pdf-->
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>19.5jdk</version>
</dependency>

工具类

import com.aspose.words.*;

/**
 * Created on 2021/12/3
 *
 * <pre>
 *      word转PDF
 * </pre>
 *
 * @author cuicc@ebikj.com
 * @version reversion 1.0
 */

public class WordUtil {
    /**
     * 将WORD转换为PDF
     */
    public static void wordToPdf(String wordPath, String pdfPath) throws Exception {
        // 采用aspose.words包,原版带水印,当前使用的是去水印版
        Document doc = new Document(wordPath);
        // 直接转换,发现每个段落后间距会增加10pt,手动去除
        // 一般段落
        SectionCollection sc = doc.getSections();
        for (int i = 0; i < sc.getCount(); i++) {
            Section s = sc.get(i);
            ParagraphCollection pc = s.getBody().getParagraphs();
            if (pc.getCount() > 0) {
                for (int j = 0; j < pc.getCount(); j++) {
                    Paragraph p = pc.get(j);
                    // 设置段后间距为0
                    p.getParagraphFormat().setSpaceAfter(0);
                }
            }
        }

        //这一步很重要需要指定字体文件目录
        FontSettings fontSettings = new FontSettings();
        fontSettings.setFontsFolder("D:\Fonts", false);
        doc.setFontSettings(fontSettings);

        //表格中的段落
        NodeCollection<Table> tables = doc.getChildNodes(NodeType.TABLE, true);
        for (Table table : tables) {
            RowCollection rc = table.getRows();
            for (int i = 0; i < rc.getCount(); i++) {
                Row row = rc.get(i);
                CellCollection cc = row.getCells();
                for (int j = 0; j < cc.getCount(); j++) {
                    Cell cell = cc.get(j);
                    ParagraphCollection pc = cell.getParagraphs();
                    if (pc.getCount() > 0) {
                        for (int k = 0; k < pc.getCount(); k++) {
                            Paragraph p = pc.get(k);
                            // 设置段后间距为0
                            p.getParagraphFormat().setSpaceAfter(0);
                        }
                    }
                }
            }
        }
        // 执行转换
        doc.save(pdfPath, SaveFormat.PDF);
    }

字体文件

链接:pan.baidu.com/s/1NEhz6OU3… 提取码:2lfb