Java中Itext生成Pdf,并給PdfCell添加圖片
1. 頁眉頁腳類 _ 根據(jù)實(shí)際情況使用,如不需要可忽略此步
package com.mediinfo.test;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.Date;
@Slf4j
public class PdfHeaderFooter extends PdfPageEventHelper {
private final static String FONT_PATH = "c:\\windows\\fonts\\SIMSUN.TTC,1";
private final static String logoPath = "D:\\1.jpg";
//總頁碼使用的模板對(duì)象
public PdfTemplate totalNumTemplate = null;
/**
* 重寫頁面結(jié)束時(shí)間 分別添加頁眉、頁腳
*/
public void onEndPage(PdfWriter writer, Document docment){
try{
this.addPageHeader(writer, docment);
}catch(Exception e){
log.error("添加頁眉出錯(cuò)", e);
}
try{
this.addPageFooter(writer, docment);
}catch(Exception e){
log.error("添加頁腳出錯(cuò)", e);
}
}
/**
* 頁眉
*/
private void addPageHeader(PdfWriter writer, Document docment) throws IOException, DocumentException {
BaseFont BASE_FONT = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
//創(chuàng)建字體
Font textFont = new Font(BASE_FONT, 10f);
//兩列 一列l(wèi)ogo 一列項(xiàng)目簡(jiǎn)稱 有Logo時(shí)添加圖片,沒有時(shí)添加個(gè)空值,避免報(bào)錯(cuò)
PdfPTable table = new PdfPTable(2);
//設(shè)置表格寬度 A4紙寬度減去兩個(gè)邊距 比如我一邊30 所以減去60
table.setTotalWidth(PageSize.A4.getWidth()-60);
//logo
//創(chuàng)建圖片對(duì)象
try {
Image logo = Image.getInstance(logoPath);
//創(chuàng)建一個(gè)Phrase對(duì)象 再添加一個(gè)Chunk對(duì)象進(jìn)去 Chunk里邊是圖片
Phrase logoP = new Phrase("", textFont);
//自己調(diào)整偏移值 主要是y軸值
logoP.add(new Chunk(logo, 0, -5));
PdfPCell logoCell = new PdfPCell(logoP);
//只保留底部邊框和設(shè)置高度
logoCell.disableBorderSide(13);
logoCell.setFixedHeight(20);
table.addCell(logoCell);
}catch (IOException e){
Phrase nameP = new Phrase("", textFont);
PdfPCell nameCell = new PdfPCell(nameP);
nameCell.disableBorderSide(13);
nameCell.setFixedHeight(20);
table.addCell(nameCell);
}
Phrase nameP = new Phrase("頁眉右上角顯示的內(nèi)容", textFont);
PdfPCell nameCell = new PdfPCell(nameP);
//只保留底部邊框和設(shè)置高度 設(shè)置水平居右和垂直居中
nameCell.disableBorderSide(13);
nameCell.setFixedHeight(20);
nameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
nameCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(nameCell);
//再把表格寫到頁眉處 使用絕對(duì)定位
table.writeSelectedRows(0, -1, 30, PageSize.A4.getHeight()-5, writer.getDirectContent());
}
/**
* 頁腳
*/
private void addPageFooter(PdfWriter writer, Document docment) throws DocumentException, IOException {
BaseFont BASE_FONT = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
//創(chuàng)建字體
Font textFont = new Font(BASE_FONT, 10f);
//三列 一列導(dǎo)出人 一列頁碼 一列時(shí)間
PdfPTable table = new PdfPTable(3);
//設(shè)置表格寬度 A4紙寬度減去兩個(gè)邊距 比如我一邊30 所以減去60
table.setTotalWidth(PageSize.A4.getWidth()-60);
//僅保留頂部邊框
table.getDefaultCell().disableBorderSide(14);
table.getDefaultCell().setFixedHeight(40);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
//導(dǎo)出人
table.addCell(new Phrase("admin", textFont));
//頁碼
//初始化總頁碼模板
if(null == totalNumTemplate){
totalNumTemplate = writer.getDirectContent().createTemplate(30, 16);
}
//再嵌套一個(gè)表格 一左一右 左邊當(dāng)前頁碼 右邊總頁碼
PdfPTable pageNumTable = new PdfPTable(2);
pageNumTable.setTotalWidth(new float[]{80f, 80f});
pageNumTable.setLockedWidth(true);
pageNumTable.setPaddingTop(-5f);
//第一列居右
pageNumTable.getDefaultCell().disableBorderSide(15);
pageNumTable.getDefaultCell().setFixedHeight(16);
pageNumTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
pageNumTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
pageNumTable.addCell(new Phrase(writer.getPageNumber()+" / ", textFont));
//第二列居左
Image totalNumImg = Image.getInstance(totalNumTemplate);
totalNumImg.setPaddingTop(-5f);
pageNumTable.getDefaultCell().setPaddingTop(-18f);
pageNumTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
pageNumTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
pageNumTable.addCell(totalNumImg);
//把頁碼表格添加到頁腳表格
table.addCell(pageNumTable);
//日期
table.addCell(new Phrase(String.valueOf(new Date()), textFont));
//再把表格寫到頁腳處 使用絕對(duì)定位
table.writeSelectedRows(0, -1, 30, 40, writer.getDirectContent());
}
/**
* 文檔關(guān)閉事件
*/
@SneakyThrows
@Override
public void onCloseDocument(PdfWriter writer, Document docment){
BaseFont BASE_FONT = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
//創(chuàng)建字體
Font textFont = new Font(BASE_FONT, 10f);
//將最后的頁碼寫入到總頁碼模板
String totalNum = writer.getPageNumber() + "頁";
totalNumTemplate.beginText();
totalNumTemplate.setFontAndSize(BASE_FONT, 5f);
totalNumTemplate.showText(totalNum);
totalNumTemplate.setHeight(16f);
totalNumTemplate.endText();
totalNumTemplate.closePath();
}
}
2. Pdf生成 [ PdfCell添加圖片參考createHardwarePDF方法的第九行nineRowTalbe ]
package com.mediinfo.test;
import com.itextpdf.text.*;
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 java.io.*;
public class PdfUtils {
//使用例子
public static void main(String[] args) throws Exception {
createHardwarePDF("d:/test.pdf");
}
/**
* 新建以下兩個(gè)方法,創(chuàng)建表格內(nèi)的字體和樣式的方法
*
* @param str 內(nèi)容
* @param font 字體對(duì)象
* @param high 表格高度
* @return
* @Param alignCenter 是否水平居中
* @Param alignMidde 是否垂直居中
*/
private static PdfPCell mircoSoftFont(String str, Font font, int high, boolean alignCenter, boolean alignMidde) {
PdfPCell pdfPCell = new PdfPCell(new Phrase(str, font));
pdfPCell.setMinimumHeight(high);
pdfPCell.setUseAscender(true); // 設(shè)置可以居中
if (alignCenter) {
pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 設(shè)置水平居中
}
if (alignMidde) {
pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 設(shè)置垂直居中
}
return pdfPCell;
}
/**
* @param str 字符串
* @param font 字體
* @param high 表格高度
* @return
* @Param alignCenter 是否水平居中
* @Param alignMidde 是否垂直居中
* @Param haveColor 是否有背景色(灰色)
*/
private static PdfPCell mircoSoftFont(String str, Font font, int high, boolean alignCenter, boolean alignMidde, boolean haveColor) {
PdfPCell pdfPCell = new PdfPCell(new Phrase(str, font));
pdfPCell.setMinimumHeight(high);
pdfPCell.setUseAscender(true); // 設(shè)置可以居中
if (alignCenter) {
pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 設(shè)置水平居中
}
if (alignMidde) {
pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 設(shè)置垂直居中
}
if (haveColor) {
//顏色代碼 RGB
pdfPCell.setBackgroundColor(new BaseColor(217, 217, 217));
}
return pdfPCell;
}
/*
將圖片插入到PdfCell
*/
// private static PdfPCell mircoSoftFont(byte[] iamgeBytes, int high) throws Exception {
private static PdfPCell ImageSet(int high) throws Exception {
byte[] fileByte = toByteArray("D:\\2.jpg");
Jpeg jpeg = new Jpeg(fileByte);
jpeg.scaleAbsolute(70, 50);
PdfPCell pdfPCell = new PdfPCell(jpeg);
pdfPCell.setMinimumHeight(high);
pdfPCell.setUseAscender(true); // 設(shè)置可以居中
pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 設(shè)置水平居中
pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 設(shè)置垂直居中
return pdfPCell;
}
/*
生成Pdf文檔
*/
public static void createHardwarePDF(String outputPath) throws Exception {
//新建文檔對(duì)象,頁大小為A4紙,然后設(shè)置4個(gè)邊距
Document document = new Document(PageSize.A4, 20, 20, 30, 30);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
//創(chuàng)建字體
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//字體對(duì)象
Font size14font = new Font(baseFont, 14, Font.NORMAL); //大小為14的正常字體
Font size10font = new Font(baseFont, 10, Font.BOLD); //大小為10的粗體
document.open();
// 添加頁眉和頁碼 Add By Zhaof 2022-11-16 實(shí)測(cè)可用
// 要修改頁眉頁腳顯示的內(nèi)容,直接修改PdfHeaderFooterEvent對(duì)象的頁眉頁腳內(nèi)容即可;
PdfHeaderFooter event = new PdfHeaderFooter();
writer.setPageEvent(event);
//添加標(biāo)題
PdfPTable tableName = new PdfPTable(1);
tableName.setWidthPercentage(90); //設(shè)置標(biāo)題長(zhǎng)度占紙張比例
PdfPCell titleCell = mircoSoftFont("個(gè)人信息", size14font, 80, true, true);
titleCell.disableBorderSide(15);
tableName.addCell(titleCell);
document.add(tableName);
//添加第二行的數(shù)據(jù)
PdfPTable secondRowTable = new PdfPTable(3); //三列的意思
secondRowTable.setWidthPercentage(90);
//這里的數(shù)組長(zhǎng)度是上面創(chuàng)建的列數(shù),數(shù)組的總和為1,就是按比例劃分的意思
secondRowTable.setTotalWidth(new float[]{0.18f, 0.32f, 0.5f});
secondRowTable.addCell(mircoSoftFont(" 姓名: ", size10font, 50, false, true));
secondRowTable.addCell(mircoSoftFont("李曉明", size10font, 50, false, true));
secondRowTable.addCell(mircoSoftFont(" 出生日期: 1994年3月14日", size10font, 50, false, true));
document.add(secondRowTable);
//第三行數(shù)據(jù)
PdfPTable thirdRowTable = new PdfPTable(3);
thirdRowTable.setWidthPercentage(90);
thirdRowTable.setTotalWidth(new float[]{0.18f, 0.32f, 0.5f});
thirdRowTable.addCell(mircoSoftFont(" 名族:", size10font, 50, false, true));
thirdRowTable.addCell(mircoSoftFont("漢族", size10font, 50, false, true));
thirdRowTable.addCell(mircoSoftFont(" 聯(lián)系電話: 13888880000", size10font, 50, false, true));
document.add(thirdRowTable);
//第四行數(shù)據(jù)
PdfPTable fourthRowTable = new PdfPTable(2);
fourthRowTable.setWidthPercentage(90);
fourthRowTable.setTotalWidth(new float[]{0.66f, 0.34f});
fourthRowTable.addCell(mircoSoftFont(" 個(gè)人描述 :", size10font, 175, false, false));
fourthRowTable.addCell(mircoSoftFont("個(gè)人特長(zhǎng) :", size10font, 175, false, false));
document.add(fourthRowTable);
//第五行
PdfPTable fifthDetailName = new PdfPTable(1);
fifthDetailName.setWidthPercentage(90);
fifthDetailName.addCell(mircoSoftFont("獲獎(jiǎng)記錄 :", size14font, 50, true, true));
document.add(fifthDetailName);
//第六行
PdfPTable sisthRowTalbe = new PdfPTable(1);
sisthRowTalbe.setWidthPercentage(90);
sisthRowTalbe.addCell(mircoSoftFont(" 聯(lián)系地址: " + "廣東省廣州市天河區(qū)XXXXXXXXXXXXXXXXXX", size10font, 50, false, true));
document.add(sisthRowTalbe);
PdfPTable seventhRowTalbe = new PdfPTable(1);
seventhRowTalbe.setWidthPercentage(90);
seventhRowTalbe.addCell(mircoSoftFont(" 畢業(yè)院校 ", size14font, 60, true, true));
document.add(seventhRowTalbe);
//第八行
PdfPTable eiththRowTalbe = new PdfPTable(3);
eiththRowTalbe.setWidthPercentage(90);
eiththRowTalbe.setTotalWidth(new float[]{0.3f, 0.5f, 0.2f});
eiththRowTalbe.addCell(mircoSoftFont(" 畢業(yè)學(xué)校", size10font, 50, true, true, true));
eiththRowTalbe.addCell(mircoSoftFont(" 就讀日期", size10font, 50, true, true, true));
eiththRowTalbe.addCell(mircoSoftFont(" 聯(lián)系人", size10font, 50, true, true, true));
document.add(eiththRowTalbe);
//接下來加List
String school = "XXX學(xué)校";
String time = "201909 - 2022-06";
String name = "陳某";
for (int i = 0; i < 2; i++) {
PdfPTable tempTable = new PdfPTable(3);
tempTable.setWidthPercentage(90);
tempTable.setTotalWidth(new float[]{0.3f, 0.5f, 0.2f});
tempTable.addCell(mircoSoftFont(school, size10font, 50, true, true));
tempTable.addCell(mircoSoftFont(time, size10font, 50, true, true));
tempTable.addCell(mircoSoftFont(name, size10font, 50, true, true));
document.add(tempTable);
}
// 第九行,添加圖片
PdfPTable nineRowTalbe = new PdfPTable(3);
nineRowTalbe.setWidthPercentage(90);
nineRowTalbe.setTotalWidth(new float[]{0.3f, 0.5f, 0.2f});
nineRowTalbe.addCell(mircoSoftFont(" test1", size10font, 50, true, true));
nineRowTalbe.addCell(mircoSoftFont(" test222", size10font, 50, true, true));
nineRowTalbe.addCell(ImageSet(50)); // 給PdfCell添加圖片
document.add(nineRowTalbe);
document.close();
writer.close();
}
public static byte[] toByteArray(String filename) throws IOException {
File f = new File(filename);
if (!f.exists()) {
throw new FileNotFoundException(filename);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
}
3. 實(shí)現(xiàn)效果如下圖
文章來源地址http://www.zghlxwxcb.cn/news/detail-571175.html
文章來源:http://www.zghlxwxcb.cn/news/detail-571175.html
到了這里,關(guān)于Java中Itext生成Pdf,并給PdfCell添加圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!