Getting a preview image of a PDF file in Scala


In order to have an preview image of an PDF file you can use PDFBox. Here is the simple tutorial to extracting an preview image of an PDF file.

Firstly you need to get the pdfbox-jar file & you can get it here.

1. You need to have these following imports.

import java.io.FileInputStream
import javax.imageio.ImageIO
import org.dopdf.document.model.PageDetail
import org.dopdf.document.read.pdf.PDFDocumentReader
import java.io.ByteArrayInputStream
import utils.AmazonUpload
import java.io.InputStream
import java.io.File

2. Convert the file in to InputStream.

 val inputStream = new FileInputStream(pdfFile)


3. Pass the generated inputstream to PDFDocumentReader & set the page no. of which you want to have an image.

val pageDetail = new PageDetail("", "", 0, "")
val resourceDetails = document.getPageAsImage(pageDetail)

4. Use ImageIO in order to read the resource details from PDFDocumentReader as ByteArrayInputStream & write the generated preview image to desired location.

 val image = ImageIO.read(new ByteArrayInputStream(resourceDetails.getBytes()))
 ImageIO.write(image, "jpg", new File("/home/neelkanth/Desktop/previewOfPdf.jpg"))

Get the complete code file here :

object PreviewImageOfPDF extends App {

  val docReceived = new File("/home/neelkanth/Desktop/sample.pdf")
 
  /**
   * Method to extract an preview image of an pdf file
   */
  def convertPdfToImage(pdfFile: File) = {
    val inputStream = new FileInputStream(pdfFile)

    val document = new PDFDocumentReader(inputStream)
    val pageDetail = new PageDetail("", "", 0, "")
    val resourceDetails = document.getPageAsImage(pageDetail)

    val image = ImageIO.read(new ByteArrayInputStream(resourceDetails.getBytes()))
    ImageIO.write(image, "jpg", new File("/home/neelkanth/Desktop/previewOfPdf.jpg"))
    println("Preview Image Generated at specified location")
  }
  convertPdfToImage(docReceived) // Calling method
}

About Neelkanth Sachdeva

Software Consultant @ Knoldus Software LLP Co-Founder @ My Cell Was Stolen
This entry was posted in Java, Scala, Web and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s