VOOZH about

URL: https://dzone.com/articles/thumbnail-generator-spring-boot-pdf

โ‡ฑ Thumbnail Generator Microservice for PDF in Spring Boot


Related

  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. Thumbnail Generator Microservice for PDF in Spring Boot

Thumbnail Generator Microservice for PDF in Spring Boot

Build a utility Spring Boot microservice that converts PDF documents to PNG thumbnails with the open-source Apache PDFBox package.

By Apr. 21, 25 ยท Tutorial
Likes
Comment
Save
3.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will delve into converting a PDF to individual PNG image files for each page. Typically, if we have a PDF document shared with our customers and need to preview the first page for users in push notifications, this article will help us create a preview thumbnail image from the PDF document. 

In this article, we will cover the Spring microservice for converting PDF documents to PNG images.

API Endpoint

In our Spring application, we will create an API endpoint to convert PDF documents to thumbnail images.

Controller

Java
@RestController
public class DocumentController extends BaseController {

 @Autowired
 ThumbnailGeneratorService thumbnailGeneratorService;

 @Autowired
 FileConversionService fileConversionService;

 @PostMapping(path = {"system/v1/thumbnail/{sourceType}/{targetType}"}, consumes = "application/json", produces = "application/json")
 public ThumbnailResponse createThumbnailsForPDF(@PathVariable("sourceType") String sourceType, @PathVariable("targetType") String targetType,
 @RequestBody @Valid ThumbnailRequest thumbnailRequest) {
 thumbnailRequest.setSourceType(sourceType);
 thumbnailRequest.setTargetType(targetType);
 return thumbnailGeneratorService.generateThumbnail(thumbnailRequest);
 }
}


Note that sourceType is a PDF and targetType is a PNG.

Below is the request object:

Java
public class ThumbnailRequest extends BaseThumbnailAttrib{
 String sourceType;
 String targetType;
 String targetFilePath;
 String targetFileName;
 boolean generateThumbnailForAllPages;

 public String getSourceType() {
 return sourceType;
 }

 public void setSourceType(String sourceType) {
 this.sourceType = sourceType;
 }

 public String getTargetType() {
 return targetType;
 }

 public void setTargetType(String targetType) {
 this.targetType = targetType;
 }

 public String getTargetFilePath() {
 return targetFilePath;
 }

 public void setTargetFilePath(String targetFilePath) {
 this.targetFilePath = targetFilePath;
 }

 public String getTargetFileName() {
 return targetFileName;
 }

 public void setTargetFileName(String targetFileName) {
 this.targetFileName = targetFileName;
 }

 public boolean getGenerateThumbnailForAllPages() {
 return generateThumbnailForAllPages;
 }

 public void setGenerateThumbnailForAllPages(boolean generateThumbnailForAllPages) {
 this.generateThumbnailForAllPages = generateThumbnailForAllPages;
 }
}


In this case, we are sending the PDF file path. This PDF path would be an AWS S3 path. We can easily modify this endpoint to accept a raw file instead of an AWS S3 path.

Java
@PostMapping(path = {"system/v1/thumbnail/{sourceType}/{targetType}"}, consumes = "application/json", produces = "application/json")
public ThumbnailResponse createThumbnailsForPDF(@PathVariable("sourceType") String sourceType, @PathVariable("targetType") String targetType,
 @RequestParam(value = "file", required = true) MultipartFile document)


Below is the response class:

Java
public class ThumbnailResponse extends BaseThumbnailAttrib {
 private boolean result;
 private String message;
 private List<ThumbnailPage> thumbnailPages;

 public boolean getResult() {
 return result;
 }

 public void setResult(boolean result) {
 this.result = result;
 }

 public String getMessage() {
 return message;
 }

 public void setMessage(String message) {
 this.message = message;
 }

 public List<ThumbnailPage> getThumbnailPages() {
 return thumbnailPages;
 }

 public void setThumbnailPages(List<ThumbnailPage> thumbnailPages) {
 this.thumbnailPages = thumbnailPages;
 }
}

public class BaseThumbnailAttrib {
 private String bucket;
 private String filePath;

 public String getBucket() {
 return bucket;
 }

 public void setBucket(String bucket) {
 this.bucket = bucket;
 }

 public String getFilePath() {
 return filePath;
 }

