java 后端生成pdf模板合并单元格表格的案例

 更新时间:2021年1月31日 15:00  点击:1989

这里只放部分片段的代码

java中使用二维数组生成表格非常方便,但是每一维的数组都需要排好序,而且,在java中所谓的二维数组,三维数组等,其实都是多个一维数组组成的

	/**
 	 * 添加子女教育规划表。
 	 * @param name 子女姓名
 	 * @param educationItems 某个孩子的教育规划的二维数组,每列依次是:学程阶段、年数、费用支出(元)/年、年增长率
 	 * @param spacing
 	 * @throws DocumentException
 	 * @throws IOException
 	 */
private void addEducationTable(String name, String[][] educationItems, float spacing) throws DocumentException, IOException
	{
	addParagraphText(name + "的教育支出规划如下:", getMainTextFont(), 0, SPACING_5, LEADING_MULT);//标题字段
	//以下是表头
	float[] colWidth = new float[] { mm2px_width(34f), mm2px_width(34f), mm2px_width(34f), mm2px_width(34f), mm2px_width(34f) };
				String[] colName = { "学程阶段", "年数", "规划值(首次)","发生值(首次)", "年增长率" };//表头列的一维数组
				int[] colAlignment = {Element.ALIGN_LEFT, Element.ALIGN_RIGHT, Element.ALIGN_RIGHT, Element.ALIGN_RIGHT, Element.ALIGN_RIGHT }; //表头有几列就写几个对齐方式
				float[] colPaddingLeft = { 3f, 3f, 3f, 3f, 3f };
				float[] colPaddingRight = { 3f, 3f, 3f, 3f, 3f };
				Font[] colFont = { getTabCellTextFont(), getTabCellTextFont(), getTabCellTextFont(), getTabCellTextFont(), getTabCellTextFont() };//字体及颜色的设置
				educationItems=swap(educationItems, 3, 4);//这是排序二维数组,把第4列换到第3行(从0开始计数)
				PdfPTable table = tableTemplate(educationItems, colWidth, colName, colAlignment, colPaddingLeft, colPaddingRight, colFont);//生成表格
				table.setSpacingAfter(mm2px_height(spacing)); 
				this._document.add(table);//生成到PDF去,代码就不贴了
	}
