QUARKUS - Generate Microsoft Word with Apache POI

Hello everyone, today we will learn how to generate and export a Microsoft word document with Quarkus and Apache POI. 

You can generate a Microsoft word document like below at the end of this post,


Project Structure:


Maven[pom.xml]:

<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.knf.dev.demo</groupId>
<artifactId>quarku-microsoft-word-demo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<compiler-plugin.version>3.8.1</compiler-plugin.version>
<maven.compiler.parameters>true</maven.compiler.parameters>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<quarkus-plugin.version>2.2.3.Final</quarkus-plugin.version>
<quarkus.platform.artifact-id>
quarkus-universe-bom
</quarkus.platform.artifact-id>
<quarkus.platform.group-id>io.quarkus</quarkus.platform.group-id>
<quarkus.platform.version>2.2.3.Final</quarkus.platform.version>
<surefire-plugin.version>2.22.1</surefire-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>${quarkus.platform.artifact-id}</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.platform.version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>build</goal>
<goal>generate-code</goal>
<goal>generate-code-tests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<parameters>
${maven.compiler.parameters}
</parameters>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.manager>
org.jboss.logmanager.LogManager
</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<systemPropertyVariables>
<native.image.path>
${project.build.directory}/${project.build.finalName}-runner
</native.image.path>
<java.util.logging.manager>
org.jboss.logmanager.LogManager
</java.util.logging.manager>
<maven.home>${maven.home}
</maven.home>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<quarkus.package.type>
native
</quarkus.package.type>
</properties>
</profile>
</profiles>
</project>

Generate Microsoft Word [WordHelper.class]:

package com.knf.dev.demo.helper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class WordHelper {

static String imgFile = "/home/user/Downloads/"
+ "Quarkus-main/quarku-microsoft-word-demo"
+ "/src/main/resources/quarkus.jpeg";

public static ByteArrayInputStream generateWord()
throws FileNotFoundException, IOException,
InvalidFormatException {
try (XWPFDocument doc = new XWPFDocument()) {

XWPFParagraph p1 = doc.createParagraph();
p1.setAlignment(ParagraphAlignment.CENTER);
// Set Text to Bold and font size to 22 for first paragraph
XWPFRun r1 = p1.createRun();
r1.setBold(true);
r1.setItalic(true);
r1.setFontSize(22);
r1.setText("Quarkus + Apache POI Example");
r1.setFontFamily("Courier");
r1.setColor("008000");
r1.addBreak();

XWPFParagraph p2 = doc.createParagraph();
// Set color for second paragraph
XWPFRun r2 = p2.createRun();
r2.setText("Quarkus + Apache POI Example");
r2.setColor("FF5733");
r2.setEmbossed(true);
r2.setStrikeThrough(true);
r2.addBreak();
r2.addBreak();

XWPFParagraph p3 = doc.createParagraph();
p3.setAlignment(ParagraphAlignment.CENTER);
XWPFRun r3 = p3.createRun();
r3.setBold(true);
r3.setItalic(true);
r3.setFontSize(22);
r3.setText("Table");
r3.setFontFamily("Arial");

XWPFTable table = doc.createTable();
// Creating first Row
XWPFTableRow row1 = table.getRow(0);
row1.getCell(0).setText("Java, Scala");
row1.addNewTableCell().setText("PHP, Flask");
row1.addNewTableCell().setText("Ruby, Rails");

// Creating second Row
XWPFTableRow row2 = table.createRow();
row2.getCell(0).setText("C, C ++");
row2.getCell(1).setText("Python, Kotlin");
row2.getCell(2).setText("Android, React");

// add png image
XWPFRun r4 = doc.createParagraph().createRun();
r4.addBreak();
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
try (FileInputStream is = new FileInputStream(imgFile)) {
r.addPicture(is, Document.PICTURE_TYPE_PNG, imgFile,
Units.toEMU(500), Units.toEMU(200));

}

ByteArrayOutputStream b = new ByteArrayOutputStream();
doc.write(b);
return new ByteArrayInputStream(b.toByteArray());
}

}
}

Resource:

package com.knf.dev.demo;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import com.knf.dev.demo.helper.WordHelper;

@Path("/api")
public class Resource {

@GET
@Path("/word")
@Produces("application/vnd.openxmlformats-" +
"officedocument.wordprocessingml.document")
public Response word() throws FileNotFoundException,
InvalidFormatException, IOException {
ByteArrayInputStream bis = WordHelper.generateWord();
return Response.ok(bis).header("content-disposition",
"attachment; filename = mydoc.docx").build();
}
}

Run & Test:

Build application  jar file: mvn clean package


Start the application: java -jar quarkus-run.jar

Hit this URL in your local system, http://localhost:8080/api/word

Open the downloaded word file


Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

ReactJS - Bootstrap - Buttons

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

Java, Spring Boot Mini Project - Library Management System - Download

Top 5 Java ORM tools - 2024

Java - DES Encryption and Decryption example