 public void setFilePath(String filePath) {
 this.filePath = filePath;
 }
}


BaseController is a common infrastructure class for all controllers.

API Request and Response

Below is the sample Request

JSON
{
    "bucket": "docs-bucket-name",
    "filePath": "DOCS/Invoices/5cbe38b6-cacd-11ef-afae-0ec1fc5a2deb/Invoices-0420202501.pdf",
    "targetFilePath": "1182249/1182249/docs/thumbnail",
    "targetFileName": "DocThumbnail.png"
}


Sample response:

JSON
{
 "bucket": "docs-bucket-name",
 "filePath": "1182249/1182249/docs/thumbnail/DocThumbnail.png",
 "result": true,
 "message": "Thumbnail generated successfully",
 "thumbnailPages": [
 {
 "pageNumber": 1,
 "thumbnailFilePath": "1182249/1182249/docs/thumbnail/DocThumbnail.png"
 }
 ]
}


Packages

We need to add the following packages to the Spring Boot application:

XML
<dependency>
	<groupId>org.apache.pdfbox</groupId>
	<artifactId>pdfbox-tools</artifactId>
	<version>3.0.0</version>
</dependency>
<dependency>
	<groupId>net.sf.cssbox</groupId>
	<artifactId>pdf2dom</artifactId>
	<version>2.0.1</version>
</dependency>


The Apache PDFBox library is an open-source Maven package for working with PDF documents. This package allows the creation of new PDF documents, the manipulation of existing documents, and the ability to extract content from documents.

PNG Image Generator Service

Below is the code snippet for the thumbnail (PNG file) generator service:

Java
@Service
@Qualifier("thumbnailGeneratorService")
public class ThumbnailGeneratorService {

 private final Logger logger = LoggerFactory.getLogger(this.getClass());

 @Autowired
 ExtDocumentService extDocumentService;

 @Autowired
 ConfigurationRepository configurationRepository;

 @Autowired
 private BaseService baseService;

 public ThumbnailResponse generateThumbnail(ThumbnailRequest thumbnailRequest) {
 ThumbnailResponse thumbnailResponse = null;
 try {
 Optional<String> token = baseService.getDomain().getAccessToken();
 if (token.isPresent()) {
 String accessToken = token.get();
 if (thumbnailRequest != null && StringUtils.hasText(thumbnailRequest.getBucket())
 && StringUtils.hasText(thumbnailRequest.getSourceType())
 && StringUtils.hasText(thumbnailRequest.getTargetType())
 && StringUtils.hasText(thumbnailRequest.getFilePath())) {
 String sourceType = thumbnailRequest.getSourceType();
 String targetType = thumbnailRequest.getTargetType();
 String filePath = thumbnailRequest.getFilePath();
 String bucket = thumbnailRequest.getBucket();
 String targetFileName = thumbnailRequest.getTargetFileName();
 String targetFilePath = thumbnailRequest.getTargetFilePath();
 if (sourceType.equalsIgnoreCase("pdf") && targetType.equalsIgnoreCase("png")) {
 byte[] fileContent = extDocumentService.getDocument(bucket, filePath, accessToken);
 InputStream inputStream = new ByteArrayInputStream(fileContent);
 BufferedImage bufferedImage = null;
 PDDocument document = PDDocument.load(inputStream);
 PDFRenderer pdfRenderer = new PDFRenderer(document);
 float dpi = 200.0f;
 String dpiConfigValue = configurationRepository.getConfigValue("uw_quote_doc_thumbnail_dpi", "UTILITY_API", null);
 if (StringUtils.hasText(dpiConfigValue)) {
 dpi = Float.parseFloat(dpiConfigValue);
 }
 bufferedImage = pdfRenderer.renderImageWithDPI(0, dpi, ImageType.RGB);
 Resource resource = CommonUtility.convertToByteArrayResource(bufferedImage, "png", targetFileName);
 targetFilePath = targetFilePath + "/" + targetFileName;
 DocumentsResponse documentsResponse = extDocumentService.uploadDocument(bucket, targetFilePath, resource, false, accessToken);
 List<ThumbnailPage> thumbnailPages = new ArrayList<>();
 if (documentsResponse != null && StringUtils.hasText(documentsResponse.getDocId())) {
 thumbnailResponse = new ThumbnailResponse();
 thumbnailResponse.setBucket(bucket);
 thumbnailResponse.setFilePath(documentsResponse.getDocId());
 thumbnailResponse.setResult(true);
 thumbnailResponse.setMessage("Thumbnail generated successfully");
 ThumbnailPage thumbnailPage = new ThumbnailPage();
 thumbnailPage.setPageNumber(1);
 thumbnailPage.setThumbnailFilePath(documentsResponse.getDocId());
 thumbnailPages.add(thumbnailPage);
 thumbnailResponse.setThumbnailPages(thumbnailPages);
 }
 if (thumbnailRequest.getGenerateThumbnailForAllPages()){
 int pageCount = document.getNumberOfPages();
 Optional<String> extensionOpt = getExtensionByStringHandling(filePath);
 if (extensionOpt.isPresent()) {
 String extension = extensionOpt.get();
 for (int i = 1; i < pageCount; i++) {
 bufferedImage = pdfRenderer.renderImageWithDPI(i, dpi, ImageType.RGB);
 String pageTargetFileName = thumbnailRequest.getTargetFileName();
 pageTargetFileName = pageTargetFileName.replaceAll(extension, "").replace(".", "");
 pageTargetFileName = pageTargetFileName + "_" + (i + 1) + ".png";
 resource = CommonUtility.convertToByteArrayResource(bufferedImage, "png", pageTargetFileName);
 String pageTargetFilePath = thumbnailRequest.getTargetFilePath() + "/" + pageTargetFileName;
 documentsResponse = extDocumentService.uploadDocument(bucket, pageTargetFilePath, resource, false, accessToken);
 if (documentsResponse != null && StringUtils.hasText(documentsResponse.getDocId())) {
 ThumbnailPage thumbnailPage = new ThumbnailPage();
 thumbnailPage.setPageNumber(i + 1);
 thumbnailPage.setThumbnailFilePath(documentsResponse.getDocId());
 thumbnailPages.add(thumbnailPage);
 }
 }
 }
 }
 }
 }
 }
 } catch (Exception ex) {
 logger.error("ThumbnailGeneratorService::generateThumbnail - An error occurred while generating thumbnail, detail error:", ex);
 }
 return thumbnailResponse;
 }

