java通過itext生成pdf的干貨教程
我們經(jīng)常會遇到要導(dǎo)出pdf的需求,方式有很多種 今天的教程是采用itext的方式生成pdf
先來看一下效果

OK,下面開始教程
1.準(zhǔn)備工作-下載相關(guān)依賴
<!--itext相關(guān)-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>io</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>pdfa</artifactId>
<version>7.0.3</version>
</dependency>2.創(chuàng)建實(shí)體對象
package com.example.demo.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author: Mr.Z
* @Date: 2024年03月22日 14:53
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChildInfo {
/**
* 幼兒姓名
*/
private String stuName;
/**
* 性別
*/
private String sex;
/**
* 是否獨(dú)生子女
*/
private String onlyChild;
/**
* 血型
*/
private String blood;
/**
* 幼兒身份證號
*/
private String stuIdCard;
/**
* 幼兒出生日期
*/
private String stuDate;
/**
* 民族
*/
private String nation;
/**
* 幼兒照片
*/
private String childPic;
/**
* 幼兒籍貫
*
*/
private String nativePlace;
/**
* 出生所在地
*/
private String birthPlace;
/**
* 幼兒戶籍地區(qū)碼
*/
private String nativeCode;
}
3.編寫pdf樣式及內(nèi)容,這里相關(guān)介紹我都寫到注釋里面了,很詳細(xì)
package com.example.demo.service.impl;
import com.example.demo.entity.ChildInfo;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.color.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
/**
* @Author: Mr.Z
* @Date: 2024年03月22日 9:37
**/
@Service
public class ItextPdfServiceImpl {
/**
* 下載到本地
* @param stu
* @throws IOException
*/
public void downLoad(ChildInfo stu) throws IOException {
//獲取項(xiàng)目根路徑
String baseUrl=System.getProperty("user.dir")+"/";
//隨機(jī)命名
String templateUUId = UUID.randomUUID().toString();
//生成的pdf路徑+名稱
String pdf = baseUrl+templateUUId+".pdf";
//1、創(chuàng)建流對象
PdfWriter pdfWriter=new PdfWriter(new File(pdf));
//2、創(chuàng)建文檔對象
PdfDocument pdfDocument=new PdfDocument(pdfWriter);
//3、創(chuàng)建內(nèi)容文檔對象
Document document=new Document(pdfDocument);
//創(chuàng)建內(nèi)容
Paragraph paragraph=new Paragraph("報(bào)名信息");
//設(shè)置字體,解決中文顯示問題
PdfFont font= PdfFontFactory.createFont("STSongStd-Light","UniGB-UCS2-H",true);
paragraph.setFont(font);
paragraph.setTextAlignment(TextAlignment.CENTER);//居中
document.add(paragraph);
//設(shè)置表格每列寬度
Table table=new Table(new float[]{108,65,35,50,90,70,40,40,80});
//設(shè)置表格寬度百分比
table.setWidthPercent(100);
//創(chuàng)建表頭
Cell head=new Cell(1,9); //一行9列
//創(chuàng)建標(biāo)題
Color customColor = new DeviceRgb(255, 165, 0); //這是一個(gè)橙色示例,您可以替換為其他RGB值
head.add(new Paragraph("幼兒身份信息"))
.setFont(font) // 設(shè)置字體
.setTextAlignment(TextAlignment.LEFT) // 居左
.setBackgroundColor(customColor); // 設(shè)置自定義背景顏色
Cell cell1=new Cell().add(new Paragraph("姓名").setFont(font));
Cell cell2=new Cell().add(new Paragraph(stu.getStuName()).setFont(font));
Cell cell3=new Cell().add(new Paragraph("性別").setFont(font));
Cell cell4=new Cell().add(new Paragraph(stu.getSex()).setFont(font));
Cell cell5=new Cell().add(new Paragraph("是否獨(dú)生子女").setFont(font));
Cell cell6=new Cell().add(new Paragraph(stu.getOnlyChild()).setFont(font));
Cell cell7=new Cell().add(new Paragraph("血型").setFont(font));
Cell cell8=new Cell().add(new Paragraph(stu.getBlood()).setFont(font));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
table.addCell(cell5);
table.addCell(cell6);
table.addCell(cell7);
table.addCell(cell8);
//加入表格
table.addHeaderCell(head);
table.addHeaderCell(new Cell(1,9));//一行9列
//加入圖片
String picUrl = stu.getChildPic();
Image image=new Image(ImageDataFactory.create(picUrl));
//設(shè)置圖片縮放比例 水平 垂直
//image.scale(0.5f,0.5f);
float scaledWidth =60; // 設(shè)置寬度(毫米)
float scaledHeight = 150; // 設(shè)置高度(毫米)
image.scaleToFit(scaledWidth, scaledHeight);
/**
* 這里解釋一下new Cell(3,1)的意思 相當(dāng)于垂直合并一列的3行單元格
* 其他單元格的合并都是如此進(jìn)行調(diào)試
*/
//將圖片插入表格
Cell cell9 = new Cell(3,1);
cell9.add(image);
table.addCell(cell9);
table.addCell(new Cell().add(new Paragraph("身份證號碼").setFont(font)));
table.addCell(new Cell(1,3).add(new Paragraph(stu.getStuIdCard()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("幼兒出生日期").setFont(font)));
table.addCell(new Cell().add(new Paragraph(stu.getStuDate()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("民族").setFont(font)));
table.addCell(new Cell().add(new Paragraph(stu.getNation()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("幼兒籍貫").setFont(font)));
table.addCell(new Cell(1,7).add(new Paragraph(stu.getNativePlace()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("出生所在地").setFont(font)));
table.addCell(new Cell(1,8).add(new Paragraph(stu.getBirthPlace()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("幼兒戶籍地區(qū)碼").setFont(font)));
table.addCell(new Cell(1,8).add(new Paragraph(stu.getNativeCode()).setFont(font)));
Cell head2=new Cell(1,9); //一行9列
//創(chuàng)建標(biāo)題
Color customColor2 = new DeviceRgb(0,255,0); //這是一個(gè)綠色示例,您可以替換為其他RGB值
head2.add(new Paragraph("家長信息"))
.setFont(font) // 設(shè)置字體
.setTextAlignment(TextAlignment.LEFT) // 居左
.setBackgroundColor(customColor2); // 設(shè)置自定義背景顏色
table.addCell(head2);
table.addCell(new Cell().add(new Paragraph("父母信息").setFont(font)));
table.addCell(new Cell(1,8).add(new Paragraph("爸爸胡英俊,媽媽張小麗").setFont(font)));
//輸出表格
document.add(table);
document.close();
System.out.println("pdf生成完成!");
}
/**
* 生成流返回給瀏覽器
*/
public void downLoadStream(ChildInfo stu, HttpServletResponse response) throws Exception {
OutputStream os = response.getOutputStream();
//1、創(chuàng)建流對象
PdfWriter pdfWriter=new PdfWriter(os);
//2、創(chuàng)建文檔對象
PdfDocument pdfDocument=new PdfDocument(pdfWriter);
//3、創(chuàng)建內(nèi)容文檔對象
Document document=new Document(pdfDocument);
//創(chuàng)建內(nèi)容
Paragraph paragraph=new Paragraph("報(bào)名信息");
//設(shè)置字體,解決中文顯示問題
PdfFont font= PdfFontFactory.createFont("STSongStd-Light","UniGB-UCS2-H",true);
paragraph.setFont(font);
paragraph.setTextAlignment(TextAlignment.CENTER);//居中
document.add(paragraph);
//設(shè)置表格每列寬度
Table table=new Table(new float[]{108,65,35,50,90,70,40,40,80});
//設(shè)置表格寬度百分比
table.setWidthPercent(100);
//創(chuàng)建表頭
Cell head=new Cell(1,9); //一行9列
//創(chuàng)建標(biāo)題
Color customColor = new DeviceRgb(255, 165, 0); //這是一個(gè)橙色示例,您可以替換為其他RGB值
head.add(new Paragraph("幼兒身份信息"))
.setFont(font) // 設(shè)置字體
.setTextAlignment(TextAlignment.LEFT) // 居左
.setBackgroundColor(customColor); // 設(shè)置自定義背景顏色
Cell cell1=new Cell().add(new Paragraph("姓名").setFont(font));
Cell cell2=new Cell().add(new Paragraph(stu.getStuName()).setFont(font));
Cell cell3=new Cell().add(new Paragraph("性別").setFont(font));
Cell cell4=new Cell().add(new Paragraph(stu.getSex()).setFont(font));
Cell cell5=new Cell().add(new Paragraph("是否獨(dú)生子女").setFont(font));
Cell cell6=new Cell().add(new Paragraph(stu.getOnlyChild()).setFont(font));
Cell cell7=new Cell().add(new Paragraph("血型").setFont(font));
Cell cell8=new Cell().add(new Paragraph(stu.getBlood()).setFont(font));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
table.addCell(cell5);
table.addCell(cell6);
table.addCell(cell7);
table.addCell(cell8);
//加入表格
table.addHeaderCell(head);
table.addHeaderCell(new Cell(1,9));//一行9列
//加入圖片
String picUrl = stu.getChildPic();
Image image=new Image(ImageDataFactory.create(picUrl));
//設(shè)置圖片縮放比例 水平 垂直
//image.scale(0.5f,0.5f);
float scaledWidth =60; // 設(shè)置寬度(毫米)
float scaledHeight = 150; // 設(shè)置高度(毫米)
image.scaleToFit(scaledWidth, scaledHeight);
/**
* 這里解釋一下new Cell(3,1)的意思 相當(dāng)于垂直合并一列的3行單元格
* 其他單元格的合并都是如此進(jìn)行調(diào)試
*/
//將圖片插入表格
Cell cell9 = new Cell(3,1);
cell9.add(image);
table.addCell(cell9);
table.addCell(new Cell().add(new Paragraph("身份證號碼").setFont(font)));
table.addCell(new Cell(1,3).add(new Paragraph(stu.getStuIdCard()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("幼兒出生日期").setFont(font)));
table.addCell(new Cell().add(new Paragraph(stu.getStuDate()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("民族").setFont(font)));
table.addCell(new Cell().add(new Paragraph(stu.getNation()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("幼兒籍貫").setFont(font)));
table.addCell(new Cell(1,7).add(new Paragraph(stu.getNativePlace()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("出生所在地").setFont(font)));
table.addCell(new Cell(1,8).add(new Paragraph(stu.getBirthPlace()).setFont(font)));
table.addCell(new Cell().add(new Paragraph("幼兒戶籍地區(qū)碼").setFont(font)));
table.addCell(new Cell(1,8).add(new Paragraph(stu.getNativeCode()).setFont(font)));
Cell head2=new Cell(1,9); //一行9列
//創(chuàng)建標(biāo)題
Color customColor2 = new DeviceRgb(0,255,0); //這是一個(gè)綠色示例,您可以替換為其他RGB值
head2.add(new Paragraph("家長信息"))
.setFont(font) // 設(shè)置字體
.setTextAlignment(TextAlignment.LEFT) // 居左
.setBackgroundColor(customColor2); // 設(shè)置自定義背景顏色
table.addCell(head2);
table.addCell(new Cell().add(new Paragraph("父母信息").setFont(font)));
table.addCell(new Cell(1,8).add(new Paragraph("爸爸胡英俊,媽媽張小麗").setFont(font)));
//輸出表格
document.add(table);
// 設(shè)置響應(yīng)頭信息
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment;filename="+new String(stu.getStuName().getBytes("gb2312"),"iso-8859-1") + ".pdf");
// 關(guān)閉文檔,此時(shí)PDF內(nèi)容已寫入到HttpServletResponse的OutputStream
document.close();
os.close();
System.out.println("pdf生成完成!");
}
}4.調(diào)用示例 controller調(diào)用
package com.example.demo.itext;
import com.example.demo.entity.ChildInfo;
import com.example.demo.service.impl.ItextPdfServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
/**
* @Author: Mr.Z
* @Date: 2024年03月22日 9:36
**/
@RestController
@RequestMapping("/itext")
public class ItextPdfController {
@Autowired
private ItextPdfServiceImpl itextPdfService;
@GetMapping("/download")
public void downLoad(HttpServletResponse response) throws Exception {
ChildInfo childInfo = new ChildInfo();
childInfo.setStuName("胡圖圖");
childInfo.setSex("男");
childInfo.setOnlyChild("是");
childInfo.setBlood("O");
childInfo.setStuIdCard("123456789987654321");
childInfo.setStuDate("2018-05-20");
childInfo.setNation("漢");
childInfo.setNativePlace("翻斗花園");
childInfo.setBirthPlace("翻斗人民醫(yī)院");
childInfo.setNativeCode("8899");
childInfo.setChildPic("https://img2.baidu.com/it/u=294455873,3061678111&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1711213200&t=a29267da1ffde9810763fb027091cee0");
itextPdfService.downLoadStream(childInfo,response);
}
}總結(jié)
到此這篇關(guān)于java通過itext生成pdf的文章就介紹到這了,更多相關(guān)java itext生成pdf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)AOP功能的封裝與配置的小框架實(shí)例代碼
這篇文章主要介紹了Java實(shí)現(xiàn)AOP功能的封裝與配置的小框架實(shí)例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
Java中的轉(zhuǎn)換流InputStreamReader解讀
InputStreamReader是Java.io包中的一個(gè)類,用于將字節(jié)輸入流轉(zhuǎn)換為字符輸入流,它繼承自java.io.Reader類,提供了兩種構(gòu)造方法,可以使用默認(rèn)或指定字符集創(chuàng)建實(shí)例,常用方法包括讀取字符、判斷是否準(zhǔn)備好讀取數(shù)據(jù)和關(guān)閉流2024-09-09
Java并發(fā)編程Callable與Future的應(yīng)用實(shí)例代碼
這篇文章主要介紹了Java并發(fā)編程Callable與Future的應(yīng)用實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
spring boot實(shí)戰(zhàn)之使用JSP的示例
本篇文章主要介紹了spring boot實(shí)戰(zhàn)之使用JSP的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
Java中的服務(wù)發(fā)現(xiàn)與負(fù)載均衡及Eureka與Ribbon的應(yīng)用小結(jié)
這篇文章主要介紹了Java中的服務(wù)發(fā)現(xiàn)與負(fù)載均衡:Eureka與Ribbon的應(yīng)用,通過使用Eureka和Ribbon,我們可以在Java項(xiàng)目中實(shí)現(xiàn)高效的服務(wù)發(fā)現(xiàn)和負(fù)載均衡,需要的朋友可以參考下2024-08-08
Java業(yè)務(wù)中臺確保數(shù)據(jù)一致性的解決方案
數(shù)據(jù)一致性通常指關(guān)聯(lián)數(shù)據(jù)之間的邏輯關(guān)系是否正確和完整。而數(shù)據(jù)存儲的一致性模型則可以認(rèn)為是存儲系統(tǒng)和數(shù)據(jù)使用者之間的一種約定。如果使用者遵循這種約定,則可以得到系統(tǒng)所承諾的訪問結(jié)果2021-10-10
淺析Spring Boot中的spring-boot-load模塊
spring-boot-loader模塊允許我們使用java -jar archive.jar運(yùn)行包含嵌套依賴jar的jar或者war文件,它提供了三種類啟動器。下面通過本文給大家介紹spring-boot-load模塊的相關(guān)知識,感興趣的朋友一起看看吧2018-01-01
探索分析Redis?AOF日志與數(shù)據(jù)持久性
這篇文章主要為大家介紹了探索分析Redis?AOF日志與數(shù)據(jù)持久性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12