/**
	 * @param items 二维数组表示的表
	 * @param colWidth 各列的宽度(像素)
	 * @param colName 各列的名称
	 * @param colAlignment 各列的水平对齐方式
	 * @param colPaddingLeft 各列的左padding
	 * @param colPaddingRight 各列的右padding
	 * @param colFont 各列的字体
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	private PdfPTable tableTemplates(String[][] items, float[] colWidth, String[] colName, int[] colAlignment,
			float[] colPaddingLeft, float[] colPaddingRight, Font[] colFont) throws DocumentException, IOException
	{
		PdfPTable intTable = new PdfPTable(colWidth.length); 
		intTable.setTotalWidth(colWidth);
		intTable.setLockedWidth(true);
		
	 intTable.getDefaultCell().setLeading(mm2px_height(LEADING_CELL_TEXT), 1f); //单元格内文字行间距
	 intTable.getDefaultCell().setBorderColor(COLOR_CELL_BORDER); //边框颜色
	 intTable.setHeaderRows(1); //第一行做表头,跨页再现表头
	 
	 //单元格可以跨页
	 intTable.setSplitLate(false);
	 intTable.setSplitRows(true);
	 /*********************************************************************************************/
	 /***********************************以下是表头标题栏*******************************************/
	 float headerHeight = mm2px_height(TABLE_HEADER_HEIGHT);
	 intTable.getDefaultCell().setFixedHeight(headerHeight); //行高
	 intTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); //无边框
	 
	 for(int i = 0; i < colName.length; i++)
	 {
	 	intTable.getDefaultCell().setBackgroundColor(COLOR_TAB_HEADER); //表头背景
			intTable.getDefaultCell().setHorizontalAlignment(colAlignment[i]);
			intTable.getDefaultCell().setPaddingLeft(colPaddingLeft[i]);
			intTable.getDefaultCell().setPaddingRight(colPaddingRight[i]);
			
			intTable.addCell(new Paragraph(colName[i], getTabHeaderTextFont()));
	 }
	 /*********************************************************************************************/
	 /***********************************以下是表格每行*********************************************/
	 float rowHeight = mm2px_height(TABLE_ROW_HEIGHT);
	 intTable.getDefaultCell().setMinimumHeight(rowHeight); //单元格内文字不确定,不能设置成固定行高 
	 intTable.getDefaultCell().setBackgroundColor(COLOR_CELL_BACK_WHITE);
	 for(int i = 0; i < items.length; i++)
	 {
	 	if(i == items.length - 1) //最后一行有合并单元格
	 	{
	 		intTable.getDefaultCell().setColspan(6);//设置具体合并哪一列
	 		intTable.getDefaultCell().setHorizontalAlignment(colAlignment[0]);
				intTable.getDefaultCell().setPaddingLeft(colPaddingLeft[0]);
				intTable.getDefaultCell().setPaddingRight(colPaddingRight[0]);
	 	 intTable.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM); 
	 	 intTable.addCell(new Paragraph(items[i][0], colFont[0]));
	 	}else{
	 		for(int j = 0; j < items[i].length; j++)
	 		{
	 			if(j == 0)intTable.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
	 			else intTable.getDefaultCell().setBorder(Rectangle.RIGHT | Rectangle.BOTTOM); 
	 			if(j < colAlignment.length){	
					intTable.getDefaultCell().setHorizontalAlignment(colAlignment[j]);
					intTable.getDefaultCell().setPaddingLeft(colPaddingLeft[j]);
					intTable.getDefaultCell().setPaddingRight(colPaddingRight[j]);
					intTable.addCell(new Paragraph(items[i][j], colFont[j]));
	 		}
	 	}
	 	}
	 }
	 /*********************************************************************************************/
	 
	 return intTable;
	}
/*
*二维数组根据指定列排序到指定位置的方法,f2要大于f1
*/
public String[][] swap(String[][] data,int f1,int f2){
		for (int i = 0; i < data.length; i++) {
			String tamp=data[i][f2];
			for (int j = f2; j >f1; j--) {
				data[i][j]=data[i][j-1];
			}
			data[i][f1]=tamp;
		}
		return data;
	}
	/**
	 * @return 获取表头标题栏字体。
	 * @throws DocumentException
	 * @throws IOException
	 */
	private static Font getTabHeaderTextFont() throws DocumentException, IOException
	{
		return getFont(GDM.getUrlString(GDM.FONT_SIMHEI), FONT_SIZE_TAB_HEADER_TEXT, Font.NORMAL, COLOR_TAB_HEADER_TEXT);
	}
	/**
	 * @return 获取单元格文字字体。
	 * @throws DocumentException
	 * @throws IOException
	 */
	private static Font getTabCellTextFont() throws DocumentException, IOException
	{
		return getFont(GDM.getUrlString(GDM.FONT_SIMHEI), FONT_SIZE_TAB_CELL_TEXT, Font.NORMAL, GDM.COLOR_666666);
	}
	
	/**
	 * @return 获取标题字体。
	 * @throws DocumentException
	 * @throws IOException
	 */
	private static Font getTitleFont() throws DocumentException, IOException
	{
		return getFont(GDM.getUrlString(GDM.FONT_HEADER_CH), FONT_SIZE_TITLE, Font.NORMAL, GDM.COLOR_333333);
	}	
	
	/**
	 * @return 获取标题字体(小)。
	 * @throws DocumentException
	 * @throws IOException
	 */
	private static Font getTitleFont_Small() throws DocumentException, IOException
	{
		return getFont(GDM.getUrlString(GDM.FONT_HEADER_CH), FONT_SIZE_TITLE - 1f, Font.NORMAL, GDM.COLOR_333333);
	}
	
	/**
	 * @return 获取正文字体。
	 * @throws DocumentException
	 * @throws IOException
	 */
	private static Font getMainTextFont() throws DocumentException, IOException
	{
		return getFont(GDM.getUrlString(GDM.FONT_NORMAL), FONT_SIZE_MAINTEXT, Font.NORMAL, GDM.COLOR_666666);
	}

