java使用itext7实现html转pdf

前言

最近项目里有个功能是要把前端展示的内容给导出pdf。经过一段时间的调研和尝试,最终选择了itext7来实现。网上有很多关于itext5的博客或者文档,但是关于itext7还挺少的。

首先介绍一下大体流程吧,项目是基于springboot 和vue 的前后端分离架构,基本思路是由前端生成html文件,传给后端,后端通过itext7转为pdf返回前端。废话少说,直接上代码!

一、前端处理html


可参考:https://segmentfault.com/a/1190000015820792,也可使用postman测试的时候传入下面的html

<!DOCTYPE html>
<html>
<head>
	<title>简单简历</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate"/>
	<meta http-equiv="pragma" content="no-cache"/>
	<meta http-equiv="expires" content="0"/>
	<!-- 自定义样式 -->
	<style>
		*{
			font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
		}

		body {
			margin: 0;
			padding: 0;
		}

		a {
			text-decoration: none;
			padding: 0;
			margin: 5px 0;
			color: black;
		}

		a:hover {
			color: #5c8dff;
		}

		b{
			margin: 0 10px;
		}

		/* 主体 */
		.main {
			/*margin: 0 auto;*/
			/*width: 770px;*/
			/*box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);*/
			/*border: 1px solid #dad8d8;*/
			/*background: #fbfbfb;*/
		}

		/* 1级标题 */
		h3.list1 {
			color: #409EFF;
			border-bottom: 1px solid #409EFF;
			padding: 5px;
			margin: 50px 0 0 0;
		}

		/* 大模块 */
		.block,.block1 {
			/*background: #efefef;*/
			/*border: 1px solid #dad8d8;*/
			margin: 0 0 20px 0;
			padding: 0 10px;
		}
		.block,.block1 p {
			text-indent:2em;
		}

		.block:hover {
			background: #eeeeee;
		}
		.block1:hover {
			background: #cecece;
		}

		.button-list{
			text-align: center;
			margin: 20px auto;
			padding: 10px;
			width: 1024px;
		}
	</style>
</head>
<body>
<!-- 简历主体 -->
<div id="body" class="main">
	<div class="section">
		<div class="module">
			<h3 class="list1" style="margin: 0;">基本信息</h3>
			<div class="block">
				<p>XXX<b>/</b>男<b>/</b>25岁</p>
				<p>本科<b>/</b>XX学校<b>/</b>XX专业<b>/</b>2014-2018</p>
				<p>工龄:X年</p>
				<p>手机:XXXXXXXXXX</p>
				<p>邮箱:XXXXX@qq.com</p>
				<p>GitHub:<a href="https://github.com/huanzi-qch">https://github.com/huanzi-qch</a></p>
				<p>博客园:<a href="https://www.cnblogs.com/huanzi-qch">https://www.cnblogs.com/huanzi-qch</a></p>
				<br/>
				<p>求职岗位:Java开发<b>/</b>目标城市:南宁市<b>/</b>期望薪资:面议</p>
				<p>注:已离职,一个月可到岗</p>

				<img style="position: relative;top: -350px;left: 500px;width: 100px;height: 130px;" src="1@2x.png"/>
			</div>
		</div>

		<div class="module">
			<h3 class="list1">技能清单</h3>
			<div class="block">
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
				<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
			</div>
		</div>

		<div class="module">
			<h3 class="list1">工作经历</h3>
			<div class="block">
				<p>XXX技术有限公司<b>/</b>Java开发工程师<b>/</b>2018.01 - 至今</p>
				<p>参与多个项目开发、测试、部署等工作,包括:</p>
				<p>1、XXX。</p>
				<p>2、XXX。</p>
				<p>3、XXX。</p>
			</div>
		</div>

		<div class="module">
			<h3 class="list1">项目经历</h3>
			<div class="block">
				<h4 class="list2">项目1</h4>
				<div class="block1">
					<p>项目名称:XXX(2020-11 —2021-11)</p>
					<p>项目介绍:XXXXXXXXXXXXXXX。</p>
					<p>技术架构:XXX + XXX + XXX。</p>
					<p>职责描述:</p>
					<p>1、XXXX。</p>
					<p>2、XXXX。</p>
					<p>3、XXXX。</p>
					<p>4、XXXX。</p>
				</div>

				<h4 class="list2">项目2</h4>
				<div class="block1">
					<p>项目名称:XXX(2020-11 —2021-11)</p>
					<p>项目介绍:XXXXXXXXXXXXXXX。</p>
					<p>技术架构:SpringBoot + Vue + Element-UI + ECharts。</p>
					<p>职责描述:</p>
					<p>1、XXXX。</p>
					<p>2、XXXX。</p>
					<p>3、XXXX。</p>
					<p>4、XXXX。</p>
				</div>
			</div>
		</div>

		<div class="module">
			<h3 class="list1">自我评价</h3>
			<div class="block">
				<p>1、XXXX;</p>
				<p>2、XXXX;</p>
				<p>3、XXXX;</p>
			</div>
		</div>
	</div>
</div>
</body>
</html>

