1. 程式人生 > 實用技巧 >iText實現Java生成PDF檔案

iText實現Java生成PDF檔案

pom.xml檔案

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf.tool</groupId>
			<artifactId>xmlworker</artifactId>
			<version>5.5.11</version>
		</dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
		</dependency>

PDFUtil.java

package cn.zj.pdf;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;

public class PdfUtil1 {

	private static String FILE_DIR = "F:\\java\\";

	private static List<List<String>> dataDocumentModificationRecord() {
		List<List<String>> dataList = new ArrayList<List<String>>();
		
		List<String> data = new ArrayList<String>();
		data.add("2020-12-17");
		data.add("7.0.0");
		data.add("新增文件");
		data.add("XXX");
		dataList.add(data);
		
		return dataList;
	}
	
	/**
	 * 下載PDF
	 */
	public static void downPdf(String down2localFileName) {
		//Step 1—Create a Document.
		//1.新建document物件
		Document document = createDocument();
		try {
			//Step 2—Get a PdfWriter instance.
			//2.建立一個書寫器(Writer)與document物件關聯
			//PdfWriter.getInstance(document, new FileOutputStream(down2localFileName));
			
			PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(down2localFileName));
			writer.setPageEvent(new MyHeaderFooter1());// 頁首/頁尾
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		//Step 3—Open the Document.
		//3.開啟文件
		document.open();
		setDocumentAttr(document);//設定文件屬性,可以不新增
		//Step 4—Add content.
		//4.向文件中新增內容
		try {
			//document.add();
			documentAddContent(document);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		//Step 5—Close the Document.
		//5.關閉文件
		document.close();
		
	}

	/**
	 * pdf內容新增
	 * @param document 
	 * @throws DocumentException 
	 */
	public static void documentAddContent(Document document) throws DocumentException {
		//封面
		addCover(document);
		
		//公共報文
		addPublicDocument(document);
		
		//選擇的報文
		addSelectedDocument(document);
		
		String content= "一葉落便知秋意濃,即使江南的綠色褪色之期晚了幾許,南飛的大雁也會在天空一會兒排成一字,一會兒排成人字,秋天真的來了,中秋真的來了,國慶真的來了。";
		//Chunk:塊(Chunk)是能被新增到文件的文字的最小單位。
		//Phrase:短句(Phrase)是一系列以特定間距(兩行之間的距離)作為引數的塊。
		//Paragraph:段落是一系列塊和(或)短句。同短句一樣,段落有確定的間距。
		//使用者還可以指定縮排;在邊和(或)右邊保留一定空白,段落可以左對齊、右對齊和居中對齊。新增到文件中的每一個段落將自動另起一行。
		Paragraph paragraph = new Paragraph(content, chineseFont(24,0));
		document.add(paragraph);
	}

	/**
	 * 新增封面
	 * @param document
	 * @throws DocumentException
	 */
	public static void addCover(Document document) throws DocumentException {
		//新增logo
		addLogo(document);
		
		//新增titleCover
		addTitleCover(document);
		
		//新增橫條線
		addLineCover(document);
		
		addEnter(document, 3);
		//新增副標題
		addSubHead(document);
		
		addEnter(document, 20);
		
		//出版社
		addPublishHouse(document);
		
		document.newPage();//跳轉下一頁
		
		addEnter(document, 7);
		//文件管理資訊
		addDocumentManagementInfo(document);
		
		addEnter(document, 1);
		//文件修改記錄
		addDocumentModificationRecord(document);
	}

	/**
	 * 公共報文
	 * @param document
	 * @throws DocumentException 
	 */
	private static void addPublicDocument(Document document) throws DocumentException {
		document.newPage();
		//前言
		addIntroductionDocument(document);
		
	}

	/**
	 * 選擇的報文
	 * @param document
	 */
	private static void addSelectedDocument(Document document) {
		
	}

	/**
	 * 新增Logo
	 * @param document
	 * @throws DocumentException
	 */
	public static void addLogo(Document document) throws DocumentException {
		
		String resourcePath = getResourcePath();
		String logoPath = resourcePath + "static/img/timg.JPG";
		Image logo = setImageBorder(logoPath);
		
		Paragraph paragraph =new Paragraph();
		paragraph.add(logo); 
		
		document.add(logo);
	}

	/**
	 * 新增封面標題
	 * @param document
	 * @throws DocumentException 
	 */
	public static void addTitleCover(Document document) throws DocumentException {
		
		String titleCoverContent = "現金管理銀企互聯綜合服務系統";
		
		Paragraph paragraph=new Paragraph(titleCoverContent,chineseFont(24, Font.BOLD));//設定字型樣式
		paragraph.setAlignment(Element.ALIGN_RIGHT);//設定文字靠右
		paragraph.setSpacingBefore(5f); //設定段落上空白
		paragraph.setSpacingAfter(10f); //設定段落下空白
		
		document.add(paragraph);
	}

	/**
	 * 新增橫線
	 * @param document
	 * @throws DocumentException
	 */
	public static void addLineCover(Document document) throws DocumentException {
		//引數
		//1.線寬度
		//2.直線長度,是個百分百,0-100之間
		//3.直線顏色
		//4.直線位置
		//5.上下移動位置
		LineSeparator line = new LineSeparator(28f,100,BaseColor.RED,Element.ALIGN_CENTER,-15f);
		
		Paragraph paragraph =new Paragraph();
		paragraph.add(new Chunk(line));
		
		document.add(line);
	}

	/**
	 * 副標題
	 * @param document
	 * @throws DocumentException
	 */
	private static void addSubHead(Document document) throws DocumentException {
		String subHead = "ERP介面開發手冊";
		
		Chunk sigUnderline = new Chunk(subHead);//塊
		sigUnderline.setUnderline(3f, -2f);//厚度,相對y方向位置
		sigUnderline.setFont(chineseFont(24, Font.BOLD|Font.UNDERLINE));
		
		Paragraph paragraph=new Paragraph();
		paragraph.setAlignment(Element.ALIGN_RIGHT);//設定文字靠右
		paragraph.setSpacingBefore(5f); //設定段落上空白
		paragraph.setSpacingAfter(10f); //設定段落下空白
		paragraph.add(sigUnderline);
		
		document.add(paragraph);
	}

	/**
	 * 出版社
	 * @param document
	 * @throws DocumentException
	 */
	private static void addPublishHouse(Document document) throws DocumentException {
		String content1 = "中國XX出版社";
		String content2 = "軟體開發中心";
		
		Phrase phrase1 = new Phrase();//短句
		phrase1.setFont(chineseFont(16, Font.BOLD));
		phrase1.add(content1);
		
		Phrase phrase2 = new Phrase();
		phrase2.setFont(chineseFont(12, Font.NORMAL));
		phrase2.add(content2);
		
		Paragraph paragraph=new Paragraph();
		paragraph.setAlignment(Element.ALIGN_CENTER);
		paragraph.add(phrase1);
		paragraph.add(phrase2);
		
		document.add(paragraph);
	}

	/**
	 * 文件管理資訊
	 * @param document
	 * @throws DocumentException
	 */
	private static void addDocumentManagementInfo(Document document) throws DocumentException {
		String content = "文件管理資訊";
		Chunk chunk=new Chunk(content);
		chunk.setFont(chineseFont(wordSize2Pound("五號"), Font.NORMAL));
		
		//A4紙尺寸為592.52*839.16磅
		float contentSize = wordSize2Pound("五號");
		float left = (592.52f/2f) - 36f - content.length()/2f * contentSize;
		float right = (592.52f/2f) - 36f - content.length()/2f * contentSize;
		chunk.setBackground(BaseColor.RED, left, 10f, right, 0f);//左下右上
		
		Paragraph paragraph=new Paragraph();
		paragraph.add(chunk);
		paragraph.setAlignment(Element.ALIGN_CENTER);
		document.add(paragraph);
		
		//編號
		String c1 = "編號";
		Paragraph p1=new Paragraph(c1, chineseFont(12, Font.NORMAL));
		p1.setSpacingBefore(5f); //設定段落上空白
		p1.setSpacingAfter(10f); //設定段落下空白
		document.add(p1);
		//類別	介面文件
		String c2 = "類別    介面文件";
		Paragraph p2=new Paragraph(c2, chineseFont(12, Font.NORMAL));
		p2.setSpacingBefore(5f); //設定段落上空白
		p2.setSpacingAfter(10f); //設定段落下空白
		document.add(p2);
		//密級	公開
		String c3 = "密級    公開";
		Paragraph p3=new Paragraph(c3, chineseFont(12, Font.NORMAL));
		p3.setSpacingBefore(5f); //設定段落上空白
		p3.setSpacingAfter(10f); //設定段落下空白
		document.add(p3);
	}

	/**
	 * 文件修改記錄
	 * @param document
	 * @throws DocumentException 
	 */
	private static void addDocumentModificationRecord(Document document) throws DocumentException {
		String content = "文件修改記錄";
		Chunk chunk=new Chunk(content);
		chunk.setFont(chineseFont(wordSize2Pound("五號"), Font.NORMAL));
		
		//A4紙尺寸為592.52*839.16磅
		float contentSize = wordSize2Pound("五號");
		float left = (592.52f/2f) - 36f - content.length()/2f * contentSize;
		float right = (592.52f/2f) - 36f - content.length()/2f * contentSize;
		chunk.setBackground(BaseColor.RED, left, 10f, right, 0f);//左下右上
		
		Paragraph paragraph=new Paragraph();
		paragraph.add(chunk);
		paragraph.setAlignment(Element.ALIGN_CENTER);
		document.add(paragraph);
		
		addEnter(document, 1);
		
		//記錄表格
		//PdfPTable table = createTable(4, Element.ALIGN_LEFT);
		PdfPTable table = createTable(new float[] {100f,60f,260f,100f});
		
		//tr th
		Font font_th = chineseFont(14, Font.BOLD);
		BaseColor backgroundColor_th = BaseColor.GRAY;
		String th1 = "日期";
		PdfPCell cell_th1 = createCell(th1, font_th);
		cell_th1.setBackgroundColor(backgroundColor_th);
		table.addCell(cell_th1);
		String th2 = "版本";
		PdfPCell cell_th2 = createCell(th2, font_th);
		cell_th2.setBackgroundColor(backgroundColor_th);
		table.addCell(cell_th2);
		String th3 = "描述資訊";
		PdfPCell cell_th3 = createCell(th3, font_th);
		cell_th3.setBackgroundColor(backgroundColor_th);
		table.addCell(cell_th3);
		String th4 = "作者";
		PdfPCell cell_th4 = createCell(th4, font_th);
		cell_th4.setBackgroundColor(backgroundColor_th);
		table.addCell(cell_th4);
		
		//tr td
		Font font_td = chineseFont(14, Font.NORMAL);
		BaseColor backgroundColor_td = BaseColor.WHITE;
		
		List<List<String>> dataList = dataDocumentModificationRecord();
		
		for (int i = 0; i < 6; i++) {
			String td1 = " ";
			String td2 = " ";
			String td3 = " ";
			String td4 = " ";
			if(null != dataList && dataList.size() > i) {
				List<String> data = dataList.get(i);
				td1 = data.get(0);
				td2 = data.get(1);
				td3 = data.get(2);
				td4 = data.get(3);
			}
			//每行資料
			PdfPCell cell_td1 = createCell(td1, font_td);
			cell_td1.setBackgroundColor(backgroundColor_td);
			table.addCell(cell_td1);
			
			PdfPCell cell_td2 = createCell(td2, font_td);
			cell_td2.setBackgroundColor(backgroundColor_td);
			table.addCell(cell_td2);
			
			PdfPCell cell_td3 = createCell(td3, font_td);
			cell_td3.setBackgroundColor(backgroundColor_td);
			table.addCell(cell_td3);
			
			PdfPCell cell_td4 = createCell(td4, font_td);
			cell_td4.setBackgroundColor(backgroundColor_td);
			table.addCell(cell_td4);
		}
		
		table.setSplitLate(false);
		table.setSplitRows(false);//這個是設定表格的行是否跨頁顯示,預設true 跨頁顯示
		
		document.add(table);
	}
	
	/**
	 * 前言
	 * @param document
	 * @throws DocumentException 
	 */
	private static void addIntroductionDocument(Document document) throws DocumentException {
		//一級標題
		addIntroductionDocument_title1(document);
		
		//一級標題下內容
		addIntroductionDocument_title1_nextLevel(document);
		
		// TODO 新增跨行表格
		addTable(document);
	}

	/**
	 * 前言一級標題
	 * @param document
	 * @throws DocumentException 
	 */
	private static void addIntroductionDocument_title1(Document document) throws DocumentException {
		
		//前言開始磅數
		//1 前言
		String content_title1 = "1 前言";
		Paragraph title1 = new Paragraph(content_title1, chineseFont(26, Font.BOLD));
		document.add(title1);
		
		String content_content1 = "";
		if(null != content_content1 && !"".equals(content_content1)) {
			
			Paragraph content1 = new Paragraph(content_title1, chineseFont(26, Font.BOLD));
			document.add(content1);
		}
	}

	/**
	 * 一級標題下內容
	 * @param document
	 * @throws DocumentException 
	 */
	private static void addIntroductionDocument_title1_nextLevel(Document document) throws DocumentException {
		for (int i = 0; i < 9; i++) {
			
			//1.1 編寫目的
			String title_1_1 = "1." + (i+1) + " 編寫目的";
			Paragraph p_title_1_1 = new Paragraph(title_1_1, chineseFont(22, Font.BOLD));
			document.add(p_title_1_1);
			
			//1.1內容
			String content_1_1= "一葉落便知秋意濃,即使江南的綠色褪色之期晚了幾許,南飛的大雁也會在天空一會兒排成一字,一會兒排成人字,秋天真的來了,中秋真的來了,國慶真的來了。";
			Paragraph p_content_1_1 = new Paragraph(content_1_1, chineseFont(12, Font.NORMAL));
			p_content_1_1.setFirstLineIndent(24);//首行縮排
			document.add(p_content_1_1);
		}
		
	}

	/**
	 * 新增跨行表格
	 * @param document
	 * @throws DocumentException 
	 */
	private static void addTable(Document document) throws DocumentException {
		PdfPTable table = createTable(new float[] {100f, 100f, 100f, 100f});
		
		Font font_th = chineseFont(14, Font.BOLD);
		BaseColor backgroundColor_th = BaseColor.GRAY;
		String th1 = "日期";
		PdfPCell cell_th1 = createCell(th1, font_th);
		cell_th1.setBackgroundColor(backgroundColor_th);
		table.addCell(cell_th1);
		String th2 = "版本";
		PdfPCell cell_th2 = createCell(th2, font_th);
		cell_th2.setBackgroundColor(backgroundColor_th);
		table.addCell(cell_th2);
		String th3 = "描述資訊";
		PdfPCell cell_th3 = createCell(th3, font_th);
		cell_th3.setBackgroundColor(backgroundColor_th);
		table.addCell(cell_th3);
		String th4 = "作者";
		PdfPCell cell_th4 = createCell(th4, font_th);
		cell_th4.setBackgroundColor(backgroundColor_th);
		table.addCell(cell_th4);
		
		
		Font font_td = chineseFont(14, Font.NORMAL);
		
		for (int i = 0; i < 2; i++) {
			String td1 = "td1資料顯示";
			PdfPCell cell_td1 = createCell(td1, font_td);
			table.addCell(cell_td1);
			String td2 = "td2資料顯示";
			PdfPCell cell_td2 = createCell(td2, font_td);
			table.addCell(cell_td2);
			String td3 = "td3資料顯示";
			PdfPCell cell_td3 = createCell(td3, font_td);
			table.addCell(cell_td3);
			String td4 = "td4資料顯示";
			PdfPCell cell_td4 = createCell(td4, font_td);
			table.addCell(cell_td4);
		}
		
		String td5 = "td5資料顯示";
		PdfPCell cell_td5 = createCell(td5, font_td);
		cell_td5.setRowspan(25);//合併行
		cell_td5.setColspan(2);
		table.addCell(cell_td5);
		
//		String td6 = "td6資料顯示";
//		PdfPCell cell_td6 = createCell(td6, font_td);
//		table.addCell(cell_td6);
		String td7 = "td7資料顯示td7資料顯示td7資料顯示td7資料顯示";
		PdfPCell cell_td7 = createCell(td7, font_td);
		table.addCell(cell_td7);
		String td8 = "td8資料顯示";
		PdfPCell cell_td8 = createCell(td8, font_td);
		table.addCell(cell_td8);
		
		for (int i = 0; i < 24; i++) {			
//			PdfPCell cell_td6_1 = createCell(td6, font_td);
//			table.addCell(cell_td6_1);
			PdfPCell cell_td7_1 = createCell(td7, font_td);
			table.addCell(cell_td7_1);
			PdfPCell cell_td8_1 = createCell(td8, font_td);
			table.addCell(cell_td8_1);
		}
		
		/*
		 * 如果出現某些行中的文字非常大, 那麼iText將按照“行優先”的方式對錶格進行分頁處理, 所謂“行優先”是說:當遇到無法在當前頁顯示完整的一行時,
		 * 該行將被放到下一頁進行顯示,而只有當一整業都無法顯示完此行時, iText才會將此行拆開顯示在兩頁中。如果不想使用“行優先”的方式,
		 * 而是想採用“頁優先”方式(保證填滿當前頁面的前提下,決定是否需要分拆行)顯示, 可使用方法setSplitLate(false)
		 */
		//若為true時,當前頁顯示完整的一行時該行將被放到下一頁進行顯示,若此時跨行過大超出一頁範圍則報java.lang.NullPointerException
		table.setSplitLate(false);
		table.setSplitRows(true);//跨頁顯示
		document.add(table);
		
		
		
	}

	/**
	 * 獲取專案資源路徑 resource/
	 * @return
	 */
	public static String getResourcePath() {
		String resourcePath = PdfUtil1.class.getClass().getResource("/").getPath();
		return resourcePath;
	}

	/**
	 * 設定文件屬性
	 * @param document
	 */
	public static void setDocumentAttr(Document document) {
//		document.addTitle("Title@PDF-Java");// 標題
//		document.addAuthor("Author@zj");// 作者
//		document.addSubject("Subject@iText pdf sample");// 主題
//		document.addKeywords("Keywords@iTextpdf");// 關鍵字
//		document.addCreator("Creator@zj");// 建立者

	}

	/**
	 * 自定義頁面引數
	 * @return
	 */
	public static Document createDocument() {
		//頁面大小  每邊36磅頁邊距
		Rectangle rect = new Rectangle(PageSize.A4);
		//頁面背景色
		rect.setBackgroundColor(BaseColor.WHITE);
		// 設定邊框顏色
		rect.setBorderColor(BaseColor.RED);
		rect.setBorder(Rectangle.BOX);//設定邊框
		rect.setBorderWidth(10);//邊框寬度
		
		//Document document =new Document(); // 預設頁面大小是A4
		//Document document =new Document(PageSize.A4); // 指定頁面大小為A4
		//Document document =new Document(PageSize.A4,50,50,30,20); // 指定頁面大小為A4,且自定義頁邊距(marginLeft、marginRight、marginTop、marginBottom)
		//其中頁面大小PageSize也可自定義大小,例:
		Document document = new Document(rect);
		
		return document;
	}

	/**
	 * 新增換行
	 * @param document
	 * @param num	幾次換行,預設不換行
	 * @throws DocumentException
	 */
	public static void addEnter(Document document, int num) throws DocumentException {
		if(0 == num) {
			return;
		}
		for (int i = 0; i < num; i++) {
			String content = "\r";
			Paragraph paragraph = new Paragraph(content);
			
			document.add(paragraph);
		}
	}
	
	/**
	 * 字型設定
	 * 中文亂碼
	 * @param size	字型大小
	 * @param style	字型樣式,多個樣式用"|"分隔
	 * @return
	 */
	public static Font chineseFont(float size, int style) {
		if(0 == size) {
			//預設字型
			size = Font.DEFAULTSIZE;
		}
		if(0 == style) {
			//預設無樣式
			style = Font.NORMAL;
		}
		
		BaseFont bfChinese = null;
		try {
			//STSongStd-Light 是字型,在jar 中以property為字尾
			//UniGB-UCS2-H 是編碼,在jar 中以cmap為字尾
			//H 代表文字版式是橫版,相應的 V 代表豎版
			bfChinese=BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
			//bfChinese=BaseFont.createFont("C:/Windows/Fonts/msyh.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}//jar包
		
		//引數一:新建好的字型;引數二:字型大小,引數三:字型樣式,多個樣式用"|"分隔
		Font fontChinese = new Font(bfChinese, size, style);
		return fontChinese;
	}
	
	/**
	 * 中文字號和磅的換算
	 * @param wordSize
	 * @return
	 */
	public static float wordSize2Pound(String wordSize) {
		if(null == wordSize || "".equals(wordSize.trim())) {
			return 0f;
		}
		float pound = 0f;
		
		String[] wordSizes	= {
				"初號",	"小初", "一號", "小一",
				"二號", "小二", "三號", "小三",
				"四號", "小四", "五號", "小五",
				"六號", "小六", "七號", "八號"};
		float[] pounds = {
				42f,36f, 26f, 24f,
				22f, 18f, 16f, 15f,
				14f, 12f, 10.5f, 9f,
				7.5f, 6.5f, 5.5f, 5f};
		
		for (int i = 0; i < wordSizes.length; i++) {
			if(wordSizes[i].equals(wordSize.trim())) {
				pound = pounds[i];
			}
		}
		return pound;
	}
	
	/**
	 * 設定圖片
	 * @param imgPath
	 * @return
	 */
	public static Image setImage(String imgPath) {
		Image image = null;
		try {
			image = Image.getInstance(imgPath);
		} catch (BadElementException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		image.setAlignment(Image.LEFT);
		image.scalePercent(40);//依照比例縮放
		
		return image;
	}
	
	/**
	 * 
	 * @param imgPath
	 * @param borderWidth
	 * @param borderColor
	 * @param rotationDegrees
	 * @return
	 */
//	public static Image setBorderImage(String imgPath, int borderWidth, BaseColor borderColor, float rotationDegrees) {
	public static Image setImageBorder(String imgPath) {
		Image image = setImage(imgPath);
		
		//設定圖片邊框
		//UNDEFINED = -1
		//TOP = 1
		//BOTTOM = 2
		//LEFT = 4
		//RIGHT = 8
		//NO_BORDER = 0
		//BOX = TOP + BOTTOM + LEFT + RIGHT
		image.setBorder(Image.BOX);
		image.setBorderWidth(10);//向內加寬
		image.setBorderColor(BaseColor.RED);//邊框背景顏色
		image.setRotationDegrees(0);//旋轉 正值為逆時針
		
		return image;
	}
	
//	public static void set(Paragraph paragraph) {
//		paragraph.setAlignment(1);//設定文字居中 0靠左   1,居中     2,靠右
//		paragraph.setIndentationLeft(12);// 左縮排  
//		paragraph.setIndentationRight(12);// 右縮排  
//		paragraph.setFirstLineIndent(24);// 首行縮排 
//		paragraph.setLeading(20f); //行間距
//		paragraph.setSpacingBefore(5f); //設定段落上空白
//		paragraph.setSpacingAfter(10f); //設定段落下空白
//	}
	
	/**
	 * 建立表格
	 * @param numColumns
	 * @param horizontalAlignment
	 * @return
	 */
	public static PdfPTable createTable(int numColumns, int horizontalAlignment) {
		PdfPTable table = new PdfPTable(numColumns);
		table.setTotalWidth(592.52f);
		table.setLockedWidth(true);
		table.setHorizontalAlignment(horizontalAlignment);//水平對齊
		table.getDefaultCell().setBorder(Rectangle.BOX);
		
//		table.setSpacingBefore(20);//設定段落上空白
//		table.setSpacingAfter(20);//設定段落上下空白
//		table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
//		table.setWidths(cellswidth);//設定表格的寬
//		table.setTotalWidth(1000f);//設定表格的總寬度
//		table.setWidthPercentage(100);//設定表格寬度的百分比

		return table;
	}
	
	/**
	 * 建立表格
	 * @param widths
	 * @param horizontalAlignment
	 * @return
	 */
	public static PdfPTable createTable(float[] widths) {
		PdfPTable table = new PdfPTable(widths);
		try {
			table.setTotalWidth(widths);
			table.setLockedWidth(true);
			//table.setHorizontalAlignment(horizontalAlignment);//水平對齊
			table.getDefaultCell().setBorder(Rectangle.BOX);
			
//			table.setSpacingBefore(20);//設定段落上空白
//			table.setSpacingAfter(20);//設定段落上下空白
//			table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
//			table.setWidths(cellswidth);//設定表格的寬
//			table.setTotalWidth(1000f);//設定表格的總寬度
//			table.setWidthPercentage(100);//設定表格寬度的百分比
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return table;
	}
	
	/**
	 * 建立單元格(指定字型)
	 * 預設水平左對齊,垂直居中
	 * @param content	單元格內容
	 * @param font		字型
	 * @return
	 */
	public static PdfPCell createCell(String content, Font font) {
		PdfPCell cell = new PdfPCell();
		
//		ALIGN_LEFT = 0;
//		ALIGN_CENTER = 1;
//		ALIGN_RIGHT = 2;
		cell.setHorizontalAlignment(Element.ALIGN_LEFT);//水平對齊方式
//		ALIGN_TOP = 4
//		ALIGN_MIDDLE = 5
//		ALIGN_BOTTOM = 6
//		ALIGN_BASELINE = 7
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直對齊方式
		
		Phrase phrase = new Phrase(content, font);
		cell.setPhrase(phrase);//填充資料
		
		return cell;
	}
	
	/**
	 * 建立單元格(指定字型、水平對齊方式)
	 * 垂直居中
	 * @param content	單元格內容
	 * @param font		字型
	 * @param horizontalAlignment	水平對齊方式
	 * @return
	 */
	public static PdfPCell createCell(String content, Font font, int horizontalAlignment) {
		PdfPCell cell = new PdfPCell();
		
//		ALIGN_LEFT = 0;
//		ALIGN_CENTER = 1;
//		ALIGN_RIGHT = 2;
		cell.setHorizontalAlignment(horizontalAlignment);//水平對齊方式
//		ALIGN_TOP = 4
//		ALIGN_MIDDLE = 5
//		ALIGN_BOTTOM = 6
//		ALIGN_BASELINE = 7
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直對齊方式
		
		Phrase phrase = new Phrase(content, font);
		cell.setPhrase(phrase);//填充資料
		
		return cell;
	}
	/**
	 * 建立單元格(指定字型、水平對齊方式、垂直對齊方式)
	 * @param content	單元格內容
	 * @param font		字型
	 * @param horizontalAlignment	水平對齊方式
	 * @param verticalAlignment		垂直對齊方式
	 * @return
	 */
	public static PdfPCell createCell(String content, Font font, int horizontalAlignment, int verticalAlignment) {
		PdfPCell cell = new PdfPCell();
		
//		ALIGN_LEFT = 0;
//		ALIGN_CENTER = 1;
//		ALIGN_RIGHT = 2;
		cell.setHorizontalAlignment(horizontalAlignment);//水平對齊方式
		
//		ALIGN_TOP = 4
//		ALIGN_MIDDLE = 5
//		ALIGN_BOTTOM = 6
//		ALIGN_BASELINE = 7
		cell.setVerticalAlignment(verticalAlignment);//垂直對齊方式
		
		Phrase phrase = new Phrase(content, font);
		cell.setPhrase(phrase);//填充資料
		
		return cell;
	}
	
	/**
	 * 建立單元格(指定字型、水平對齊方式、單元格跨x列合併)
	 * 預設垂直居中
	 * @param content
	 * @param font
	 * @param horizontalAlignment
	 * @param colspan
	 * @return
	 */
	public static PdfPCell createCellColspan(String content, Font font, int horizontalAlignment, int colspan) {
		PdfPCell cell = new PdfPCell();
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		cell.setHorizontalAlignment(horizontalAlignment);
		cell.setColspan(colspan);
		cell.setPhrase(new Phrase(content, font));
		return cell;
	}
	
	/**
	 * 建立單元格(指定字型、水平對齊方式、單元格跨x列合併、設定單元格內邊距)
	 * 預設垂直居中
	 * @param value
	 * @param font
	 * @param align
	 * @param colspan
	 * @return
	 */
	public PdfPCell createCellBorder(String value, Font font, int horizontalAlignment, int colspan) {
		PdfPCell cell = new PdfPCell();
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		cell.setHorizontalAlignment(horizontalAlignment);
		cell.setColspan(colspan);
		cell.setPhrase(new Phrase(value, font));
		cell.setPadding(3.0f);//設定單元格內內容的填充(內容與邊框之間的空格)
		
		cell.setBorder(0);//0表示無邊框
		cell.setPaddingTop(8.0f);//屬性填充頂部
		cell.setPaddingBottom(8.0f);//屬性填充底部
		return cell;
	}

	
	
	public static void main(String[] args) {
		downPdf(FILE_DIR + "createSamplePDF1.pdf");
		System.out.println("操作成功");
	}
	
	@Test
	public void method() {
		cm2pound(10);//單位毫米
	}

	private void cm2pound(int cm) {
		float pound= 592.52f/297 * cm;
		System.out.println(pound);
	}
}

  

MyHeaderFooter1.java

package cn.zj.pdf;

import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

public class MyHeaderFooter1 extends PdfPageEventHelper {

	private static Font chineseFont;
	private PdfTemplate totalPage;

	static {
		try {
			chineseFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12, Font.NORMAL);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 開啟文件時,建立一個總頁數的模版
	 */
	public void onOpenDocument(PdfWriter writer, Document document) {
		PdfContentByte pdfContentByte = writer.getDirectContent();
		totalPage = pdfContentByte.createTemplate(30f, 16f);
	}
	
	public void onEndPage(PdfWriter writer, Document document) {
		PdfPTable table = new PdfPTable(3);
		
		int pageNumber = writer.getPageNumber();
		if(pageNumber >= 3) {//前兩頁為封皮,不用加頁首頁尾
			try {
				table.setTotalWidth(PageSize.A4.getWidth() - 100);
				table.setWidths(new int[] { 24, 24, 3});
				table.setLockedWidth(true);
				table.getDefaultCell().setFixedHeight(-10);//設定單元格的固定高度
				table.getDefaultCell().setBorder(Rectangle.BOTTOM);
				
				table.addCell(new Paragraph("我是頁首/頁尾", chineseFont));// 可以直接使用addCell(str),不過不能指定字型,中文無法顯示
				table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
				table.addCell(new Paragraph("第" + (writer.getPageNumber() - 2) + "頁/", chineseFont));
				// 總頁數
				PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
				cell.setBorder(Rectangle.BOTTOM);
				table.addCell(cell);
				// 將頁首寫到document中,位置可以指定,指定到下面就是頁尾
				// PageSize.A4.getHeight() = 842.0
				// table.writeSelectedRows(0, -1, 50,PageSize.A4.getHeight() - 20, writer.getDirectContent());
				// 如果使用PageSize.A4.getHeight()則writer.getPageNumber()應該減去2 ,寫在當頁的最上部
				//如果使用PageSize.A4.getBottom()則writer.getPageNumber()應該減去3,寫在當頁的最下部
				table.writeSelectedRows(0, -1, 50,PageSize.A4.getBottom() + 30, writer.getDirectContent());
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 全部完成後,將總頁數的pdf模版寫到指定位置
	 */
    public void onCloseDocument(PdfWriter writer,Document document) {
    	//減去2 去掉封面的兩頁
        String text = "總" + (writer.getPageNumber() - 2) + "頁";
        ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,chineseFont), 2, 2, 0);
    }

}

  

其中 圖片位置/project/src/main/resources/static/img/timg.JPG