加一个生成pdf常用的格式工具类

import java.io.IOException;
import java.net.MalformedURLException;
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.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class FinPlan 
{
	protected Document _document; //文档对象
	protected PdfWriter _writer; //pdf文档输出器	
	public FinPlan(Document document, PdfWriter writer) 
	{
		super();
		this._document = document;
		this._writer = writer;
	}
	/**
	 * 像素到毫米的转换(高度)
	 * @param px 纵向像素
	 * @return
	 */
	public static float px2mm_height(float px)
	{
		return px * GDM.PAGE_HEIGHT / PageSize.A4.getHeight();
	}	
	/**
	 * 在指定位置写入文字
	 * @param text 需要写入的文字
	 * @param xPoint 距左边位置(毫米)
	 * @param yPoint 距底边位置(毫米)
	 */
	protected void writeOnSpLocation(float xPoint, float yPoint, String text, Font font)
	{
		PdfContentByte pcb = this._writer.getDirectContent();
		
		xPoint = mm2px_width(xPoint);
		yPoint = mm2px_height(yPoint);
		Paragraph prg = new Paragraph(text, font);		
		ColumnText.showTextAligned(pcb, PdfContentByte.ALIGN_LEFT, prg, xPoint, yPoint, 0);
	}	
	/**
	 * 添加标题。
	 * @param title 标题
	 * @param font 标题字体
	 * @param spacingBefore 标题前的空白(毫米)
	 * @throws DocumentException
	 * @throws IOException
	 */
	protected void addTitle(String title, Font font, float spacingBefore) throws DocumentException, IOException
	{
		addTitle(title, font, spacingBefore, 0f);
	}	
	/**
	 * 添加标题。
	 * @param title 标题
	 * @param font 标题字体
	 * @param spacingBefore 标题前的空白(毫米)
	 * @param spacingAfter 标题后的空白(毫米)
	 * @throws DocumentException
	 * @throws IOException
	 */
	protected void addTitle(String title, Font font, float spacingBefore, float spacingAfter) throws DocumentException, IOException
	{
		Paragraph prg = new Paragraph(title, font);
		spacingBefore = mm2px_height(spacingBefore);
		prg.setSpacingBefore(prg.getLeading() * -1 + prg.getFont().getSize() * 0.8f + spacingBefore);
		//prg.setSpacingAfter(spacingAfter);
		this._document.add(prg);		
		addSpan(spacingAfter);
	}	
	/**
	 * 添加标题。
	 * @param title 标题
	 * @param font 标题字体
	 * @param spacingBefore 标题前的空白(毫米)
	 * @param spacingAfter 标题后的空白(毫米)
	 * @param alignment 标题的对齐方式(居中用Element.ALIGN_CENTER)
	 * @throws DocumentException
	 * @throws IOException
	 */
	protected void addTitle(String title, Font font, float spacingBefore, float spacingAfter, int alignment) throws DocumentException, IOException
	{
		Paragraph prg = new Paragraph(title, font);
		spacingBefore = mm2px_height(spacingBefore);
		prg.setSpacingBefore(prg.getLeading() * -1 + prg.getFont().getSize() * 0.8f + spacingBefore);
		prg.setAlignment(alignment);
		//prg.setSpacingAfter(spacingAfter); 改用下面的 addSpan(spacingAfter);
		this._document.add(prg);		
		addSpan(spacingAfter);
	}	
	/**
	 * 添加段落文本。
	 * @param text 段落文本
	 * @param font 字体
	 * @param spacingBefore 段落前的空白(毫米)
	 * @param leadingMult 文本行间距倍数
	 * @throws DocumentException
	 */
	protected void addParagraphText(String text, Font font, float spacingBefore, float leadingMult) throws DocumentException
	{	
		addParagraphText(text, font, spacingBefore, 0f, leadingMult);
	}	
	/**
	 * 添加段落文本。
	 * @param text 段落文本
	 * @param font 字体
	 * @param spacingBefore 段落前的空白(毫米)
	 * @param spacingAfter 段落后的空白(毫米)
	 * @param leadingMult 文本行间距倍数
	 * @throws DocumentException
	 */
	protected void addParagraphText(String text, Font font, float spacingBefore, float spacingAfter, float leadingMult) throws DocumentException
	{
		Paragraph prg = new Paragraph(text, font); //.trim()
		spacingBefore = mm2px_height(spacingBefore);
		//spacingAfter = mm2px_height(spacingAfter);
		prg.setLeading(prg.getLeading() * leadingMult);
		prg.setSpacingBefore(prg.getLeading() * -1f + prg.getFont().getSize() * 0.8f + spacingBefore); 
		//prg.setSpacingAfter(spacingAfter);
		//prg.setFirstLineIndent(prg.getFont().getSize() * 2f); //首行缩进
		prg.setAlignment(Element.ALIGN_LEFT); //对齐方式
		this._document.add(prg);
		
		addSpan(spacingAfter);
	}
	
	/**
	 * 添加跨页后不再起作用的间隔。
	 * @param gap 间隔大小(毫米)
	 * @throws DocumentException
	 */
	protected void addSpan(float gap) throws DocumentException
	{
		PdfPTable spanTable = new PdfPTable(1);
		spanTable.setTotalWidth(this._document.right() - this._document.left());
		spanTable.setLockedWidth(true);
		spanTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
		spanTable.setSpacingAfter(mm2px_height(gap)); //表后面的间隔,跨页之后不再起作用,要的就是这个效果		
		spanTable.addCell("");
		this._document.add(spanTable);
	}	
	/**
	 * 添加每一章的头部文字。
	 * @param headerCH 头部中文
	 * @param headerEN 头部英文
	 * @throws DocumentException
	 * @throws IOException
	 */
	protected void addChapterHeader(String headerCH, String headerEN) throws DocumentException, IOException
	{
		Font fontCH = getFont(GDM.getUrlString(GDM.FONT_HEADER_CH), GDM.FONT_SIZE_HEADER_CH, Font.NORMAL, GDM.COLOR_GOLD);
		Font fontEN = getFont(GDM.getUrlString(GDM.FONT_HEADER_EN), GDM.FONT_SIZE_HEADER_EN, Font.NORMAL, GDM.COLOR_GOLD);
		
		Phrase phrase = new Phrase();
		Chunk chunkCH = new Chunk(headerCH, fontCH);
		phrase.add(chunkCH);
		phrase.add(Chunk.NEWLINE);
 	Chunk chunkEN = new Chunk(headerEN, fontEN);
 	phrase.add(chunkEN);
 	
 	Paragraph prg = new Paragraph(phrase); 	
		prg.setSpacingAfter(mm2px_width(GDM.SPACING_AFTER_HEADER));
		this._document.add(prg);
	}
	
	/**
	 * 添加小节的头部图片
	 * @param imgFilename 含路径的图片文件名
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws DocumentException
	 */
	protected void addSectionHeader(String imgFilename) throws MalformedURLException, IOException, DocumentException
	{	
		Paragraph prg = new Paragraph("");
		prg.setLeading(0);
		this._document.add(prg);//在新开页中,上面段落的行间距会影响图片的位置
		
		float width = GDM.PAGE_WIDTH - GDM.MARGIN_LEFT - GDM.MARGIN_RIGHT;
		float height = GDM.HEIGHT_SECTIONHEADER;		
		addImage(imgFilename, width, height);
	}	
	/**
	 * 添加图片。
	 * @param imgFilename 含路径的图片文件名
	 * @param width 图片宽度(毫米)
	 * @param height 图片高度(毫米)
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws DocumentException
	 */
	protected void addImage(String imgFilename, float width, float height) throws MalformedURLException, IOException, DocumentException
	{
		Image img = Image.getInstance(imgFilename);
		addImage(img, width, height);
	}	
	/**
	 * 添加图片。
	 * @param imgByte 图片内存数组
	 * @param width 图片宽度(毫米)
	 * @param height 图片高度(毫米)
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws DocumentException
	 */
	protected void addImage(byte[] imgByte, float width, float height) throws MalformedURLException, IOException, DocumentException
	{
		Image img = Image.getInstance(imgByte);
		addImage(img, width, height);
	}	
	/**
	 * 添加图片。	 
	 * @param img 图片
	 * @param width 图片宽度(毫米)
	 * @param height 图片高度(毫米)
	 * @throws DocumentException
	 */
	private void addImage(Image img, float width, float height) throws DocumentException
	{
		img.setAlignment(Image.ALIGN_LEFT);
		width = mm2px_width(width);
		height = mm2px_height(height);
		img.scaleAbsolute(width, height);		
		this._document.add(img);
	}	
	/**
	 * 在指定位置添加图片。
	 * @param imgFilename 含路径的图片文件名
	 * @param width 图片宽度(毫米)
	 * @param height 图片高度(毫米)
	 * @param xPoint 距左边位置(毫米)
	 * @param yPoint 距底边位置(毫米)
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws DocumentException
	 */
	protected void addImageOnSpLocation(String imgFilename, float width, float height, float xPoint, float yPoint) throws MalformedURLException, IOException, DocumentException
	{
		Image img = Image.getInstance(imgFilename);
		img.setAlignment(Image.ALIGN_LEFT);		
		width = mm2px_width(width);
		height = mm2px_height(height);
		img.scaleAbsolute(width, height);		
		xPoint = mm2px_width(xPoint);
		yPoint = mm2px_height(yPoint);
		img.setAbsolutePosition(xPoint, yPoint);		
		this._document.add(img);
	}	
	/**
	 * 画线。
	 * @param beginX 开始X坐标(毫米)
	 * @param beginY 开始Y坐标(毫米)
	 * @param endX 终止X坐标(毫米)
	 * @param endY 终止Y坐标(毫米)
	 * @param lineWidth
	 * @param color
	 */
	protected void drawLint(float beginX, float beginY, float endX, float endY, float lineWidth, BaseColor color)
	{
		PdfContentByte cb = _writer.getDirectContent();
		cb.setLineWidth(lineWidth);
		cb.setColorStroke(color);		
		beginX = mm2px_width(beginX);
		beginY = mm2px_height(beginY);
		endX = mm2px_width(endX);
		endY = mm2px_height(endY);		
		cb.moveTo(beginX, beginY);
		cb.lineTo(endX, endY);		
		cb.stroke();
	}
	
	/**
	 * 添加新的页面
	 */
	protected void newPage()
	{
		this._document.newPage();
		//this._writer.setPageEmpty(false); //fasle-页内容为空依然显示; true-页内容为空不会显示
	}	
	/**
	 * 获取字体。
	 * @param fontname 字体名称(含路径)
	 * @param fontsize 字体大小
	 * @param fontstyle 字体风格
	 * @param color 字体颜色
	 * @return 字体
	 * @throws DocumentException
	 * @throws IOException
	 */	
	public static Font getFont(String fontname, float fontsize, int fontstyle, BaseColor color) throws DocumentException, IOException
	{
		BaseFont bfont = BaseFont.createFont(fontname, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		return new Font(bfont, fontsize, fontstyle, color);
	}	
	/**
	 * 像素到毫米的转换(宽度)
	 * @param px 横向像素
	 * @return
	 */
	public static float px2mm_width(float px)
	{
		return px * GDM.PAGE_WIDTH / PageSize.A4.getWidth();
	}	
	/**
	 * 毫米到像素的转换(宽度)
	 * @param mm 横向毫米
	 * @return
	 */
	public static float mm2px_width(float mm)
	{
		return mm * PageSize.A4.getWidth() / GDM.PAGE_WIDTH; //A4纸宽210毫米
	}
	/**
	 * 毫米到像素的转换(高度)
	 * @param mm 纵向毫米
	 * @return
	 */
	public static float mm2px_height(float mm)
	{
		return mm * PageSize.A4.getHeight() / GDM.PAGE_HEIGHT; //A4纸高297毫米
	}
	
	/**
	 * 添加法律声明、我们的观点、假设和依据、资产配置策略。
	 * @version 2017-03-30
	 * @param segments 文字或图片
	 * @param font 字体
	 * @param spacingBefore 段落前的空白(毫米)
	 * @param leadingMult 行间距
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws DocumentException
	 */
	protected void addPdfWord(Object[] segments, Font font, float spacingBefore, float leadingMult) throws MalformedURLException, IOException, DocumentException
	{
		for(Object obj : segments)
		{
			if(obj instanceof byte[])
			{
				Image img = Image.getInstance((byte[])obj);
				addImageTab(img);
			}
			else if(obj instanceof String)
			{
				addParagraphText((String)obj, font, spacingBefore, px2mm_height(font.getSize()) * leadingMult, leadingMult);
			}	
		}
	}	
	/**
	 * 以表格的方式添加图片。
	 * @version 2017-04-19
	 * @param img 图片
	 * @throws DocumentException
	 */
	protected void addImageTab(Image img) throws DocumentException
	{		
		float imgWidth = img.getWidth();
		float imgHeight = img.getHeight();
		float docWidth = this._document.right() - this._document.left();
		float docHeight = this._document.top() - this._document.bottom() - 5f * 2;
		
		float scalePercent_w = 100f;
		if(imgWidth > docWidth) scalePercent_w = docWidth * 100f / imgWidth;
		float scalePercent_h = 100f;
		if(imgHeight > docHeight) scalePercent_h = docHeight * 100f / imgHeight;
		
		float scalePercent = Math.min(scalePercent_w, scalePercent_h);
		float fixedHeight = imgHeight * scalePercent / 100f;
		
		img.setAlignment(Image.ALIGN_LEFT);
		img.scalePercent(scalePercent);
		
		PdfPTable table = new PdfPTable(1); 
 	table.setWidthPercentage(100f);
 	
		PdfPCell imgCell = new PdfPCell(img);
		imgCell.setPadding(0f);
		imgCell.setFixedHeight(fixedHeight);
		imgCell.setBorder(Rectangle.NO_BORDER);
		table.addCell(imgCell);
		table.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.setSpacingAfter(5f);
		table.setSpacingBefore(5f);
		table.keepRowsTogether(0);		
		this._document.add(table);
	}	
	/**
	 * 根据所在区域的宽高对图片进行不变形缩放。
	 * @param imgByte 图片
	 * @param scaleWidth 所在区域宽度
	 * @param scaleHeight 所在区域高度
	 * @return
	 * @throws BadElementException
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	protected Image scaledImage(byte[] imgByte, float scaleWidth, float scaleHeight) throws BadElementException, MalformedURLException, IOException
	{
		Image img = Image.getInstance(imgByte);		
		float imgWidth = img.getWidth();
		float imgHeight = img.getHeight();	
		float scalePercent_w = 100f;
		if(imgWidth > scaleWidth) scalePercent_w = scaleWidth * 100f / imgWidth;
		float scalePercent_h = 100f;
		if(imgHeight > scaleHeight) scalePercent_h = scaleHeight * 100f / imgHeight;
		
		float scalePercent = Math.min(scalePercent_w, scalePercent_h);
		img.setAlignment(Image.ALIGN_LEFT);
		img.scalePercent(scalePercent);			
		return img;
	}	
	/**
	 * 获取文档可操作区域的宽度(像素)。
	 * @return
	 */
	protected float getDocWidth()
	{
		return this._document.right() - this._document.left();
	}
}

补充:java动态生成pdf含表格table和 合并两个pdf文件功能

1.首先一样需要maven依赖包:

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
 <dependency>
 <groupId>com.itextpdf</groupId>
 <artifactId>itextpdf</artifactId>
 <version>5.5.10</version>
 </dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
 <dependency>
 <groupId>com.itextpdf</groupId>
 <artifactId>itext-asian</artifactId>
 <version>5.2.0</version>
 </dependency>

2.废话不多说,上代码,直接拿去运行测试:

public static void test1(){//生成pdf
 BaseFont bf;
  Font font = null;
  try {
  bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
   BaseFont.NOT_EMBEDDED);//创建字体
  font = new Font(bf,12);//使用字体
  } catch (Exception e) {
  e.printStackTrace();
  }
  Document document = new Document();
  try {
  PdfWriter.getInstance(document, new FileOutputStream("E:/测试.pdf"));
  document.open();
  document.add(new Paragraph("就是测试下",font));//引用字体
  document.add(new Paragraph("真的测试下",font));//引用字体
  
  float[] widths = {25f,25f,25f };// 设置表格的列宽和列数 默认是4列 
  PdfPTable table = new PdfPTable(widths);// 建立一个pdf表格 
  table.setSpacingBefore(20f); 
  table.setWidthPercentage(100);// 设置表格宽度为100% 
  
  PdfPCell cell = null; 
  cell = new PdfPCell(new Paragraph("姓名",font));// 
  cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
  cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(cell);
  
  cell = new PdfPCell(new Paragraph("性别",font));// 
  cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
  cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(cell);
  
  cell = new PdfPCell(new Paragraph("身份证号",font));// 
  cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
  cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(cell);
 
  //以下代码的作用是创建100行数据,其中每行有四列,列依次为 编号 姓名 性别 备注
  for (int i = 1; i <=10; i++) {
   //设置编号单元格
  PdfPCell cell11=new PdfPCell(new Paragraph("aa名媛",font));
  PdfPCell cell22=new PdfPCell(new Paragraph("bb女",font));
  PdfPCell cell33=new PdfPCell(new Paragraph("cc花姑娘",font));
 
   //单元格水平对齐方式
   cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
   //单元格垂直对齐方式
   cell11.setVerticalAlignment(Element.ALIGN_CENTER); 
   cell22.setHorizontalAlignment(Element.ALIGN_CENTER);
   cell22.setVerticalAlignment(Element.ALIGN_CENTER); 
   cell33.setHorizontalAlignment(Element.ALIGN_CENTER);
   cell33.setVerticalAlignment(Element.ALIGN_CENTER); 
   table.addCell(cell11);
   table.addCell(cell22);
   table.addCell(cell33);  
  }
  document.add(table);  
  document.close();
  } catch (Exception e) {
  System.out.println("file create exception");
  }
  
 }

