Tips & Tricks - Convert a PDF to an Image File

This article shows how PDF files saved as attachments in an application can be converted into image files (e.g., .png or .jpg) using a process. You can download the sample application with the process here and import it as usual. Next, activate the included process.

Application

In the sample application, you can enter a title and description on the input page. There is also a file manager that allows you to upload PDFs in the browser. The images generated from the PDFs are stored in the "images" subgroup.

The data type of the primary key for this data group is GUID.

In the "images" data group, there is a file data field in which the process stores a reference to the images that have been created.

Process

The process responds to the insertion or modification of an entry in the "PDFs" data group.

Next, the images that have already been saved should be deleted from the child table in case an existing PDF is replaced.

The PDF file is then split into images using a Groovy action. Individual PDF pages are converted to images using the Apache "PDFBox" project (https://pdfbox.apache.org). All necessary classes are included with the installation of Intrexx and simply need to be incorporated into the Groovy script as an import.

import java.awt.Toolkit
import java.awt.image.BufferedImage
import org.apache.pdfbox.pdmodel.*
import org.apache.pdfbox.Loader
import org.apache.pdfbox.rendering.PDFRenderer
import java.io.IOException
import org.apache.pdfbox.pdmodel.PDPage
import org.apache.pdfbox.pdmodel.font.PDType1Font
import org.apache.pdfbox.pdmodel.PDPageContentStream
import javax.imageio.ImageIO
import java.util.List
import java.io.File
import java.io.FileWriter
import java.io.BufferedWriter
import org.apache.pdfbox.rendering.ImageType



//define variables
def conn = g_dbConnections.systemConnection
def strNewGuid
def l_pdfPage = 1
File tempFile = null

def inputFile = g_record[strInputFileGuid] /* datafield file <file> */
int l_recId = g_record[strRecIdGuid].value  /* data field (PK) (S) ID <integer> */

if (inputFile.hasValue() && inputFile.getFirstFile().getContentType() == "application/pdf") {
	try {
		//Get file from Intrexx
	 	def pdfFile = new File(inputFile.getFirstFile().getPath())

		// Load PDF document
		PDDocument document = Loader.loadPDF(pdfFile)

		// Get all pages
		pages = document.getDocumentCatalog().getPages()

		PDFRenderer pdfRenderer = new PDFRenderer(document);

		// for each page
		for (int i = 0; i < pages.getCount(); i++) {
			// single page
			PDPage singlePage = pages.get(i)

			// to BufferedImage

			BufferedImage buffImage = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);

			 /*use for quality configuration*/
			//BufferedImage buffImage =  singlePage.convertToImage(BufferedImage.TYPE_INT_BGR, 70)


			// Write image to temporary file

			tempFile = File.createTempFile("pdfImage", ".png")
			ImageIO.write(buffImage, "png", tempFile)

			//Generate a new GUID for the INSERT query
			strNewGuid = newGuid()

			//insert into child table
			g_dbQuery.executeUpdate(conn, "INSERT INTO ${strImageDatagroup} (${strVariableFKLID}, ${strVariableImageRecId}, ${strVariablePage}) VALUES (?, ?, ?)") {
				setInt(1, l_recId)
				setString(2, strNewGuid)
				setInt(3, l_pdfPage)
			}

			// Save image to Intrexx
            		g_dgFile.copy(guid: strImageFileGuid, id: strNewGuid, file: tempFile.getAbsolutePath(), replaceMode: true, triggerWorkflow: false)
			
			//next l_pdfPage as integer
			l_pdfPage = l_pdfPage + 1

			tempFile.delete()

	    }
			document.close()
	}
	catch (IOException e) {
		g_log.err(e)
	}
	finally
	{
	    //Delete PDFBox temporary files
	    File path = new File("internal/tmp/")
   		for (File file : path.listFiles()) {
   			if (file.getName().endsWith(".tmp") && file.getName().startsWith("+~")) {
        				file.delete()
      		}
   		}
	}
}