PDFBox添加矩形

本章将演示如何在PDF文档的页面中创建颜色框。

在PDF文档中创建框

使用PDPageContentStream类的addRect()方法在PDF页面中添加矩形框。

以下是在PDF文档的页面中创建矩形形状的步骤。

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

第2步:获取页面对象
需要使用PDDocument类的getPage()方法检索要添加矩形的所需页面的PDPage对象。 对于此方法,传递要添加矩形的页面的索引。

PDPage page = document.getPage(0);

第3步:准备内容流

使用PDPageContentStream类的对象来插入各种数据元素。 因此,需要将文档对象和页面对象传递给此类的构造函数,通过传递在前面的步骤中创建的这两个对象来实例化此类,如下所示。

PDPageContentStream contentStream = new PDPageContentStream(document, page);

第4步:设置不划线颜色

使用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();

 示例

假设在目录:F:\worksp\pdfbox 中有一个名称为:blank-doc.pdf 的PDF文档,它包含一个空白页面,如下所示。

这个例子演示了如何在PDF文档中创建/插入矩形。 在这里,将在空白PDF中创建一个框。 将此代码保存为AddRectangles.java

package com.zyiz;

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("F:/worksp/pdfbox/bank_doc.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("F:/worksp/pdfbox/colorbox.pdf");
      document.save(file1);

      //Closing the document
      document.close();
   }
}

执行上面示例代码,得到以下结果 -

Rectangle created

打开生成的文件:colorbox.pdf ,显示如下 -


上一篇:PDFBox提取图像

下一篇:没有了

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程