mn create-app example.micronaut.micronautguide \
--features= \
--build=gradle \
--lang=java \
--test=junit
Download a PDF with OpenPDF
Learn how to generate a PDF in a Micronaut Controller with OpenPDF.
Authors: Sergio del Amo
Micronaut Version: 4.6.3
1. Getting Started
In this guide, we will create a Micronaut application written in Java.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOME
configured appropriately
3. Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut
in a directory named micronautguide
.
If you use Micronaut Launch, select Micronaut Application as application type and add null features.
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application. |
5. OpenPDF
To generate PDFs, we use OpenPDF.
OpenPDF is a Java library for creating and editing PDF files with a LGPL and MPL open source license. OpenPDF is the LGPL/MPL open source successor of iText, and is based on some forks of iText 4 svn tag. We welcome contributions from other developers. Please feel free to submit pull-requests and bugreports to this GitHub repository.
5.1. OpenPDF Dependency
To use OpenPDF, add the following dependency:
implementation("com.github.librepdf:openpdf:1.3.35")
6. Controller
Create a controller that generates and downloads a PDF.
package example.micronaut;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.io.Writable;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.scheduling.TaskExecutors;
import io.micronaut.scheduling.annotation.ExecuteOn;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
@Controller("/pdf") (1)
class PDFController {
@ExecuteOn(TaskExecutors.BLOCKING) (2)
@Get("/download") (3)
HttpResponse<Writable> download() throws IOException { (4)
return download("example.pdf");
}
private HttpResponse<Writable> download(String filename) throws IOException {
return HttpResponse.ok(pdfWritable())
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF);
}
private Writable pdfWritable() {
return new Writable() {
public void writeTo(OutputStream outputStream, @Nullable Charset charset) throws IOException {
generatePDF(outputStream);
}
public void writeTo(Writer out) {
}
};
}
private void generatePDF(OutputStream outputStream) {
try (Document document = new Document()) {
PdfWriter.getInstance(document, outputStream);
document.open();
document.newPage();
document.add(new Paragraph("Hello World"));
}
}
}
1 | The class is defined as a controller with the @Controller annotation mapped to the path /pdf . |
2 | It is critical that any blocking I/O operations (such as fetching the data from the database) are offloaded to a separate thread pool that does not block the Event loop. |
3 | The @Get annotation maps the download method to an HTTP GET request on /download . |
4 | When returning a Writable, the blocking I/O operation is shifted to the I/O thread pool so the Netty event loop is not blocked. |
7. Test
Create a test that verifies the controller’s download matches the expected text.
package example.micronaut;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.parser.PdfTextExtractor;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@MicronautTest (1)
class PDFControllerTest {
@Test
void testDownload(@Client("/") HttpClient httpClient) throws IOException { (2)
BlockingHttpClient client = httpClient.toBlocking();
HttpResponse<byte[]> pdfResponse = assertDoesNotThrow(() -> client.exchange("/pdf/download", byte[].class));
assertEquals(HttpStatus.OK, pdfResponse.status());
assertEquals(MediaType.APPLICATION_PDF, pdfResponse.getHeaders().get(HttpHeaders.CONTENT_TYPE));
assertEquals("attachment; filename=example.pdf", pdfResponse.getHeaders().get(HttpHeaders.CONTENT_DISPOSITION));
byte[] pdfBytes = pdfResponse.body();
String firstPageText = textAtPage(pdfBytes, 1);
assertEquals("Hello World", firstPageText);
}
private static String textAtPage(PdfReader pdfReader, int pageNumber) throws IOException {
PdfTextExtractor pdfTextExtractor = new PdfTextExtractor(pdfReader);
return pdfTextExtractor.getTextFromPage(pageNumber);
}
private static String textAtPage(byte[] pdfBytes, int pageNumber) throws IOException {
try (PdfReader pdfReader = new PdfReader(pdfBytes)) {
return textAtPage(pdfReader, pageNumber);
}
}
}
1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
2 | Inject the HttpClient bean and point it to the embedded server. |
8. Testing the Application
To run the tests:
./gradlew test
Then open build/reports/tests/test/index.html
in a browser to see the results.
9. Running the Application
To run the application, use the ./gradlew run
command, which starts the application on port 8080.
Visit http://localhost:8080/pdf/download and the browser downloads a PDF.
10. Next steps
Explore more features with Micronaut Guides.
Learn more about OpenPDF.
11. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
12. License
All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…). |