解密pdf-7(为pdf插入页码,页眉,页脚)

首先我们先来认识一个类 com.lowagie.text.HeaderFooter,
使用了改类可以自动计算当前页的页码,并插入页眉或页脚中。
该类有两个构造方法如下:
1.HeaderFooter(Phrase before, boolean flag);
2.HeaderFooter(Phrase before, Phrase after);
使用1中的flag参数是表示是否进行页号的显示,
before和after参数是用于显示在页码前后的说明文字,如 page:1,第 1 页 等。
其中的setAlignment(int alignment)方法是用于设定相应对齐方式,如:居中,居右等。
默认的HeaderFooter会在显示一个带有边框的样式,
当然我们可以进行设置,
可以通过setBorder()方法将其隐藏或只显示某侧边框。
最后需要告诉Document将使用HeaderFooter,可以使用document.setHeader()和document.setFooter()
下面是一个例子:
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

/**
 * 页码
 * 
 */
public class Simple7 {
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws DocumentException,
			IOException {

		Document doc = new Document(PageSize.B5);
		BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
				"UniGB-UCS2-H", false);
		Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.GREEN);

		PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(
				"E:/HelloWorld.pdf"));
		// HeaderFooter footer = new HeaderFooter(new Phrase(" 第", fontChinese),
		// new Phrase(" 页", fontChinese));
		
		HeaderFooter footer = new HeaderFooter(new Phrase("页码:", fontChinese),
				true);
		footer.setBorder(Rectangle.NO_BORDER);
		footer.setAlignment(Element.ALIGN_CENTER);
		doc.setFooter(footer);
		doc.open();
		for (int i = 0; i < 20; i++) {
			doc.add(new Paragraph("Test......."));
			doc.add(new Paragraph("Test......."));
			doc.add(new Paragraph("Test......."));
		}
		doc.close();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值