PDFBox之文档创建

1.创建一个空的PDF

下面的小例子表示如何使用PDFBox来创建一个新的PDF文档。

 // 创建一个空的文档
PDDocument document = new PDDocument();

// 创建一个空的Page然后添加到文档中
PDPage blankPage = new PDPage();
document.addPage( blankPage );

// 保存文档
document.save("BlankPage.pdf");

// 一定要确保最后文档是别关闭的
document.close();

1.1举例说明

	public static void createPDFFile() {
		
		PDDocument document = null;
		PDPage blankPage = null;

		try {
			document = new PDDocument();
			blankPage = new PDPage();
			
			document.addPage(blankPage);
			document.save("D:" + File.separator + "pdfBox.pdf");
			
		} catch (COSVisitorException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				document.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

2.使用PDF字体的Hello World

// 创建一个文档并且添加一个Page
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage( page );

// 创建一个FONTT
PDFont font = PDType1Font.HELVETICA_BOLD;

// 创建一个待加入的文档流
PDPageContentStream contentStream = new PDPageContentStream(document, page);

// 使用选择的字体定义一个文本内容
contentStream.beginText();
contentStream.setFont( font, 12 );
contentStream.moveTextPositionByAmount( 100, 700 );
contentStream.drawString( "Hello World" );
contentStream.endText();

// 关闭内容流
contentStream.close();

// 保存结果并且关闭文档对象
document.save( "Hello World.pdf");
document.close();

2.1举例说明

	public static void usePdfFont() {

		PDDocument document = new PDDocument();
		PDPage page = new PDPage();
		PDPageContentStream contentStream = null;
	

		PDFont font = PDType1Font.HELVETICA_BOLD;

		try {
			document.addPage(page);
			contentStream = new PDPageContentStream(document, page);
			contentStream.beginText();
			contentStream.setFont(font, 12);
			contentStream.moveTextPositionByAmount(100, 700);
			contentStream.drawString("Hello World");
			contentStream.endText();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				contentStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			document.save("D:" + File.separator + "Hello World.pdf");
		} catch (COSVisitorException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				document.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
posted on 2015-08-03 22:40  叼烟斗的纤夫  阅读(624)  评论(0编辑  收藏  举报