iText实现Java生成PDF文件

Posted ASKANDANSWERS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = "
";
			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

 

以上是关于iText实现Java生成PDF文件的主要内容,如果未能解决你的问题,请参考以下文章

iText实现Java生成PDF文件

Java Itext 生成PDF文件

java 已经获取pdf代码,如何把他pdf文件保存到本机 要求用输出流做

Java使用Flying Saucer实现HTML代码生成PDF文档

# Itext Pdf 生成相关API

Java操作PDF之itext入门