使用Java创建与操作PDF文档

Pdf文档是办公中常见的一种文档格式,这种文档格式不依赖于系统安装的字体库,从而在多语言办公环境中广泛被使用。Java语言也可动态创建PDF文档,并且itext包提供了一系列用于操作PDF文档的API,从而为我们在实际开发中生成和定制PDF文档提供了一种良好的解决思路。

1.创建PDF文档

    首先,我们需要导入itext.jar和itexasian.jar(亚洲语言包)这两个依赖的包,主要代码如下:

public class PdfC01 {

	/**
	 * @author Helen
	 * @date 2015年7月17日 上午9:35:54 
	 */
	public static void main(String[] args) {
		com.lowagie.text.Document document = new com.lowagie.text.Document();
		try {
			PdfWriter.getInstance(document, new FileOutputStream("C:\\first.pdf"));
			document.open();
			document.add(new Paragraph("PDF Document!"));
			document.add(new Paragraph("Author:yan."));
			document.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}

    以上代码通过Document类来创建一个文档对象,然后使用PdfWriter类的getInstance()方法将这个文档对象与磁盘文件关联。随后,调用Document的open()方法打开文档对象,使用add()方法为创建的Pdf文档中添加内容(该程序中仅仅添加了两个段落),最后需要调用close() 方法来关闭文档对象,完成Pdf文档的创建和内容填充。

2.操作PDF文档属性

    每一个PDF文档在发布时,都会有文档属性,使用Java程序可以操作创建的PDF文档的属性(文档属性通过PDF Reader的"文件>>属性"菜单进行查看)。这些属性主要包括:标题、作者、主题、关键字、创建日期等。

    示例代码如下:

 

public class PdfC02 {

	/**
	 * @date 2015年7月17日 上午10:04:25 
	 */
	public static void main(String[] args) {
		Document document=new Document();
		try {
			PdfWriter.getInstance(document, new FileOutputStream("C:\\002.pdf"));
			document.addTitle("Title Info.");
			document.addSubject("For learning");
			document.addKeywords("iText");
			document.addAuthor("yan");
			document.addCreator("Samgung SDS");
			document.open();
			document.add(new Paragraph("Content."));
			document.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}

     操作PDF文档属性主要是通过Document类的一系列addXXX()方法来完成的,注意:操作属性一定要在文档对象open之前。这些API的统一格式为:public boolean addXXX(String arg);方法调用成功即返回true,否则返回false。

    Tips:1)创建文档时必须保证路径是正确且存在的,否则后续所有的操作都会失败;

          2)在创建PDF文档时,创建日期和修改日期默认会选定文档生成时的系统时间,因此调用addCreationDate()方法时,不需要传参数,会默认选定当前时间。

          3)操作文档属性的所有语句必须在文档对象打开之前,否则无法成功添加;

          4)确保在文档操作完成之后使用close()方法关闭文档对象,从而释放程序的资源占用。

3.文档的其它操作

    1)设置页面大小

    示例代码:

public class Pdf03C {

	/**
	 * @date 2015年7月17日 上午10:52:12 
	 */
	public static void main(String[] args) {
		Document document = new Document();
		try {
			PdfWriter.getInstance(document, new FileOutputStream("C:\\003.pdf"));
			Rectangle pageSize=new Rectangle(200, 100);
			pageSize=pageSize.rotate();
			document.setPageSize(pageSize);
			document.open();
			document.add(new Paragraph("PageSize:200*100"));
			document.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}

    在特定的使用场合中,PDF文档单页显示的尺寸一般是有限制的,通过Rectangle类即可为文档的页面设置尺寸大小。该类的构造方法可以接收两个float实数,用于表示页面所处矩形区域的宽度和高度,单位是磅,在这种情况下参照起点坐标是(0,0)。这个构造方法也可以接收四个实数作为参数,用起始坐标和矩形大小来确定页面的尺寸。

    2)设置页面显示方向
 PDF文档在创建时,默认的显示方向是纵向,即矩形区域参数对应的分别为宽度和高度。通过Rectangle类提供的rotate()方法可以设置页面的显示方向,可以切换纵向为横向;在显示方向为横向的情况下也可调用该方法设置显示方向为纵向。

    3)添加页眉和页脚

    示例代码:

public class Pdf04C {

	/**
	 * @date 2015年7月17日 上午11:19:46 
	 */
	public static void main(String[] args) {
		try {
			PdfReader reader = new PdfReader("C:\\first.pdf");
			PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("C:\\first_pre.pdf"));
			PdfContentByte head = stamp.getOverContent(1);
			head.setTextRise(800);
			head.beginText();
			BaseFont chinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			head.setFontAndSize(chinese, 16);
			head.showText("页眉");
			head.endText();
			stamp.insertPage(2, PageSize.A4);
			PdfContentByte bottom = stamp.getUnderContent(2);
			bottom.setTextRise(20);
			bottom.beginText();
			bottom.setFontAndSize(chinese, 16);
			bottom.showText("页脚");
			bottom.endText();
			stamp.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

    注意:添加页眉和页脚内容时,需要使用PdfReader类来读取一个已创建的PDF文档,使用PdfStamper 类来修改读取的文档完成页眉和页脚添加。主要API:

  • public PdfContentByte getOverContent(int pageNum),获得指定页面的内容。

  • public void setTextRise(float rise),使当前文本位置上移,如果将参数设置为小数,则必须使用标准的单精度表示(如100.5f)

  • 使用beginText()标记文本开始,使用showText(String text)设置页眉页脚的显示内容,使用endText()标记文本结束。

     以上示例代码读取C盘下的first.pdf文档进行编辑,为其添加页眉,并在第二页添加页脚,最终修改完成的文件以first_pre.pdf文件输出。

猜你喜欢

转载自bjtale.iteye.com/blog/2229460