markdown文件转pdf

news/2024/7/18 22:40:54 标签: pdf, 前端
步骤:md转html转pdf
pom引入
 <!--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代码

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文件夹下即可


http://www.niftyadmin.cn/n/5544429.html

相关文章

快速上手:前后端分离开发(Vue+Element+Spring Boot+MyBatis+MySQL)

文章目录 前言项目简介环境准备第一步&#xff1a;初始化前端项目登录页面任务管理页面 第二步&#xff1a;初始化后端项目数据库配置数据库表结构实体类和Mapper服务层和控制器 第三步&#xff1a;连接前后端总结 &#x1f389;欢迎来到架构设计专栏~探索Java中的静态变量与实…

唯迈医疗随经贸团赴埃塞俄比亚探讨合作共促发展

近日&#xff0c;唯迈医疗参加了由北京市贸促会组织的赴埃塞俄比亚经贸代表团。埃塞俄比亚在非洲具有重要战略地位&#xff0c;也是非洲的门户&#xff0c;资源丰富、人口众多且年轻化程度高、经济增长速度快。经贸团一行在埃塞俄比亚拜会了中国驻埃塞俄比亚使馆&#xff0c;埃…

SpringBoot源码阅读(1)——环境搭建

SpringBoot官网 官网 https://spring.io/projects/spring-boot 代码仓库 github&#xff1a;https://github.com/spring-projects/spring-boot gitee: https://gitee.com/mirrors/spring-boot 下载代码 git clone https://gitee.com/mirrors/spring-boot.git下载的代码中有些…

手机数据恢复:如何在没有root的情况下恢复Android数据?

您是否不小心从Android设备中删除了重要数据&#xff1f;您是否担心如何取回您的照片、视频和文档&#xff1f;有时&#xff0c;我们不小心删除了重要数据&#xff0c;并使用Android root方法取回文件。许多用户不喜欢root他们的Android设备&#xff0c;因为这是一种复杂的方法…

【学习笔记】网络设备(华为交换机)基础知识2——常用设备管理命令

一、前期准备 提示&#xff1a;下面所有学习内容都是基于以下条件完成的 条件1.已经可以正常访问交换机的命令行接口 Console口本地访问教程参考 ① &#xff1a;使用第三方工具&#xff08;secureCRT软件&#xff09;通过console口本地访问访问交换机的详细操作过程 Telnet访…

高级RAG检索中的五种查询重写策略_用于检索增强的大型语言模型的查询重写

一、前言 检索增强生成 (RAG) 作为人工智能 (AI) 领域的一项重要技术&#xff0c;近年来得到了飞速发展。它将基于检索模型和基于生成的模型相结合&#xff0c;利用海量外部数据&#xff0c;生成更具信息量、更准确、更具语境相关性的回复。检索策略是 RAG 系统的关键组成部分…

传统IO和NIO文件拷贝过程

参考&#xff1a;https://blog.csdn.net/weixin_57323780/article/details/130250582

在AvaotaA1全志T527开发板上使用AvaotaOS 部署 Docker 服务

Docker 是一个开源的应用容器引擎&#xff0c;让开发者可以打包他们的应用以及依赖包到一个可移植的镜像中&#xff0c;然后发布到任何流行的 Linux或Windows操作系统的机器上&#xff0c;也可以实现虚拟化。容器是完全使用沙箱机制&#xff0c;相互之间不会有任何接口。 准备…