1. 程式人生 > 其它 >java使用itext7實現html轉pdf

java使用itext7實現html轉pdf

技術標籤:springbootjavaspringbootitext7htmlpdf

前言

最近專案裡有個功能是要把前端展示的內容給匯出pdf。經過一段時間的調研和嘗試,最終選擇了itext7來實現。網上有很多關於itext5的部落格或者文件,但是關於itext7還挺少的。

首先介紹一下大體流程吧,專案是基於springboot 和vue 的前後端分離架構,基本思路是由前端生成html檔案,傳給後端,後端通過itext7轉為pdf返回前端。廢話少說,直接上程式碼!

一、前端處理html

由於不是我寫的程式碼,這裡只能給出參考:https://segmentfault.com/a/1190000015820792

,我們的前端是基於這個方案改造的,很有參考價值。

二、後端引入依賴

<!-- 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的版本。

三、水印和頁碼

匯出pdf一般是需要水印和頁碼的,我們只要實現com.itextpdf.kernel.events.IEventHandler介面就可以了

水印

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();
    }
}

頁碼

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.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 {

    private 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();
    }

}

service

@Service
public class ExportPdfService {

    public void exportPdf(MultipartFile file, OutputStream outputStream) throws Exception {

        String waterMarkText =  "自定義水印";
        InputStream inputStream = file.getInputStream();
        HtmlToPdfUtils.convertToPdf(inputStream, waterMarkText, outputStream);

    }

}

controller,工具類用的是hutool的。

@Slf4j
@RestController
public class ExportPdfController {

    @Autowired
    private ExportPdfService exportPdfService;

    @PostMapping("/export")
    public void exportVehicleArchives(MultipartFile file, HttpServletResponse response) throws Exception {
        try{
            String fileNamePrefix = "檔名稱";
            String date = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
            String fileName = fileNamePrefix + "_" + date +".pdf";
            this.resolveResponse(response, fileName);
            this.exportPdfService.exportPdf(file, response.getOutputStream());
        } catch (Exception e) {
            this.resetResponse(response, e);
        }
    }

    private void resolveResponse(HttpServletResponse response, String fileName){
        response.setContentType("application/pdf");
        response.setCharacterEncoding("utf-8");
        String encodeFileName = URLEncoder.createDefault().encode(fileName, StandardCharsets.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 stacktrace = ExceptionUtil.stacktraceToString(exception);
        log.error("{}", stacktrace);
        String result = "下載檔案失敗," + exception.getMessage();
        response.getWriter().println(result);
    }

}

這樣前端就能順利匯出pdf了

寫在最後的話

itext7明顯比itext5好用很多,如果匯出的pdf樣式有問題,讓前端修改一下html的樣式就可以了,比如去除padding-left,去除label的對齊,圖片小一點等等。我們前端一點一點的修改才最終匯出了符合產品的pdf。