java 後端生成pdf模板合並單元格表格的案例

這裡隻放部分片段的代碼

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();
 }
 
 }

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: