Skip to content

Instantly share code, notes, and snippets.

@aeischeid
Created May 25, 2021 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeischeid/8fa4f6de3a23d36c64c9ceac8022e1a5 to your computer and use it in GitHub Desktop.
Save aeischeid/8fa4f6de3a23d36c64c9ceac8022e1a5 to your computer and use it in GitHub Desktop.
use pdfBox library to render a pdf file as a png.
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import groovy.transform.CompileStatic
// pdfbox imports
import org.apache.pdfbox.cos.*
import org.apache.pdfbox.pdmodel.*
import org.apache.pdfbox.pdmodel.common.*
import org.apache.pdfbox.rendering.PDFRenderer
class PdfService {
// pageNumber is zero indexed for the sake of consistency with PdfBox.
@CompileStatic
File makePngFromPdfPage(File doc, int pageNumber = 0) {
PDDocument document = PDDocument.load(doc)
// many forms aren't flattened doing so helps ensure they display properly in more pdf renderers.
try {
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm()
if (acroForm) {
acroForm.getCOSObject().setItem(COSName.getPDFName('NeedAppearances'), COSBoolean.TRUE)
acroForm.getCOSObject().setNeedToBeUpdated(true)
acroForm.refreshAppearances()
acroForm.flatten()
}
} catch(e) {
log.error('error in flattening form')
}
PDFRenderer renderer = new PDFRenderer(document)
BufferedImage bimg = renderer.renderImageWithDPI(pageNumber, 240) // will be RGB - not black/white or greyscale
File tempPngFile = File.createTempFile("${doc.key}TempFile", '.png')
// NOTE: if memory usage or disc IO ends up being a problematic bottleneck consider move to ImageOutputStream instead
ImageIO.write(bimg, 'png', tempPngFile)
document.close()
return tempPngFile
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment