Integrating PDF.js into a Spring Boot Application for PDF Preview
This guide walks through setting up a Spring Boot project, adding PDF.js static assets, creating a preview page, implementing a backend controller to serve PDF files, configuring MIME types, and testing the integrated PDF viewer for proper functionality.
1. Preparation
Create a Spring Boot project (e.g., via Spring Initializr) with Spring Web dependency, using Spring Boot 3.4.2 and Java 21.
Download the legacy PDF.js distribution (pdfjs-4.10.38-legacy-dist.zip) from the official repository and place the extracted files into the project's static resources directory (e.g., src/main/resources/static/ ).
2. Integration Steps
2.1 Add PDF.js files – Ensure the PDF.js CSS and JS files are accessible from the static folder so the front‑end page can load them.
2.2 Configure static resource mapping – Spring Boot automatically maps /static and /public ; no extra configuration is required for this example.
2.3 Create a PDF preview page – Add an HTML file under src/main/resources/templates/ that includes the PDF.js assets and an iframe to display the PDF. Example code:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>pdf.js + spring boot</title>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<style>
iframe { border: solid 1px #bfbfbf; border-radius: 6px; }
</style>
</head>
<body>
<script type="text/javascript">
function loadPdf(){
document.getElementById('myIframe').src = '/pdfjs-4.10.38-legacy-dist/web/viewer.html?file=http://localhost:8080/media/preview';
}
window.onload = function() { loadPdf(); };
</script>
<p>
<iframe id="myIframe" src="" title="pdf文件预览" width="100%" height="100%"></iframe>
</p>
</body>
</html>2.4 Backend PDF file endpoint – Implement a Spring MVC controller that reads a PDF from the classpath (e.g., classpath:doc/1996_PODC_queues.pdf ) and writes it to the response as application/pdf :
package com.renzhikeji.pdfviewer.controller;
import java.io.*;
import jakarta.servlet.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/media")
public class PdfviewerPdfjsController {
@GetMapping
public String home() { return "home"; }
@GetMapping("preview")
public void preview(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
File file = ResourceUtils.getFile("classpath:doc/1996_PODC_queues.pdf");
if (file.exists()) {
try (FileInputStream input = new FileInputStream(file)) {
byte[] data = new byte[input.available()];
input.read(data);
response.setContentType("application/pdf");
response.getOutputStream().write(data);
response.flushBuffer();
} catch (Exception e) { System.out.println(e.getMessage()); }
}
}
}2.5 MIME type configuration for .mjs files – Add a configuration class to map the mjs extension to application/javascript so browsers load PDF.js modules correctly:
package com.renzhikeji.pdfviewer.config;
import org.springframework.boot.web.server.*;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MimeConfig implements WebServerFactoryCustomizer
{
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.add("mjs", "application/javascript");
factory.setMimeMappings(mappings);
}
}3. Testing and Optimization
Run the Spring Boot application, navigate to the preview page, and verify that the PDF loads correctly in the iframe. Adjust styles or PDF.js settings for browser compatibility, and consider enhancements such as page‑turn animations or lazy loading to improve user experience.
Source code repository: https://github.com/sdcuike/ppdfviewer-springboot-demo
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.