DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

How to convert PDF to image in Java

Convert PDF to image is a common need for developers. With the help of Free Spire.PDF, we can easily convert PDF files of any size and version to image with high quality in Java applications. In this article, I will explain the solutions of converting the PDF file to bitmap images in PNG, BMP, JPEG, GIF etc. and PDF file to vector images in EMF, WMF, and SVG.

Convert the PDF page to bitmap images (BMP, Jpeg, Png, and GIF)

Spire.PDF for Java offers a method pdf.saveAsImage() to convert PDF page to bitmap images in Jpeg, Jpg, Png, Bmp, Tiff, Gif and also vector images in WMF and EMF format etc. Here we use PDF to .png image for example.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import com.spire.pdf.PdfDocument;
import javax.imageio.ImageIO;

public class PDFtoImage {
        public static void main(String[] args) throws IOException {
        //load the sample PDF
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("Sample.pdf");

        //save every PDF to .png image
        BufferedImage image;
        for (int i = 0; i < pdf.getPages().getCount(); i++) {
            image = pdf.saveAsImage(i);
            File file = new File( String.format("ToImage-img-%d.png", i));
            ImageIO.write(image, "png", file);
        }
        pdf.close();
    }

}

output

Convert the PDF page to vector images (EMF, WMF, SVG)
The common vector images formats are EMF, WMF and SVG. Spire.PDF for Java offers a method pdf.saveToFile("result.svg",FileFormat.SVG) to save PDF page to SVG image. With this method, each page on the PDF file has been saved as a single SVG file by default. For example, if the PDF contains 10 pages, we will get 10 SVG files separately. We can also set the property pdf.getConvertOptions().setOutputToOneSvg() as true to convert a multipage PDF to one single SVG file in Java.

import com.spire.pdf.*;

public class PDFtoImage {
    public static void main(String[] args) {
        //Load the PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("Sample.pdf");

        //convert the PDF to one SVG
        pdf.getConvertOptions().setOutputToOneSvg(true);

        //Save to SVG image
        pdf.saveToFile("Output/output.svg",FileFormat.SVG);
        pdf.close();
    }
}

Output

Top comments (0)