Thumbnail Generator Microservice for PDF in Spring Boot

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

@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:

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.

@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:

public class ThumbnailResponse extends BaseThumbnailAttrib {
    private boolean result;
    private String message;
    private List 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 getThumbnailPages() {
        return thumbnailPages;
    }

    public void setThumbnailPages(List 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

{
    "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:

{
    "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:


	org.apache.pdfbox
	pdfbox-tools
	3.0.0


	net.sf.cssbox
	pdf2dom
	2.0.1

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:

@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 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 + "https://dzone.com/" + targetFileName;
                        DocumentsResponse documentsResponse = extDocumentService.uploadDocument(bucket, targetFilePath, resource, false, accessToken);
                        List 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 extensionOpt = getExtensionByStringHandling(filePath);
                            if (extensionOpt.isPresent()) {
                                String extension = extensionOpt.get();
                                for (int i = 1; i  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:

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.