java 后端生成pdf模板合并單元格表格的案例
這里只放部分片段的代碼
java中使用二維數(shù)組生成表格非常方便,但是每一維的數(shù)組都需要排好序,而且,在java中所謂的二維數(shù)組,三維數(shù)組等,其實(shí)都是多個(gè)一維數(shù)組組成的
/**
* 添加子女教育規(guī)劃表。
* @param name 子女姓名
* @param educationItems 某個(gè)孩子的教育規(guī)劃的二維數(shù)組,每列依次是:學(xué)程階段、年數(shù)、費(fèi)用支出(元)/年、年增長率
* @param spacing
* @throws DocumentException
* @throws IOException
*/
private void addEducationTable(String name, String[][] educationItems, float spacing) throws DocumentException, IOException
{
addParagraphText(name + "的教育支出規(guī)劃如下:", getMainTextFont(), 0, SPACING_5, LEADING_MULT);//標(biāo)題字段
//以下是表頭
float[] colWidth = new float[] { mm2px_width(34f), mm2px_width(34f), mm2px_width(34f), mm2px_width(34f), mm2px_width(34f) };
String[] colName = { "學(xué)程階段", "年數(shù)", "規(guī)劃值(首次)","發(fā)生值(首次)", "年增長率" };//表頭列的一維數(shù)組
int[] colAlignment = {Element.ALIGN_LEFT, Element.ALIGN_RIGHT, Element.ALIGN_RIGHT, Element.ALIGN_RIGHT, Element.ALIGN_RIGHT }; //表頭有幾列就寫幾個(gè)對齊方式
float[] colPaddingLeft = { 3f, 3f, 3f, 3f, 3f };
float[] colPaddingRight = { 3f, 3f, 3f, 3f, 3f };
Font[] colFont = { getTabCellTextFont(), getTabCellTextFont(), getTabCellTextFont(), getTabCellTextFont(), getTabCellTextFont() };//字體及顏色的設(shè)置
educationItems=swap(educationItems, 3, 4);//這是排序二維數(shù)組,把第4列換到第3行(從0開始計(jì)數(shù))
PdfPTable table = tableTemplate(educationItems, colWidth, colName, colAlignment, colPaddingLeft, colPaddingRight, colFont);//生成表格
table.setSpacingAfter(mm2px_height(spacing));
this._document.add(table);//生成到PDF去,代碼就不貼了
}
/**
* @param items 二維數(shù)組表示的表
* @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); //單元格內(nèi)文字行間距
intTable.getDefaultCell().setBorderColor(COLOR_CELL_BORDER); //邊框顏色
intTable.setHeaderRows(1); //第一行做表頭,跨頁再現(xiàn)表頭
//單元格可以跨頁
intTable.setSplitLate(false);
intTable.setSplitRows(true);
/*********************************************************************************************/
/***********************************以下是表頭標(biāo)題欄*******************************************/
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); //單元格內(nèi)文字不確定,不能設(shè)置成固定行高
intTable.getDefaultCell().setBackgroundColor(COLOR_CELL_BACK_WHITE);
for(int i = 0; i < items.length; i++)
{
if(i == items.length - 1) //最后一行有合并單元格
{
intTable.getDefaultCell().setColspan(6);//設(shè)置具體合并哪一列
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;
}
/*
*二維數(shù)組根據(jù)指定列排序到指定位置的方法,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 獲取表頭標(biāo)題欄字體。
* @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 獲取標(biāo)題字體。
* @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 獲取標(biāo)題字體(小)。
* @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);
}
加一個(gè)生成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;
}
/**
* 像素到毫米的轉(zhuǎn)換(高度)
* @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);
}
/**
* 添加標(biāo)題。
* @param title 標(biāo)題
* @param font 標(biāo)題字體
* @param spacingBefore 標(biāo)題前的空白(毫米)
* @throws DocumentException
* @throws IOException
*/
protected void addTitle(String title, Font font, float spacingBefore) throws DocumentException, IOException
{
addTitle(title, font, spacingBefore, 0f);
}
/**
* 添加標(biāo)題。
* @param title 標(biāo)題
* @param font 標(biāo)題字體
* @param spacingBefore 標(biāo)題前的空白(毫米)
* @param spacingAfter 標(biāo)題后的空白(毫米)
* @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);
}
/**
* 添加標(biāo)題。
* @param title 標(biāo)題
* @param font 標(biāo)題字體
* @param spacingBefore 標(biāo)題前的空白(毫米)
* @param spacingAfter 標(biāo)題后的空白(毫米)
* @param alignment 標(biāo)題的對齊方式(居中用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 文本行間距倍數(shù)
* @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 文本行間距倍數(shù)
* @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); //首行縮進(jìn)
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)); //表后面的間隔,跨頁之后不再起作用,要的就是這個(gè)效果
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);
}
/**
* 添加小節(jié)的頭部圖片
* @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 圖片內(nèi)存數(shù)組
* @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坐標(biāo)(毫米)
* @param beginY 開始Y坐標(biāo)(毫米)
* @param endX 終止X坐標(biāo)(毫米)
* @param endY 終止Y坐標(biāo)(毫米)
* @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-頁內(nèi)容為空依然顯示; true-頁內(nèi)容為空不會顯示
}
/**
* 獲取字體。
* @param fontname 字體名稱(含路徑)
* @param fontsize 字體大小
* @param fontstyle 字體風(fēng)格
* @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);
}
/**
* 像素到毫米的轉(zhuǎn)換(寬度)
* @param px 橫向像素
* @return
*/
public static float px2mm_width(float px)
{
return px * GDM.PAGE_WIDTH / PageSize.A4.getWidth();
}
/**
* 毫米到像素的轉(zhuǎn)換(寬度)
* @param mm 橫向毫米
* @return
*/
public static float mm2px_width(float mm)
{
return mm * PageSize.A4.getWidth() / GDM.PAGE_WIDTH; //A4紙寬210毫米
}
/**
* 毫米到像素的轉(zhuǎn)換(高度)
* @param mm 縱向毫米
* @return
*/
public static float mm2px_height(float mm)
{
return mm * PageSize.A4.getHeight() / GDM.PAGE_HEIGHT; //A4紙高297毫米
}
/**
* 添加法律聲明、我們的觀點(diǎn)、假設(shè)和依據(jù)、資產(chǎn)配置策略。
* @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);
}
/**
* 根據(jù)所在區(qū)域的寬高對圖片進(jìn)行不變形縮放。
* @param imgByte 圖片
* @param scaleWidth 所在區(qū)域?qū)挾?
* @param scaleHeight 所在區(qū)域高度
* @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;
}
/**
* 獲取文檔可操作區(qū)域的寬度(像素)。
* @return
*/
protected float getDocWidth()
{
return this._document.right() - this._document.left();
}
}
補(bǔ)充:java動(dòng)態(tài)生成pdf含表格table和 合并兩個(gè)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.廢話不多說,上代碼,直接拿去運(yùn)行測試:
public static void test1(){//生成pdf
BaseFont bf;
Font font = null;
try {
bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);//創(chuàng)建字體
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 };// 設(shè)置表格的列寬和列數(shù) 默認(rèn)是4列
PdfPTable table = new PdfPTable(widths);// 建立一個(gè)pdf表格
table.setSpacingBefore(20f);
table.setWidthPercentage(100);// 設(shè)置表格寬度為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);
//以下代碼的作用是創(chuàng)建100行數(shù)據(jù),其中每行有四列,列依次為 編號 姓名 性別 備注
for (int i = 1; i <=10; i++) {
//設(shè)置編號單元格
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");
}
}
以下是合并多個(gè)pdf文件功能程序,上代碼:
//*********合并 pdfFilenames為文件路徑數(shù)組,targetFileName為目標(biāo)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();
}
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Java使用Callable接口實(shí)現(xiàn)多線程的實(shí)例代碼
這篇文章主要介紹了Java使用Callable接口實(shí)現(xiàn)多線程的實(shí)例代碼,實(shí)現(xiàn)Callable和實(shí)現(xiàn)Runnable類似,但是功能更強(qiáng)大,具體表現(xiàn)在可以在任務(wù)結(jié)束后提供一個(gè)返回值,Runnable不行,call方法可以拋出異,Runnable的run方法不行,需要的朋友可以參考下2023-08-08
Eclipse導(dǎo)入項(xiàng)目報(bào)錯(cuò)問題解決方案
這篇文章主要介紹了Eclipse導(dǎo)入項(xiàng)目報(bào)錯(cuò)問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
解決Eclipse中java文件的圖標(biāo)變成空心J的問題
這篇文章主要介紹了解決Eclipse中java文件的圖標(biāo)變成空心J的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
java開發(fā)SpringBoot參數(shù)校驗(yàn)過程示例教程
這篇文章主要為大家介紹了SpringBoot如何進(jìn)行參數(shù)校驗(yàn)的過程示例詳解教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10
通過Java?Reflection實(shí)現(xiàn)編譯時(shí)注解正確處理方法
Java注解是一種標(biāo)記在JDK5及以后的版本中引入,用于Java語言中向程序添加元數(shù)據(jù)的方法,這篇文章主要介紹了通過Java?Reflection實(shí)現(xiàn)編譯時(shí)注解處理方法,需要的朋友可以參考下2023-06-06
springmvc接收json串,轉(zhuǎn)換為實(shí)體類List方法
今天小編就為大家分享一篇springmvc接收json串,轉(zhuǎn)換為實(shí)體類List方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
spring aop底層源碼執(zhí)行邏輯剖析(源碼解析)
這篇文章主要介紹了spring aop底層源碼執(zhí)行邏輯剖析,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-08-08