 public Optional<String> getExtensionByStringHandling(String filename) {
 return Optional.ofNullable(filename)
 .filter(f -> f.contains("."))
 .map(f -> f.substring(filename.lastIndexOf(".") + 1));
 }
}


The service loads the PDF file from S3 and then converts it to thumbnail images. The service factors into whether we need to generate the thumbnail for the first page or for all pages. The service returns the generated PNG S3 file paths.  Instead of returning file paths, we can return a zip file containing multiple PNG files.

extDocumentService is a generic utility service for loan saving the S3 documents, getDocument loads the document from S3, and uploadDocument uploads the document to S3.

The DPI setting helps generate higher-resolution PNG files from a PDF file. The lower the DPI value, the lower the image quality. We can render other image types apart from ImageType.RGB like ImageType.GRAY.

Implementation details for convertToByteArrayResource:

Java
public static ByteArrayResource convertToByteArrayResource(BufferedImage bufferedImage, String format, String fileName) throws Exception {
	// Convert BufferedImage to ByteArrayOutputStream
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ImageIO.write(bufferedImage, format, baos); // Format can be "png", "jpg", etc.
	baos.flush();

	// Convert ByteArrayOutputStream to byte array
	byte[] imageBytes = baos.toByteArray();
	final ByteArrayResource byteArrayResource = new ByteArrayResource(imageBytes) {
		@Override
		public String getFilename() {
			return fileName;
		}
	};
	baos.close();
	return byteArrayResource;
}


Conclusion

In this article, using the Apache PDFBox open-source package, we have created a Spring Boot microservice that converts PDF documents into PNG thumbnails. This generic utility service allows us to generate preview images for PDF files, which are used in push notification previews, image galleries, or any other user interface that requires visual document representation. By customizing parameters like DPI, we can control the image quality.

Document PDF Spring Boot Data Types

Opinions expressed by DZone contributors are their own.

Related

  • How To Add, Remove, or Rotate Pages in a PDF Document Using Java
  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Securing Verifiable Credentials With DPoP: A Spring Boot Implementation
  • Jakarta EE 11 and the Road Ahead With Jakarta EE 12

Partner Resources

ร—

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: