itext基本用法

用itext创建pdf,成为多数企业报表工具的一个首选;

看了itext官方文档,简单的写下笔记:

 

利用itext生成pdf的步骤:

                                 1:给定一个地址!

                                 2:实例化document对象!

                                 3:取得PdfWriter实例!

                                 4:打开document对象!

                                 5:往document里添加内容!

                                 6:关闭document!

通过以上的简单步骤就可以生成一个pdf!

例如代码:

package com.keith.test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
	private static final String URL = "/home/core/Desktop/itext_test/hellowold.pdf";

	public static void main(String[] args) {

		// step 1
		Document document = new Document();
		try {
			// step 2
			PdfWriter.getInstance(document, new FileOutputStream(URL));
			// step 3
			document.open();
			// step 4
			document.add(new Paragraph("hello wold"));
			// step 5
			document.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}
}

 来看下如何设置pdf的相关属性:

 

设置宽度(参考附件里的ItextNarrow.java):

Rectangle pageSize = new Rectangle(216f,720f);

设置pdf的格式为信纸类型这里是(参考附件里的ItextLetter.java):

Document document = new Document(PageSize.LETTER.rotate());

 设置odf的页面宽度(参考附件里的ItextLandspace.java):

Document document = new Document(new Rectangle(792,612));

 设置顶部和底部的边线(参考附件里的IItextMirroredMarginsTop.java):

 document.setMarginMirroringTopBottom(true);

 延迟向pdf添加内容(参考附件里的ItextMemory.java):

	FileOutputStream fos = new FileOutputStream(URL);

 设置odf的格式版本(参考附件里的ItextVersion.java):

writer.setPdfVersion(PdfWriter.VERSION_1_7);

 生成zip文件并包含pdf:

 ZipOutputStream zip =  new ZipOutputStream(new FileOutputStream(URL));
 
ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");

 附件里共享完整的代码!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值