In this tutorials, we will see how to work with Spring Boot PDF with iText using String Template.

Spring Boot PDF iText integration:

Technologies:

    • SpringBoot 1.4.5.RELEASE
    • iTextpdf 5.2.0
  • String Template 3.2
  • iText Pdf tool xmlworker 1.1
  • HTML cleaner 2.2
  • Java 8

Example Spring Boot PDF iText:

Project Structure:

Spring Boot Pdf Itext String Template

pom.xml

Included iText pdf, StringTemplate, htmlcleaner and recommended dependencies.

pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.onlinetutorialspoint</groupId>
  <artifactId>SpringBoot-iText-Pdf-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringBoot-iText-Pdf-Example</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.5.RELEASE</version>
  </parent>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itextpdf</artifactId>
      <version>5.2.0</version>
    </dependency>
    <dependency>
      <groupId>org.antlr</groupId>
      <artifactId>stringtemplate</artifactId>
      <version>3.2</version>
    </dependency>
    <dependency>
      <groupId>com.itextpdf.tool</groupId>
      <artifactId>xmlworker</artifactId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
      <groupId>net.sourceforge.htmlcleaner</groupId>
      <artifactId>htmlcleaner</artifactId>
      <version>2.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Data.java

It is used to provide dynamic data to String template.

Data.java
package com.onlinetutorialspoint.beans;

public class Data {
  private String empNumber;
  private String empName;
  private String joiningDate;
  private String salary;
  private String deptNo;
  private String managerId;
  public Data(String empNumber, String empName,String joiningDate, String salary, String deptNo, String managerId) {
    super();
    this.empNumber = empNumber;
    this.empName = empName;
    this.joiningDate = joiningDate;
    this.salary = salary;
    this.deptNo = deptNo;
    this.managerId = managerId;
  }
  public String getEmpNumber() {
    return empNumber;
  }
  public void setEmpNumber(String empNumber) {
    this.empNumber = empNumber;
  }
  
  public String getEmpName() {
    return empName;
  }
  public void setEmpName(String empName) {
    this.empName = empName;
  }
  public String getJoiningDate() {
    return joiningDate;
  }
  public void setJoiningDate(String joiningDate) {
    this.joiningDate = joiningDate;
  }
  public String getSalary() {
    return salary;
  }
  public void setSalary(String salary) {
    this.salary = salary;
  }
  public String getDeptNo() {
    return deptNo;
  }
  public void setDeptNo(String deptNo) {
    this.deptNo = deptNo;
  }
  public String getManagerId() {
    return managerId;
  }
  public void setManagerId(String managerId) {
    this.managerId = managerId;
  }
}

Exports.java

Export Controller is used to handling actual pdf export logic. Where we create Data object and passed dynamic data to the StringTemplate object.

Exports.java
package com.onlinetutorialspoint.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import com.onlinetutorialspoint.beans.Data;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

@Controller
public class Exports {

  @RequestMapping(value = "generatePDF.htm", method = RequestMethod.GET)
  public void exportToPDF(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    OutputStream os = null;
    try {
      
      Data data = new Data("8596582","CHANDRA SHEKHAR","03/30/2016","$2,000.00","1005205",
          "452562");

      StringTemplate page = getStringTemplate();
      page.setAttribute("data",data);
      
      String content = page.toString();

      final HtmlCleaner htmlCleaner = new HtmlCleaner();
      final TagNode tagNode = htmlCleaner.clean(content);
      content = htmlCleaner.getInnerHtml(tagNode);

      os = response.getOutputStream();

      Document document = null;

      document = new Document(PageSize.A4);

      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      final PdfWriter writer = PdfWriter.getInstance(document, baos);
      document.open();

      final HtmlPipelineContext htmlContext = new HtmlPipelineContext();

      htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

      final CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
      final Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext,
          new PdfWriterPipeline(document, writer)));
      final XMLWorker worker = new XMLWorker(pipeline, true);
      final XMLParser parser = new XMLParser(worker);

      try {
        parser.parse(new StringReader(content));
      } catch (final Exception e) {
        e.printStackTrace();
        
      }

      document.close();
      response.setContentType("Content-Type: text/html; charset=UTF-8");
      response.addHeader(
          "Content-Disposition",
          "attachment; filename=employee_details.pdf");
      response.setContentLength(baos.size());
      baos.writeTo(os);
    } catch (final IOException | DocumentException e) {
      e.printStackTrace();
    } finally {
      try {
        if (os != null) {
          os.flush();
          os.close();
        }
      } catch (final IOException e) {
        e.printStackTrace();
      }
    }
  }

  StringTemplate getStringTemplate() {
    final StringTemplateGroup group = new StringTemplateGroup("Generators");
    return group.getInstanceOf("employee_details");
  }
}

HomeController.java

HomeController.java
package com.onlinetutorialspoint.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String init(Model model) {
        return "index.jsp";
    }
}

Creating StringTemplate.

employee_details.st

