Springboot integrates itextpdf to dynamically generate and display PDF

Time:2022-1-7

background

Continued aboveSpringboot integrates markdown to realize document management, markdown is not particularly friendly to the support of tables, and the internal document management needs to add the function of table format API interface documents. Therefore, it is decided to use the method of combining database storage and dynamic generation of PDF with the help of directory structure

Table structure design

Table of contents

DROP TABLE IF EXISTS `knowledge_interfacecatalog`;
CREATE TABLE `knowledge_interfacecatalog` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `UnitGuid` varchar(50) DEFAULT NULL,
  `AddDate` datetime DEFAULT NULL,
  `CataName` varchar(100) DEFAULT NULL,
  `ParentCataGuid` varchar(50) DEFAULT NULL,
  `SortNum` int(11) DEFAULT NULL,
  `DocGuid` varchar(50) DEFAULT NULL,
  KEY `ID` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;

Interface content table

DROP TABLE IF EXISTS `knowledge_interfaceinfo`;
CREATE TABLE `knowledge_interfaceinfo` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `UnitGuid` varchar(50) DEFAULT NULL,
  `AddDate` datetime DEFAULT NULL,
  `InterfaceName` varchar(100) DEFAULT NULL,
  `Description` varchar(500) DEFAULT NULL,
  `Remark` varchar(500) DEFAULT NULL,
  `ParamJson` varchar(2000) DEFAULT NULL,
  `ResponseJson` varchar(2000) DEFAULT NULL,
  `InterfaceAddress` varchar(500) DEFAULT NULL,
  `SortNum` int(11) DEFAULT NULL,
  `CataGuid` varchar(50) DEFAULT NULL,
  `DocGuid` varchar(50) DEFAULT NULL,
  KEY `ID` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb4;

Input interface

Pdf generation

quote

com.itextpdf
            itextpdf
            5.4.3
        

        
            com.itextpdf
            itext-asian
            5.2.0

Create pdf

Document document = new Document(PageSize.A2);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
  	document.addTitle(doc.getDocName());
    document.addAuthor("xxxxx");
    document.addCreationDate();
    document. Addlanguage ("Chinese");
    document.open();

Set custom font

File fontFile = new File("font/msyh.ttf");
    BaseFont bf = BaseFont.createFont(fontFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font fontChinese5 = new Font(bf,14);

Add chapters and paragraphs

//Font for directory
   Font cataFont = new Font(bf, 24, Font.NORMAL, BaseColor.BLACK);
   //Interface font
   Font interFont = new Font(bf, 20, Font.NORMAL, BaseColor.BLACK);     
   for(int i=1;i<=10;i++){
		Chapter chapter = new chapter (new paragraph ("directory", catafont), I);
        for(int j=1;j<=5;j++){
            Section section = chapter. Addsection (new paragraph ("interface", interfont));
        }
        document.add(chapter);
    }
	document.close();

Add table

PdfPTable table = new PdfPTable(3);// Generate a 3-column table
  //Center table vertically
  table.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.setTotalWidth(800f);
  float[] widths = new float[] { 150f,325f,325f };
  table.setWidths(widths);
  PdfPCell cell;
  Cell = new pdfpcell (new paragraph ("interface address", fontchinese5));
  table.addCell(cell);
   cell = new PdfPCell(new Paragraph(interfaceInfoDO.getInterfaceAddress(),fontChinese5));
  cell.setColspan(2);
  table.addCell(cell);

Tab replacement

In the process of PDF generation, invalid tab \ T results in style change, which requires encoding and replacement (“\ T”, “\ u00a0 \ u00a0 \ u00a0 \ u00a0”)

Pdf presentation

Pdf is selected here JS for display, reference relevant files, and the file in and out of the address bar represents the URL address. Because it is used for interface document display, I need to enter the directory mode by default, so I need to carry out relevant JS processing on the page

var interval = setInterval('loadPdf()', 1000);

    function loadPdf() {
        if (PDFViewerApplication.pdfDocument == null) {
            console.info('Loading...');
        } else {
            clearInterval(interval);
            console.info('Load Success...');
            var sidebarToggle =   $("#sidebarToggle");
            var viewOutline =   $("#viewOutline");
            if(!sidebarToggle.hasClass("toggled")){
              sidebarToggle.click();
            }
            if(!viewOutline.hasClass("toggled")){
              viewOutline.click();
            }
        }
    }

Display effect

Recommended Today

Springboot 2.6.3 integrated redis stepped on the pit

The integration steps are as follows: development tools: idea2019, JDK1.8, maven 3.5.4 Idea creates a new project, selects spring initializer, selects spring boot version 2.6.3 (the latest version at present), and adds web, and redis modules. After successful construction, the POM file is as follows: <?xml version=”1.0″ encoding=”UTF-8″?> <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <parent> […]