? ? 之前项目有个需求,系统实现自己的打印功能,基本上都是前端找了个框架搞的,我呢,就是配合处理一些前端不好处理的部分,但是新一期的需求评审中,前端提出了,前端自己生成pdf在数据量大的时候会很慢,自然这时候需要我这个后端介入了。虽然期间遇到过不少问题,但最后都解决了,至少解决的这一期的需求任务,后续可能在此基础上还会扩展,到时候再一一补充到这篇博客中。
? ? 首先,一开始也找了很多工具,都不是很合适,原因就不说了,最终敲定使用itext来实现html转pdf。
? ?html是前端自己生成,要注意的就是语法要合规(其中可能还有些标签属性不支持,但是这个得前端自己摸索改造,不在此处展开说明),不然很容易出现生成的pdf和html渲染的效果不一致的问题。
? 项目通过maven引入依赖
<!-- 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>
下面是具体相关代码
1水印部分
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;
/**
* @ClassName WaterMarkEventHandler
* @Description 水印
* @Author nw
* @Date 2024/1/12 9:35
* @Version 1.0
*/
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();
}
}
2.页码
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;
/**
* @ClassName PageEventHandler
* @Description 页数
* @Author nw
* @Date 2024/1/12 9:38
* @Version 1.0
*/
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();
}
}
3.工具类
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.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;
/**
* @ClassName HtmlToPdfUtils
* @Description
* @Author nw
* @Date 2024/1/12 9:40
* @Version 1.0
*/
public class HtmlToPdfUtils
{
public static void html2Pdf(InputStream inputStream, String waterMark, OutputStream outputStream) throws
IOException
{
PdfWriter pdfWriter = new PdfWriter(outputStream);
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
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");
properties.setFontProvider(fontProvider);
HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);
pdfWriter.close();
pdfDocument.close();
}
}
4.由于电脑端和手机端的要求不一样,所以写了两个接口,电脑端直接响应了文件流,手机端直接返回oss的一个地址,但是底层的逻辑是一致的,只是后续处理稍微不一样而已,下面两个接口代码示例,供大家参考。
4.1电脑端
控制层
/**
* web端用
* @param file
* @param param
* @param response
* @throws Exception
*/
@PostMapping("/exportPdfWeb")
public void exportPdfWeb(@RequestParam("file") MultipartFile file, @RequestParam("param") String param,HttpServletResponse response) throws Exception {
JSONObject params = null;
if(StringUtil.isEmpty(param)){
params = new JSONObject();
}else{
params = JSON.parseObject(param);
}
String fileNamePrefix = params.getString("fileNamePrefix");
try{
String fileName = fileNamePrefix + "_" + DateUtil.getTimestamp("yyyyMMddHHmmss") + StringUtil.getUUID2Long() +".pdf";
this.resolveResponse(response, fileName);
customPrintModelService.exportPdfWeb(file, response.getOutputStream(),params);
} catch (Exception e) {
log.error("exportPdfWeb生成pdf出错:",e);
this.resetResponse(response, e);
}
}
/**
* 客户端用
* @param file
* @param param
* @return
* @throws Exception
*/
@PostMapping("/exportPdfClient")
@ResponseBody
public ApiResponse exportPdfClient(@RequestParam("file") MultipartFile file, @RequestParam("param") String param){
JSONObject params = null;
if(StringUtil.isEmpty(param)){
params = new JSONObject();
}else{
params = JSON.parseObject(param);
}
if(!params.containsKey("fileNamePrefix") || StringUtil.isEmpty(params.getString("fileNamePrefix"))){
return ApiResponse.failed(ApiResponse.CODE_FAIL_DEFAULT,"模板名称不能为空");
}
try{
return customPrintModelService.exportPdfClient(file,params);
} catch (Exception e) {
log.error("exportPdfClient生成pdf出错:",e);
return ApiResponse.failed(ApiResponse.CODE_FAIL_DEFAULT,"获取pdf路径失败");
}
}
private void resolveResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException
{
response.setContentType("application/pdf");
response.setCharacterEncoding("utf-8");
String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + encodeFileName);
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
}
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);
}
service层
?
@Override
public void exportPdfWeb(MultipartFile file, OutputStream outputStream,JSONObject params) throws IOException
{
//水印
String waterMarkText = "";
if(params.containsKey("waterMarkText")){
waterMarkText = params.getString("waterMarkText");
}
InputStream inputStream = file.getInputStream();
HtmlToPdfUtils.html2Pdf(inputStream, waterMarkText, outputStream);
}
@Override
public ApiResponse exportPdfClient(MultipartFile file, JSONObject param) throws IOException
{
String fileNamePrefix = param.getString("fileNamePrefix");
String fileName = fileNamePrefix + "_" + DateUtil.getTimestamp("yyyyMMddHHmmss") + StringUtil.getUUID2Long() +".pdf";
String fullPath = PropertiesUtil.getInstance("system.properties").getValue("upload.root_path") + File.separator + fileName;
//水印
String waterMarkText = "";
if(param.containsKey("waterMarkText")){
waterMarkText = param.getString("waterMarkText");
}
InputStream inputStream = file.getInputStream();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(fullPath);
HtmlToPdfUtils.html2Pdf(inputStream, waterMarkText, fileOutputStream);
} catch (IOException e) {
log.error("exportPdfClient生成pdf文件失败:",e);
return ApiResponse.failed(ApiResponse.CODE_FAIL_DEFAULT,"生成pdf失败");
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
log.error("exportPdfClient关闭文件流失败:",e);
}
}
File localFile = new File(fullPath);
String nowDate = DateUtil.DateTimeToString("yyyyMM", new Date());
String fileKey = UserManager.getTenantId() + "/" + nowDate + "/print/" + fileName;
boolean uploadFlag = FileStorgeHelper.syncUploadFileToOss(OssUsageEnum.USAGE_PRINT, localFile, fileKey, null);
if (!uploadFlag) {
log.info("上传文件到阿里云未成功");
return ApiResponse.failed(ApiResponse.CODE_FAIL_DEFAULT,"上传文件到阿里云出错");
}
//上传成功 获取路径
String fileUrl = FileStorgeHelper
.generatePresignedUrl(OssUsageEnum.USAGE_PRINT, fileKey, 480, TimeUnit.MINUTES);
return ApiResponse.success(fileUrl);
}
另外接口调用图
电脑端:
手机端
最后说一下,目前产品的需求并未对纸张尺寸有要求,比如A3,A4,B2,itext中默认使用的是A4,具体怎么设置,等有需求再说吧,今天周六加班不想写了,准备下班。希望帮助到大家。