markdown文件转pdf

步骤:md转html转pdf
pom引入
java 复制代码
 <!--markdown 转pdf-->
        <dependency>
            <groupId>com.vladsch.flexmark</groupId>
            <artifactId>flexmark-all</artifactId>
            <version>0.64.8</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>5.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.9.2</version>
        </dependency>
java代码
java 复制代码
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.layout.font.FontInfo;
import com.itextpdf.layout.font.FontProvider;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataSet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Document.OutputSettings;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MarkdownToPdf {

    public static void main(String[] args) {
        String markdownFile = "D:\\markdown\\test.md";
        String pdfFile = "D:\\markdown\\test_" + System.currentTimeMillis() + ".pdf";
        toPdf(markdownFile, pdfFile);
    }

    private static void toPdf(String markdownFile, String pdfFile) {

        try {
            // 读取Markdown文件
            String markdown = new String(Files.readAllBytes(Paths.get(markdownFile)), StandardCharsets.UTF_8);

            // 转换Markdown为HTML
            MutableDataSet options = new MutableDataSet();
            Parser parser = Parser.builder(options).build();
            HtmlRenderer renderer = HtmlRenderer.builder(options).build();
            Node document = parser.parse(markdown);
            String html = renderer.render(document);

            // 使用JSoup解析HTML并转换为XHTML
            Document xhtmlDoc = Jsoup.parse(html);
            xhtmlDoc.outputSettings(new OutputSettings().syntax(OutputSettings.Syntax.xml));

            // 调整图片大小,不然图片高度显示不全
            xhtmlDoc.select("img").forEach(img -> {
                // 设置图片宽度和高度自适应
                img.attr("style", "max-width: 100%; height: auto;");
            });

            // 定义默认字体
            ConverterProperties converterProperties = new ConverterProperties();
            FontProvider fontProvider = new DefaultFontProvider(true, false, false);

            // 写法1
            // 宋体
            // URL url = new MarkdownToPdf().getClass().getClassLoader().getResource("font/SimSun.ttf");
            // 无衬线
            // URL url = new MarkdownToPdf().getClass().getClassLoader().getResource("font/NotoSansCJKsc-Regular.otf");
            // 有衬线
            // URL url = new MarkdownToPdf().getClass().getClassLoader().getResource("font/NotoSerifCJKsc-Regular.otf");
            // URL url = new MarkdownToPdf().getClass().getClassLoader().getResource("font/NotoSerifCJKsc-Light.otf");
            // fontProvider.addFont(url.getPath(), PdfEncodings.IDENTITY_H);

            // 写法2
            Resource resource = new ClassPathResource("font/SimSun.ttf");
            fontProvider.addFont(resource.getInputStream().readAllBytes(), PdfEncodings.IDENTITY_H);
            converterProperties.setFontProvider(fontProvider);
            File file = new File(pdfFile);
            FileOutputStream outputStream;
            try {
                outputStream = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            // Html 转化为 pdf
            HtmlConverter.convertToPdf(xhtmlDoc.html(), outputStream, converterProperties);
            System.out.println("PDF创建成功!");

        } catch (IOException e) {
            System.err.println("文件读取/写入错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

}
字体文件(见资源文件,可下载)

放在resources文件夹下即可

相关推荐
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
ew452182 小时前
ElementUI表格表头自定义添加checkbox,点击选中样式不生效
前端·javascript·elementui
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
Moon.92 小时前
el-table的hasChildren不生效?子级没数据还显示箭头号?树形数据无法展开和收缩
前端·vue.js·html
垚垚 Securify 前沿站2 小时前
深入了解 AppScan 工具的使用:筑牢 Web 应用安全防线
运维·前端·网络·安全·web安全·系统安全
工业甲酰苯胺5 小时前
Vue3 基础概念与环境搭建
前端·javascript·vue.js
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
柴柴的小记8 小时前
前端vue引入特殊字体不生效
前端·javascript·vue.js
柠檬豆腐脑9 小时前
从前端到全栈:新闻管理系统及多个应用端展示
前端·全栈
bin91539 小时前
DeepSeek 助力 Vue 开发:打造丝滑的颜色选择器(Color Picker)
前端·javascript·vue.js·ecmascript·deepseek