empoyee_details.st
<html>
<body leftmargin='10.0' rightmargin='10.0' topmargin='10.0' bottommargin='10.0' style='font-family: Arial; font-size: 14.0pt; '>
    <div>
          <table style='font-size:8.0pt; font-family:Arial;  border: 0.5px thick #000000; border-collapse: collapse; width: 1500pt;'>
        <tr>
          <td colspan='2' style='text-align:left; padding: .1pt .1pt .1pt .1pt;'>
             <p style='color: green;line-height: 12.0pt' >
              
             </p>	
          </td>
          <td colspan='4' style='text-align:left; padding: .1pt .1pt .1pt .1pt;'>
             <p style='color: black;line-height: 12.0pt' >
              <b><span style='font-size:16.0pt;font-family:Arial;color:00a8ff'>EMPLOYEE DETAILS</span></b>
             </p>	
          </td>
        </tr>
        <tr>
        <td colspan='6' style='text-align:left; background-color:00b894;'>
             <br/>
          </td>
        </tr>
      </table>
      <div>
          </div>
          <div leftmargin='36.0' rightmargin='36.0' topmargin='36.0' bottommargin='36.0'>
          <table style='font-size:8.0pt; font-family:Arial; border-collapse: collapse; width: 900pt;'>
        <tr>
          <td style='text-align:left; width:50%;padding: .1pt .1pt .1pt .1pt;'>
             <p style='line-height: 12.0pt' >
              <b><span style='font-size:10.0pt;font-family:Arial;'>Employee Number</span></b>
             </p>	
          </td>
          <td style='text-align:left; width:50%;padding: .1pt .1pt .1pt .1pt;'>
             <p style='line-height: 12.0pt' >
              <b><span style='font-size:10.0pt;font-family:Arial;'>Joining Date</span></b>
             </p>	
          </td>
        </tr>
        <tr>
          <td style='text-align:left; width:50%; padding: .1pt .1pt .1pt .1pt;'>
             <p style='line-height: 12.0pt' >
              <b><span style='font-size:10.0pt;font-family:Arial;'>$data.empNumber$</span></b>
             </p>	
          </td>
          <td style='text-align:left; width:50%; padding: .1pt .1pt .1pt .1pt;'>
             <p style='line-height: 12.0pt' >
              <b><span style='font-size:10.0pt;font-family:Arial;'>$data.joiningDate$</span></b>
             </p>	
          </td>
        </tr>
        <tr>
          <td colspan=2 style='width:100%;'>
             <p style='line-height: 12.0pt' >
             </p>	
          </td>
        </tr>			
      </table>
      <div>

          </div>
          
      <table style='font-size:8.0pt; font-family:Arial;  border: 0.5px thick #000000; border-collapse: collapse; width: 900pt;'>
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 100%'>
              <b><span style='font-size:10.0pt;font-family:Arial;'>EMPLOYEE NAME</span></b>
          </td>
        </tr>	
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 100%'>
              <b><span style='font-size:10.0pt;font-family:Arial;'>$data.empName$</span></b>
          </td>
        </tr>			
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 100%'>
              <span style='font-size:10.0pt;font-family:Arial;'>DEPARTMENT NUMBER</span>
          </td>
        </tr>	
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 100%'>
              <span style='font-size:10.0pt;font-family:Arial;'>$data.deptNo$</span>
          </td>
        </tr>
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 100%'>
          </td>
        </tr>
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 100%'>
              <span style='font-size:10.0pt;font-family:Arial;'>SALARY</span>
          </td>
        </tr>	
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 100%'>
              <span style='font-size:10.0pt;font-family:Arial;'>$data.salary$ </span>
          </td>
        </tr>	
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 100%'>
          </td>
        </tr>
        <tr>
          <td style='padding: .1pt .1pt .1pt .1pt; width : 50%'>
              <span style='font-size:10.0pt;font-family:Arial;'></span>
          </td>
          <td style='padding: .1pt .1pt .1pt .1pt; width : 50%'>
              <span style='font-size:10.0pt;font-family:Arial;'>MANAGER ID</span>
          </td>
        </tr>				
        <tr>
          <td style='padding: .1pt .1pt .1pt .1pt; width : 50%'>
              <span style='font-size:10.0pt;font-family:Arial;'></span>
          </td>
          <td style='padding: .1pt .1pt .1pt .1pt; width : 50%'>
              <span style='font-size:10.0pt;font-family:Arial;'>$data.managerId$</span>
          </td>
        </tr>
        <tr>
          <td colspan='2' style='padding: .1pt .1pt .1pt .1pt; width : 16%'>
          </td>
        </tr>
  
      </table>
      <div><br/></div>
      </div>
</div>
</body>
</html>		

Spring Boot Application.java

Application.java
package com.onlinetutorialspoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

Run Application:

Terminal
mvn clean install
mvn spring-boot:run
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ SpringBoot-iText-Pdf-Example ---
[INFO] No sources to compile
[INFO] 
[INFO] <<< spring-boot-maven-plugin:1.4.5.RELEASE:run (default-cli) < test-compile @ SpringBoot-iText-Pdf-Example <<<
[INFO] 
[INFO] --- spring-boot-maven-plugin:1.4.5.RELEASE:run (default-cli) @ SpringBoot-iText-Pdf-Example ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.5.RELEASE)

2018-05-20 18:40:47.665  INFO 5616 --- [           main] com.onlinetutorialspoint.Application     : Starting Application on DESKTOP-RN4SMHT with PID 5616 (E:\work\SpringBoot-iText-Pdf-Example\target\classes started by Lenovo in E:\work\SpringBoot-iText-Pdf-Example)
2018-05-20 18:40:47.665  INFO 5616 --- [           main] com.onlinetutorialspoint.Application     : No active profile set, falling back to default profiles: default
2018-05-20 18:40:47.790  INFO 5616 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]68db8c58: startup date [Sun May 20 18:40:47 IST 2018]; root of context hierarchy
2018-05-20 18:40:50.684  INFO 5616 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-05-20 18:40:50.705  INFO 5616 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2018-05-20 18:40:50.705  INFO 5616 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.11
....
....

Output:

Access application using :  http://localhost:8080/index

Spring Boot Pdf Itext String Template_output

Click on Download button, then the pdf will download into your local system.

Spring Boot Pdf Itext String Template_pdf

Happy Learning 🙂