以下是合并多个pdf文件功能程序,上代码:

//*********合并 pdfFilenames为文件路径数组,targetFileName为目标pdf路径
 public static void combinPdf(String[] pdfFilenames, String targetFilename) 
 throws Exception { 
 PdfReader reader = null; 
 Document doc = new Document(); 
 PdfCopy pdfCopy = new PdfCopy(doc, new FileOutputStream(targetFilename)); 
 int pageCount = 0; 
 doc.open(); 
 for (int i = 0; i < pdfFilenames.length; ++i) { 
 System.out.println(pdfFilenames[i]);
 reader = new PdfReader(pdfFilenames[i]); 
 pageCount = reader.getNumberOfPages(); 
 for (int j = 1; j <= pageCount; ++j) { 
 pdfCopy.addPage(pdfCopy.getImportedPage(reader, j)); 
 } 
 } 
 doc.close(); 
 }

这里附上测试程序:

public static void main(String[] args) throws InterruptedException {
 String fillTemplate1 = "E:/测试.pdf";
 String fillTemplate2 = "E:/测试.pdf";
 String[] st = {fillTemplate1,fillTemplate2};
 try {
 combinPdf(st,"E:/合并.pdf");
 
 } catch (Exception e) {
 e.printStackTrace();
 }
 
 }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。如有错误或未考虑完全的地方,望不吝赐教。

[!--infotagslink--]

相关文章