itext7 html转pdf


maven包导入

<!-- 获取html并替换内容 -->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.6.3</version>
</dependency>

<!-- html转PDF -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>kernel</artifactId>
    <version>7.1.1</version>
</dependency>

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>layout</artifactId>
    <version>7.1.1</version>
</dependency>

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>html2pdf</artifactId>
    <version>2.0.1</version>
</dependency>
String fileName = "PDF文件名";
//inline 设置为可在浏览器内打开,下载文件名称为fileName
response.setHeader("Content-Disposition", "inline;fileName=" + new String(fileName.getBytes(), "ISO8859-1") + ".pdf");
response.setContentType("application/pdf;charset=UTF-8");

//html文本地址
Sting url = "";
//根据html获取网络上的html对象
Document html = Jsoup.connect(url).get();
//替换html内容后将输出html文本
String htmlStr = html.html();

//导入字体
FontProvider font = new FontProvider();
font.addFont("/com/common/font/simsun.ttf");

ConverterProperties c = new ConverterProperties();
c.setFontProvider(font);
c.setCharset("utf-8");

PdfDocument pd = new PdfDocument(new PdfWriter(response.getOutputStream()));
//设置文件标题为fileName,web上展示的标题为此标题
pd.getDocumentInfo().setTitle(fileName);

Document document = new Document(pd, PageSize.A3);
try{
    //设置页面边距 必须先设置边距,再添加内容,否则页边距无效
    document.setMargins(20, 0, 20, 0);
    List<IElement> list = HtmlConverter.convertToElements(htmlStr, c);
    for (IElement ie : list) {
        document.add((IBlockElement) ie);
    }
}finally {
    document.close();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,001评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • Maven使用入门 1. Maven概述 Maven是什么?Maven项目对象模型(POM),可以通过一小段描述信...
    小小韩_小小红阅读 2,584评论 2 28
  • 简介 概述 Maven 是一个项目管理和整合工具 Maven 为开发者提供了一套完整的构建生命周期框架 Maven...
    闽越布衣阅读 4,363评论 6 39
  • 第一章:职业定位 状态有教练式、顾问式、指导式 心态是要支持式! 定位:自我探索,价值观、兴趣、内情、外情等 终极...
    吉小满满阅读 898评论 0 0