二、后端引入依赖

<!-- itext7html转pdf  -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>html2pdf</artifactId>
    <version>3.0.2</version>
</dependency>
<!-- 中文字体支持 -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>font-asian</artifactId>
    <version>7.1.13</version>
</dependency>

注意两个依赖的版本对应,进入html2pdf的pom文件就能看到itext的版本,font-asian的版本最低也要是html2pdf中itext7的版本。

三 、水印和页码

水印代码:

import com.itextpdf.kernel.colors.WebColors;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;

import java.io.IOException;

/**
 * 处理水印
 */
public class WaterMarkEventHandler implements IEventHandler {
 
    /**
     * 水印内容
     */
    private String waterMarkContent;
 
    /**
     * 一页中有几列水印
     */
    private int waterMarkX;
 
    /**
     * 一页中每列有多少水印
     */
    private int waterMarkY;
 
    public WaterMarkEventHandler(String waterMarkContent) {
        this(waterMarkContent, 5, 5);
    }
 
    public WaterMarkEventHandler(String waterMarkContent, int waterMarkX, int waterMarkY) {
        this.waterMarkContent = waterMarkContent;
        this.waterMarkX = waterMarkX;
        this.waterMarkY = waterMarkY;
    }
 
    @Override
    public void handleEvent(Event event) {
 
        PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
        PdfDocument document = documentEvent.getDocument();
        PdfPage page = documentEvent.getPage();
        Rectangle pageSize = page.getPageSize();
 
        PdfFont pdfFont = null;
        try {
            pdfFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), document);
 
        Paragraph waterMark = new Paragraph(waterMarkContent).setOpacity(0.5f);
        Canvas canvas = new Canvas(pdfCanvas, pageSize)
                .setFontColor(WebColors.getRGBColor("lightgray"))
                .setFontSize(16)
                .setFont(pdfFont);
 
        for (int i = 0; i < waterMarkX; i++) {
            for (int j = 0; j < waterMarkY; j++) {
                canvas.showTextAligned(waterMark, (150 + i * 300), (160 + j * 150), document.getNumberOfPages(), TextAlignment.CENTER, VerticalAlignment.BOTTOM, 120);
            }
        }
        canvas.close();
    }
}

页码代码:

import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;

import java.io.IOException;

/**
 * 处理页码
 */
public class PageEventHandler implements IEventHandler {
 
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
        PdfDocument document = documentEvent.getDocument();
        PdfPage page = documentEvent.getPage();
        Rectangle pageSize = page.getPageSize();
 
        PdfFont pdfFont = null;
        try {
            pdfFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), document);
        Canvas canvas = new Canvas(pdfCanvas, pageSize);
        float  x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        float  y = pageSize.getBottom() + 15;
        Paragraph paragraph = new Paragraph("第" + document.getPageNumber(page) + "页/共" + document.getNumberOfPages() + "页")
                .setFontSize(10)
                .setFont(pdfFont);
        canvas.showTextAligned(paragraph, x, y, TextAlignment.CENTER);
        canvas.close();
    }
}

四、添加转换工具类

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class HtmlToPdfUtils {
 
    /**
     * html转pdf
     * @param  inputStream 输入流
     * @param  waterMark 水印
     * @param fontPath 字体路径,ttc后缀的字体需要添加<b>,0<b/>
     * @param  outputStream 输出流
     */
    public static void convertToPdf(InputStream inputStream, String waterMark, String fontPath, OutputStream outputStream) throws IOException {
 
        PdfWriter pdfWriter = new PdfWriter(outputStream);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        //设置为A4大小
        pdfDocument.setDefaultPageSize(PageSize.A4);
        //添加水印
        pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new WaterMarkEventHandler(waterMark));

        //添加页码
        //pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE,new PageEventHandler());
        //添加中文字体支持
        ConverterProperties properties = new ConverterProperties();
        FontProvider fontProvider = new FontProvider();
 
        PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
 
        //添加自定义字体,例如微软雅黑
        /*if (StringUtils.isNotBlank(fontPath)){
            PdfFont microsoft = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, false);
            fontProvider.addFont(microsoft.getFontProgram(), PdfEncodings.IDENTITY_H);
        }*/
 
        properties.setFontProvider(fontProvider);
        HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);
 
        pdfWriter.close();
        pdfDocument.close();
    }
 
}

五、Java 调用工具类

service

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.OutputStream;

@Service
public class ExportPdfService {
 
    public void exportPdf(MultipartFile file, OutputStream outputStream) throws Exception {
        String waterMarkText =  "自定义水印";
        InputStream inputStream = file.getInputStream();
        //微软雅黑在windows系统里的位置如下,linux系统直接拷贝该文件放在linux目录下即可
        HtmlToPdfUtils.convertToPdf(inputStream, waterMarkText, "", outputStream);
 
    }
 
}

controller

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 使用itext7html转pdf
 */

@Slf4j
@RestController
public class ExportPdfController {
 
    @Resource
    private ExportPdfService exportPdfService;

