本文协助如何使用 Java 将图像插入 PDF。它提供了有关 IDE 配置的详细信息、编写应用程序的分步过程以及用于使用 Java 将图像添加到 PDF 的可运行示例代码。您还将学习不同的选项来自定义以 PNG、JPEG 等任何格式呈现图像的过程,并将图像放置在 PDF 页面上的所需位置。
使用 Java 将图像放入 PDF 的步骤
- 建立使用Aspose.PDF for Java插入图片的环境
- 加载源 PDF 文件,访问第一个 page 以添加图像,并保存图形状态
- 创建图像流并将其添加到加载的 PDF 的图像集合资源中
- 使用图像所需的矩形位置实例化 Matrix 对象
- 定义图像绘制选项,使用Do()方法绘制图像
- 在关闭图像和 PDF 流之前恢复图形状态并保存输出 PDF
这些步骤解释了如何使用 Java 在 PDF 中添加图像,其中首先从加载的 PDF 文件中获取页面引用,然后创建图像流。该图像被添加到所选页面的图像集合中,然后使用目标图像的位置矩形声明转换矩阵。最后,使用 Do() 方法渲染图像,并将生成的 PDF 文件保存在磁盘上。
使用 Java 在 PDF 中添加照片的代码
import com.aspose.pdf.*; | |
import com.aspose.pdf.operators.*; | |
public class AsposeTest { | |
public static void main(String[] args) throws Exception {//Main function to add image to a PDF using Java | |
// Instantiate the license | |
License lic = new License(); | |
lic.setLicense("Aspose.Total.lic"); | |
// Load the source PDF file | |
Document srcDocument = new Document("sample.pdf"); | |
// Get a reference to the target page | |
Page pdfPage = srcDocument.getPages().get_Item(1); | |
// Create stream for the image | |
java.io.FileInputStream streamForImage = new java.io.FileInputStream(new java.io.File("logo.png")); | |
// Add the stream of image to the collection of images in the selected page | |
pdfPage.getResources().getImages().add(streamForImage); | |
// Save the current state of the graphics for later use | |
pdfPage.getContents().add(new GSave()); | |
// Instantiate the Matrix object using the desired rectangular area | |
Rectangle rect = new Rectangle(50, 750, 100, 800); | |
Matrix matrix = new Matrix(new double[] { rect.getURX() - rect.getLLX(), 0, 0, | |
rect.getURY() - rect.getLLY(), rect.getLLX(), rect.getLLY() }); | |
// Define how image must be placed | |
pdfPage.getContents().add(new ConcatenateMatrix(matrix)); | |
XImage pdfXimage = pdfPage.getResources().getImages().get_Item(pdfPage.getResources().getImages().size()); | |
// Draw image using the Do operator | |
pdfPage.getContents().add(new Do(pdfXimage.getName())); | |
// Restore the graphics state | |
pdfPage.getContents().add(new GRestore()); | |
// Save the resultant PDF | |
srcDocument.save("updated_document.pdf"); | |
// Close image stream | |
streamForImage.close(); | |
// Close the PDF | |
srcDocument.close(); | |
System.out.println("Done"); | |
} | |
} |
此代码演示了使用 Java* 将图片添加到 PDF 的过程。它使用Document类加载PDF,Page类对象保存目标PDF页面的引用,FileInputStream对象保存目标图像,rectangle类描述图像在页面上的位置,Matrix对象定义图像的绘制,以及渲染图像的 Do() 方法。请注意,图形状态在开始此操作之前保存,并在操作完成后恢复。
在本文中,我们见证了使用 Java* 将照片添加到 PDF 的过程。如果您想了解在 PDF 中添加水印的过程,请参阅 如何使用Java为PDF添加水印 上的文章。