目录

合并多个PDF文档(Merging Multiple PDF Documents)

在上一章中,我们已经了解了如何合并多个PDF文档。 在本章中,我们将了解如何从PDF文档的页面中提取图像。

从PDF文档生成图像

PDFBox库为您提供了一个名为PDFRenderer的类, PDFRenderer PDF文档呈现为AWT BufferedImage。

以下是从PDF文档生成图像的步骤。

第1步:加载现有PDF文档

使用PDDocument类的静态方法load()加载现有PDF文档。 此方法接受文件对象作为参数,因为这是一个静态方法,您可以使用类名调用它,如下所示。

File file = new File("path of the document") 
PDDocument document = PDDocument.load(file);

第2步:实例化PDFRenderer类

名为PDFRenderer的类将PDF文档呈现为AWT BufferedImage 。 因此,您需要实例化此类,如下所示。 该类的构造函数接受一个文档对象; 传递上一步中创建的文档对象,如下所示。

PDFRenderer renderer = new PDFRenderer(document);

第3步:从PDF文档渲染图像

您可以使用Renderer类的renderImage()方法在特定页面中渲染图像,对于此方法,您需要传递要获得图像的页面的索引。

BufferedImage image = renderer.renderImage(0);

第4步:将图像写入文件

您可以使用write()方法将上一步中呈现的图像写入文件。 对于此方法,您需要传递三个参数 -

  • 渲染的图像对象。
  • 表示图像类型的字符串(jpg或png)。
  • 您需要保存提取的图像的文件对象。
ImageIO.write(image, "JPEG", new File("C:/PdfBox_Examples/myimage.jpg"));

第5步:关闭文档

最后,使用PDDocument类的close()方法关闭文档,如下所示。

document.close();

例子 (Example)

假设,我们在路径C:\PdfBox_Examples\有一个PDF文档 - sample.pdf ,它在第一页中包含一个图像,如下所示。

示例图像

此示例演示如何将上述PDF文档转换为图像文件。 在这里,我们将在PDF文档的第一页中检索图像并将其另存为myimage.jpg 。 将此代码保存为PdfToImage.java

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
public class PdfToImage {
   public static void main(String args[]) throws Exception {
      //Loading an existing PDF document
      File file = new File("C:/PdfBox_Examples/sample.pdf");
      PDDocument document = PDDocument.load(file);
      //Instantiating the PDFRenderer class
      PDFRenderer renderer = new PDFRenderer(document);
      //Rendering an image from the PDF document
      BufferedImage image = renderer.renderImage(0);
      //Writing the image to a file
      ImageIO.<i>write</i>(image, "JPEG", new File("C:/PdfBox_Examples/myimage.jpg"));
      System.out.println("Image created");
      //Closing the document
      document.close();
   }
}

使用以下命令从命令提示符编译并执行保存的Java文件。

javac PdfToImage.java 
java PdfToImage

在执行时,上述程序检索给定PDF文档中的图像,显​​示以下消息。

Image created

如果验证给定的路径,则可以观察到生成的图像并保存为myimage.jpg ,如下所示。

Generateimage
↑回到顶部↑
WIKI教程 @2018