    /**
     * @param file html文件
     * @param response
     * @param request
     * @throws Exception
     */
    @PostMapping("/export")
    public void exportVehicleArchives(MultipartFile file, HttpServletResponse response,HttpServletRequest request) throws Exception {
        try{
            String fileNamePrefix = "文件名称";
            String date = format(new Date(), "yy-mm-dd HH:mm");
            String fileName = fileNamePrefix + "_" + date +".pdf";
            this.resolveResponse(request,response, fileName);
            this.exportPdfService.exportPdf(file, response.getOutputStream());
        } catch (Exception e) {
            this.resetResponse(response, e);
        }
    }
 
    private void resolveResponse(HttpServletRequest request,HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setContentType("application/pdf");
        response.setCharacterEncoding("utf-8");
        setFileDownloadHeader(request,response,fileName);
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    }

    /**
     * 防止浏览器下载文件名中文乱码
     * @param request
     * @param response
     * @param fileName
     */
    public void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        String userAgent = request.getHeader("USER-AGENT");
        try {
            String finalFileName = null;
            if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent, "Trident") || StringUtils.contains(userAgent,"Edge")){//IE 浏览器
                finalFileName = URLEncoder.encode(fileName,"UTF8");
            }else{
                finalFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//\" 解决Firefox下载英文+中文组合的文件名的问题
        } catch (UnsupportedEncodingException e) {
        }
    }
 
    private void resetResponse(HttpServletResponse response, Exception exception)throws IOException {
        // 重置response
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String result = "下载文件失败," + exception.getMessage();
        response.getWriter().println(result);
    }

    /**
     * 格式化日期
     * @param date
     * @param pattern
     * @return
     */
    public String format(Date date,String pattern){
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }
 
}

注意

itext7明显比itext5好用很多,如果导出的pdf样式有问题,让前端修改一下html的样式就可以了,比如去除padding-left,去除label的对齐,图片小一点等等。我们前端一点一点的修改才最终导出了符合产品的pdf。

博主写的很好,转发收藏

参考文档:

java使用itext7实现html转pdf_红藕香残玉簟秋的博客-CSDN博客_html转pdf itext

下面一篇itext5 实践文档也不错:SpringBoot导出pdf文件学习_遨游在知识的海洋无法自拔的博客-CSDN博客_springboot导出pdf

下面是一个使用iText7HTML换为PDF并添加页数和水印的简单示例: ```java import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.kernel.colors.ColorConstants; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.kernel.pdf.xobject.PdfFormXObject; import java.io.File; import java.io.IOException; public class HtmlToPdfConverter { public static void main(String[] args) throws IOException { String html = "<html><body><h1>Hello, World!</h1></body></html>"; String pdfPath = "output.pdf"; PdfWriter writer = new PdfWriter(pdfPath); PdfDocument pdfDoc = new PdfDocument(writer); pdfDoc.setDefaultPageSize(new Rectangle(PageSize.A4.getLeft(), PageSize.A4.getBottom(), PageSize.A4.getRight(), PageSize.A4.getTop())); PdfFont font = PdfFontFactory.createFont("path/to/font.ttf", PdfEncodings.IDENTITY_H, true); PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage()); canvas.beginText() .setFontAndSize(font, 12) .moveText(pdfDoc.getDefaultPageSize().getRight() - 72, 36) .showText("Page 1") .endText(); ConverterProperties props = new ConverterProperties(); HtmlConverter.convertToPdf(html, pdfDoc, props); int n = pdfDoc.getNumberOfPages(); for (int i = 2; i <= n; i++) { PdfPage page = pdfDoc.getPage(i); canvas = new PdfCanvas(page); canvas.beginText() .setFontAndSize(font, 12) .moveText(pdfDoc.getDefaultPageSize().getRight() - 72, 36) .showText(String.format("Page %d", i)) .endText(); } PdfFormXObject watermark = new PdfFormXObject(new Rectangle(0, 0, 100, 100)); canvas = new PdfCanvas(watermark, pdfDoc); canvas.setFillColor(ColorConstants.LIGHT_GRAY); canvas.setStrokeColor(ColorConstants.LIGHT_GRAY); canvas.rectangle(0, 0, 100, 100); canvas.fill(); canvas.beginText() .setFontAndSize(font, 24) .moveText(20, 50) .showText("Confidential") .endText(); for (int i = 1; i <= n; i++) { PdfPage page = pdfDoc.getPage(i); canvas = new PdfCanvas(page); canvas.addXObject(watermark, 0, 0); } pdfDoc.close(); } } ``` 在上面的示例中,我们首先创建一个PdfWriter和PdfDocument对象,然后设置默认页面大小为A4纸张大小。接下来,我们添加第一页,并在页面右下角添加“Page 1”文本。然后使用iText7HtmlConverter将HTML字符串换为PDF文档。使用循环遍历文档中的每个页面,并在每个页面的右下角添加页码。最后,我们创建一个PdfFormXObject对象,添加水印文本“Confidential”,并将其添加到每个页面中。 请注意,上面的示例中的代码片段是未经测试的,仅供参考。您需要根据您自己的需求进行修改和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值