PDFBox - 添加矩形
本章教您如何在 PDF 文档的页面中创建颜色框。
在 PDF 文档中创建框
您可以使用PDPageContentStream类的addRect()方法 在 PDF 页面中添加矩形框。
以下是在 PDF 文档页面中创建矩形形状的步骤。
第 1 步:加载现有 PDF 文档
使用PDDocument类的静态方法load()加载现有 PDF 文档。此方法接受文件对象作为参数,因为这是一个静态方法,您可以使用类名调用它,如下所示。
File file = new File("path of the document") 
PDDocument document = PDDocument.load(file);
第二步:获取页面对象
您需要使用PDDocument类的getPage()方法检索要在其中添加矩形的所需页面的PDPage对象。对于此方法,您需要传递要添加矩形的页面的索引。
PDPage page = document.getPage(0);
第 3 步:准备内容流
您可以使用名为PDPageContentStream的类的对象插入各种类型的数据元素。您需要将文档对象和页面对象传递给此类的构造函数,因此,通过传递在前面的步骤中创建的这两个对象来实例化此类,如下所示。
PDPageContentStream contentStream = new PDPageContentStream(document, page);
第四步:设置非描边颜色
您可以使用PDPageContentStream类的setNonStrokingColor()方法将非描边颜色设置为矩形。对于此方法,您需要将所需的颜色作为参数传递,如下所示。
contentStream.setNonStrokingColor(Color.DARK_GRAY);
第5步:绘制矩形
使用addRect()方法绘制具有所需尺寸的矩形。对于此方法,您需要传递要添加的矩形的尺寸,如下所示。
contentStream.addRect(200, 650, 100, 100);
第6步:填充矩形
PDPageContentStream类的fill ()方法用所需的颜色填充指定维度之间的路径,如下所示。
contentStream.fill();
第 7 步:关闭文档
最后使用PDDocument类的close()方法关闭文档,如下所示。
document.close();
例子
假设我们在路径C:\PdfBox_Examples\中有一个名为Blankpage.pdf的 PDF 文档,其中包含一个空白页面,如下所示。
此示例演示如何在 PDF 文档中创建/插入矩形。在这里,我们将在空白 PDF 中创建一个框。将此代码保存为AddRectangles.java。
import java.awt.Color;
import java.io.File;
  
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
public class ShowColorBoxes {
   public static void main(String args[]) throws Exception {
      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/BlankPage.pdf");
      PDDocument document = PDDocument.load(file);
        
      //Retrieving a page of the PDF Document
      PDPage page = document.getPage(0);
      //Instantiating the PDPageContentStream class
      PDPageContentStream contentStream = new PDPageContentStream(document, page);
       
      //Setting the non stroking color
      contentStream.setNonStrokingColor(Color.DARK_GRAY);
      //Drawing a rectangle 
      contentStream.addRect(200, 650, 100, 100);
      //Drawing a rectangle
      contentStream.fill();
      System.out.println("rectangle added");
      //Closing the ContentStream object
      contentStream.close();
      //Saving the document
      File file1 = new File("C:/PdfBox_Examples/colorbox.pdf");
      document.save(file1);
      //Closing the document
      document.close();
   }
}
使用以下命令从命令提示符编译并执行保存的 Java 文件。
javac AddRectangles.java java AddRectangles
执行后,上述程序会在 PDF 文档中创建一个矩形,显示以下图像。
Rectangle created
如果您验证给定的路径并打开保存的文档 - colorbox.pdf,您可以观察到其中插入了一个框,如下所示。
