1. 程式人生 > 其它 >Java itext5預覽PDF設定頁首頁尾

Java itext5預覽PDF設定頁首頁尾

如果是maven專案需要新增依賴,普通專案在官網(http://itextpdf.com/)下載對應的jar包加入即可。依賴如下:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>

  

預覽:

public void review(HttpServletResponse response) throws Exception {
	//預覽
	response.setHeader("content-Type", "application/pdf");
	response.setCharacterEncoding("utf-8");
	response.setHeader("Content-Disposition", "inline;filename=text.pdf");

	//新建Document物件並設定紙張大小和邊距(左,右, 上,下)
	Document document = new Document(PageSize.A4, 10, 20, 30, 40);

	//PDF屬性(可寫可不寫)
	document.addAuthor("author");//作者
	document.addTitle("title");//標題
	document.addSubject("subject");//主題
	document.addKeywords("keywords");//關鍵字
	try {
		//建立書寫器(Writer)與document物件關聯,以位元組流輸出
		//建立 PdfWriter物件 第一個引數是對文件物件的引用,第二個引數是檔案的實際名稱,在該名稱中還會給出其輸出路徑。
		PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
		writer.setPageEvent(new MyHeaderFooter());// 頁首頁尾(需要時設定)
		//開啟document
		document.open();
		//新增內容
		setpdf(document, writer);
		//關閉Document物件和書寫器(Writer)
		if(document != null){
			document.close();
			writer.close();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}

  

內容設定:

/**
 * 具體內容設定
 */
public Document setpdf(Document document, PdfWriter writer) throws Exception {
	float hlead = 28;
	Font font1 = new Font(BaseFont.createFont( "/zhttfs/2.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED), 22);//小標宋2號

	float pleft = 45;
	float pright = 35;

	Paragraph p1 = new Paragraph("我是標題", font1);
	p1.setLeading(32);//行間距
	p1.setAlignment(Element.ALIGN_CENTER);//居中
	p1.setIndentationLeft(pleft);
	p1.setIndentationRight(pright);
	document.add(p1);

	document.newPage();

	Paragraph p2 = new Paragraph("我是標題", font1);
	p2.setLeading(32);//行間距
	p2.setAlignment(Element.ALIGN_CENTER);//居中
	p2.setIndentationLeft(pleft);
	p2.setIndentationRight(pright);
	document.add(p2);

	return document;
}

  

頁首頁尾:

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.IOException;

public class MyHeaderFooter extends PdfPageEventHelper {
	//總頁數
	PdfTemplate totalPage;
	//字型
	Font hfFont;
	{
		try {
			hfFont = new Font(BaseFont.createFont( "/zhttfs/1.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED), 14);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//開啟文件時,建立一個總頁數的模版
	public void onOpenDocument(PdfWriter writer, Document document) {
		PdfContentByte cb = writer.getDirectContent();
		totalPage = cb.createTemplate(50, 14);//共 頁的寬高
	}
	//一頁載入完成觸發,寫入頁首和頁尾
	public void onEndPage(PdfWriter writer, Document document) {
		//建立一個兩列的表格
		PdfPTable table = new PdfPTable(2);
		try {
			table.setTotalWidth(PageSize.A4.getWidth());//總寬度為A4紙張寬度
			table.setLockedWidth(true);//鎖定列寬
			table.setWidths(new int[]{50, 50});//設定每列寬度
			PdfPCell cell = new PdfPCell(new Phrase("第"+ document.getPageNumber() +"頁/", hfFont));
			cell.setHorizontalAlignment(Element.ALIGN_RIGHT);//設定水平右對齊
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//設定垂直居中
			cell.disableBorderSide(15);//隱藏全部邊框
			table.addCell(cell);
			PdfPCell cell1 = new PdfPCell(Image.getInstance(totalPage));//共 頁
			cell1.setHorizontalAlignment(Element.ALIGN_LEFT);//設定水平左對齊
			cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);//設定垂直居中
			cell1.disableBorderSide(15);//隱藏全部邊框
			table.addCell(cell1);
			table.writeSelectedRows(0, -1, 0, 50, writer.getDirectContent());
		} catch (Exception e) {
			throw new ExceptionConverter(e);
		}

		//生成左側頁首
		ColumnText.showTextAligned(writer.getDirectContent(),
			Element.ALIGN_LEFT, new Paragraph("左頁首", hfFont),
			document.left(), PageSize.A4.getHeight() -30, 0);

		//生成右側頁首
		ColumnText.showTextAligned(writer.getDirectContent(),
			Element.ALIGN_RIGHT, new Paragraph("右頁首", hfFont),
			document.right(), PageSize.A4.getHeight() - 30, 0);
	}

	// 全部完成後,將總頁數的pdf模版寫到指定位置
	public void onCloseDocument(PdfWriter writer,Document document) {
		String text = "共" + (writer.getPageNumber()) + "頁";
		ColumnText.showTextAligned(totalPage, Element.ALIGN_MIDDLE, new Paragraph(text, hfFont), 0, 0, 0);
	}

}