Java用itextpdf導出PDF方法(通俗易懂)
前言
在java開發(fā)的過程中會遇到太多太多文檔pdf導出,excle導出等業(yè)務場景,時隔三個月或半年來一次每一次遇到這樣的業(yè)務場景對我都是非常痛苦的過程,本文旨在記錄工具類使用方法和技術分享。
一、itextpdf是什么?

itextpdf是一個開源的Java庫,用于創(chuàng)建和操作PDF文檔。使用itextpdf,您可以創(chuàng)建新的PDF文檔或修改現(xiàn)有文檔,添加文本和圖像,創(chuàng)建表單等等。該庫提供了廣泛的功能,并經(jīng)常用于企業(yè)級應用程序中根據(jù)用戶輸入動態(tài)生成復雜的PDF文檔。它具有各種許可證選項,具體取決于您的用例,范圍從AGPL到商業(yè)許可證。
itextpdf庫提供了大量的方法和功能,以下是一些常用的方法:
- 創(chuàng)建PDF文檔和頁面:使用PdfWriter和Document對象可以創(chuàng)建一個新的PDF文檔并添加頁面。
- 添加內(nèi)容到PDF文檔:使用Paragraph、Phrase和Chunk對象可以向PDF文檔中添加文本內(nèi)容。同時,也可以添加圖片、表格等其它類型的內(nèi)容。
- 創(chuàng)建表格:使用PdfPTable對象可以創(chuàng)建表格,并向其中添加行和單元格。
- 設置頁眉頁腳:使用HeaderFooter對象可以設置PDF文檔的頁眉和頁腳,以及頁碼等信息。
- 創(chuàng)建書簽:使用PdfOutline對象可以創(chuàng)建PDF文檔的書簽,方便用戶在瀏覽器中導航。
- 導出PDF文檔:使用PdfWriter對象可以將PDF文檔導出為文件或流。
二、快速開始
1.廢話不多說,效果先上一波
下列數(shù)據(jù)均為測試虛擬數(shù)據(jù),不具有任何真實性

2.依賴引入
<!--itext5-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.11</version>
</dependency>3.模版加載

rescources-templates-創(chuàng)建一個pdf模版,如果沒有定制內(nèi)容,直接為空白即可
3.1模版加載工具類PDF
/**
* 字體對象
*/
public static BaseFont bfChinese;
/**
* 定義全局的字體靜態(tài)變量
*/
public static Font titlefont;
public static Font titleSecondFont;
public static Font headfont;
public static Font secondHeadfont;
public static Font textfont;
public static Font secondTitleFont;
public static Font itemFont;
public static Font paragraphFont;
public static Font tableCellFont;
public static Font accessoryFont;
/**
* 間距
*/
public static String shortSpacing = " ";
public static String mediumSpacing = " ";
public static String longSpacing = " ";
public static String maxLongSpacing = " ";
public static String shortSlash = " / ";
public static String mediumSlash = " / ";
public static String longSlash = " / ";
public static String maxLongSlash = " / ";
/**
* 模版
*/
public static String ht;
public static String scan;
public static String htScan;
public static String over;
public static String htSign;
public static String signatureHt;
public static File htFile;
public static File overFile;
public static File htSignFile;
/**
* 初始化字體及勾選、未勾選圖標
*/
static {
try {
// 不同字體(這里定義為同一種字體:包含不同字號、不同style)
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, Font.NORMAL);
titleSecondFont = new Font(bfChinese, 14, Font.NORMAL);
headfont = new Font(bfChinese, 14, Font.BOLD);
secondHeadfont = new Font(bfChinese, 15, Font.BOLD);
textfont = new Font(bfChinese, 16, Font.NORMAL);
secondTitleFont = new Font(bfChinese,18,Font.BOLD);
itemFont = new Font(bfChinese,16,Font.BOLD);
paragraphFont = new Font(bfChinese,11,Font.NORMAL);
accessoryFont = new Font(bfChinese,13,Font.NORMAL);
tableCellFont = new Font(bfChinese,9,Font.NORMAL);
/**
* 判斷當前環(huán)境
*/
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")||osName.contains("mac")) {
ht = getResourceBasePath() + "\\templates\\ht.pdf";
htFile = new File(ht);
} else { //todo: linux或unbunt
ht = "/mnt/jar/spring-cloud/ht.pdf";
htFile = new File(ht);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取項目根路徑
*
* @return
*/
public static String getResourceBasePath() {
// 獲取根目錄
File path = null;
try {
path = new File(ResourceUtils.getURL("classpath:").getPath());
} catch (FileNotFoundException e) {
}
if (path == null || !path.exists()) {
path = new File("");
}
//todo: 就獲取第三步中模版所在的位置,請看上列中 “3.模版加載里的內(nèi)容”
File file = new File(path.getAbsolutePath() + "\\templates");
if (!file.exists()){
return path.getAbsolutePath().replace("xx","xx");
}
return path.getAbsolutePath();
}4.PDF操作工具類方法
public static PdfPTable createTable() throws DocumentException {
PdfPTable table = new PdfPTable(2);
// 設置總寬度
table.setTotalWidth(490);
table.setLockedWidth(true);
// 設置每一列寬度
table.setTotalWidth(new float[] {240,240});
table.setLockedWidth(true);
return table;
}
public PdfPTable createTable(int numColumns) {
PdfPTable table = new PdfPTable(numColumns);
// 設置總寬度
table.setTotalWidth(490);
table.setLockedWidth(true);
return table;
}
public static PdfPTable createTitleTable(int numColumns,Font font, String ... titles) {
PdfPTable table = new PdfPTable(numColumns);
// 設置總寬度
table.setTotalWidth(490);
table.setLockedWidth(true);
for (String title : titles) {
addTitleCell(table,title,1,font);
}
return table;
}
/**
* 添加居中 title
* @param document
* @param text
* @throws DocumentException
* todo: 字體大小16px
*/
public static void addTitle(Document document, String text, int alignment) throws DocumentException {
Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 16, Font.NORMAL));
paragraph.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(0); //設置左縮進
paragraph.setIndentationRight(0); //設置右縮進
paragraph.setFirstLineIndent(0); //設置首行縮進
paragraph.setLeading(10f); //行間距
paragraph.setSpacingBefore(10f); //設置段落上空白
paragraph.setSpacingAfter(10f); //設置段落下空白
document.add(paragraph);
}
/**
* 添加一級標題
* @param document
* @param text
* @throws DocumentException
*/
public static void addFirstTitle(Document document,String text,int alignment) throws DocumentException {
Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 14, Font.NORMAL));
paragraph.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(0); //設置左縮進
paragraph.setIndentationRight(0); //設置右縮進
paragraph.setFirstLineIndent(0); //設置首行縮進
paragraph.setLeading(7f); //行間距
paragraph.setSpacingBefore(20f); //設置段落上空白
paragraph.setSpacingAfter(7f); //設置段落下空白
document.add(paragraph);
}
/**
* 添加二級標題
* @param document
* @param text
* @throws DocumentException
*/
public static void addSecondTitle(Document document,String text,Font font,int alignment) throws DocumentException {
Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 12, Font.NORMAL));
paragraph.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(9); //設置左縮進
paragraph.setIndentationRight(0); //設置右縮進
paragraph.setFirstLineIndent(9); //設置首行縮進
paragraph.setLeading(15f); //行間距
paragraph.setSpacingBefore(10f); //設置段落上空白
paragraph.setSpacingAfter(5f); //設置段落下空白
document.add(paragraph);
}
/**
* 添加分割線
* @param document
* @throws DocumentException
*/
public static void addLine(Document document) throws DocumentException {
LineSeparator ls = new LineSeparator();
ls.setLineWidth(1);
ls.setLineColor(new BaseColor(179,180,164));
Chunk chunk = new Chunk(ls);
document.add(chunk);
}
public static void addNoBorderCell(PdfPTable table,String text) {
PdfPCell cell = new PdfPCell(new Paragraph(text,paragraphFont));
cell.setBorderWidth(0);
cell.setLeading(24,0); //行間距
table.addCell(cell);
}
public static void addTitleCell(PdfPTable table,String text,float borderWidth,Font font) {
Paragraph paragraph = new Paragraph(text, font);
paragraph.setAlignment(1);
paragraph.setLeading(5f);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(borderWidth);
cell.setBackgroundColor(new BaseColor(245,247,251));
cell.setHorizontalAlignment(1);
cell.setVerticalAlignment(1);
table.addCell(cell);
}
public static void addCell(PdfPTable table,String text,float borderWidth,Font font) {
if (StringUtils.isBlank(text)) {
text = " ";
}
Paragraph paragraph = new Paragraph(text, font);
paragraph.setAlignment(1);
PdfPCell cell = new PdfPCell(paragraph);
//水平居中和垂直居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setUseAscender(true);
table.addCell(cell);
}
public static void addCell(PdfPTable table, BigDecimal amount, float borderWidth, Font font) {
Paragraph paragraph = null;
if (Objects.isNull(amount)) {
paragraph = new Paragraph(" ",font);
} else {
paragraph = new Paragraph(amount.toString(),font);
}
paragraph.setAlignment(1);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(borderWidth);
//水平居中和垂直居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setUseAscender(true);
table.addCell(cell);
}
/**
* 添加二級標題
* @param document
* @param text
* @throws DocumentException
*/
public void addSecondTitle(Document document,String text,int alignment,float spacingBefore,float spacingAfter) throws DocumentException {
Paragraph paragraph10 = new Paragraph(text, secondTitleFont);
paragraph10.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph10.setIndentationLeft(12); //設置左縮進
paragraph10.setIndentationRight(12); //設置右縮進
paragraph10.setFirstLineIndent(32); //設置首行縮進
paragraph10.setLeading(30f); //行間距
paragraph10.setSpacingBefore(1f); //設置段落上空白
paragraph10.setSpacingAfter(15f); //設置段落下空白
document.add(paragraph10);
}
/**
* 添加子項標題
* @param document
* @param text
* @throws DocumentException
*/
public void addItemTitle(Document document,String text) throws DocumentException {
Paragraph paragraph = new Paragraph(text, itemFont);
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
paragraph.setSpacingBefore(1f); //設置段落上空白
paragraph.setSpacingAfter(1f); //設置段落下空白
document.add(paragraph);
}
/**
* 添加段落 自動換行
*/
public void addTextParagraph(Document document,String text) throws DocumentException {
Paragraph paragraph = new Paragraph(text,paragraphFont);
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
document.add(paragraph);
}
/**
* 添加段落 自動換行
*/
public Paragraph createTextParagraph() throws DocumentException {
Paragraph paragraph = new Paragraph("",paragraphFont);
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
return paragraph;
}
/**
* 添加段落 自動換行
*/
public Paragraph createTextParagraph(String text) throws DocumentException {
Paragraph paragraph = new Paragraph(text,paragraphFont);
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
return paragraph;
}
/**
* 創(chuàng)建段落 自動換行
*/
public Paragraph createTextParagraph(String text,int alignment) {
Paragraph paragraph = new Paragraph(text,paragraphFont);
paragraph.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
return paragraph;
}
public void appendParagraph(Document document,Paragraph paragraph,String text) throws DocumentException {
paragraph.add(text);
document.add(paragraph);
}
/**
* 添加下劃線
*/
public Paragraph addUnderLine(Paragraph paragraph,String text){
if (StringUtils.isBlank(text)){
text = shortSpacing;
} else {
text = StringUtils.join(" ",text," ");
}
Chunk sigUnderline = new Chunk(text);
sigUnderline.setUnderline(0.1f, -2f);
paragraph.add(sigUnderline);
return paragraph;
}
/**
* 添加下劃線
*/
public void addUnderLine(Document document,Paragraph paragraph,String text) throws DocumentException {
if (StringUtils.isBlank(text)){
text = shortSpacing;
}
Chunk sigUnderline = new Chunk(StringUtils.join(" ",text," "));
sigUnderline.setUnderline(0.1f, -2f);
paragraph.add(sigUnderline);
document.add(paragraph);
}
/**objStmMark = null
* 追加簽名
*/
public File mergePdf(String [] files,String savePath){
PdfReader pdfReader = null;
Document document = null;
try {
//創(chuàng)建一個與a.pdf相同紙張大小的document
pdfReader = new PdfReader(files[0]);
document = new Document(pdfReader.getPageSize(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream(savePath));
document.open();
for (int i = 0; i < files.length; i++) {
//一個一個的遍歷現(xiàn)有的PDF
PdfReader reader = new PdfReader(files[i]);
int n = reader.getNumberOfPages();//PDF文件總共頁數(shù)
System.out.println("n:"+n);
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
reader.close();
}
document.close();
pdfReader.close();
return new File(savePath);
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
document.close();
pdfReader.close();
}
return null;
}
/**
* 添加下劃線
*/
public Paragraph addUnderLine(Boolean check,Paragraph paragraph,String text1,String text2){
Chunk sigUnderline = null;
if (check){
if (Objects.isNull(text1)){
text1 = shortSpacing;
} else {
text1 = StringUtils.join(" ",text1," ");
}
sigUnderline = new Chunk(text1);
} else {
if (Objects.isNull(text2)){
text2 = shortSpacing;
} else {
text2 = StringUtils.join(" ",text2," ");
}
sigUnderline = new Chunk(text2);
}
sigUnderline.setUnderline(0.1f, -2f);
paragraph.add(sigUnderline);
return paragraph;
}
/**
* 添加下劃線
*/
public void addUnderLine(Document document,Boolean check,Paragraph paragraph,String text1,String text2) throws DocumentException {
Chunk sigUnderline = null;
if (check){
if (Objects.isNull(text1)){
text1 = shortSpacing;
} else {
text1 = StringUtils.join(" ",text1," ");
}
sigUnderline = new Chunk(text1);
} else {
if (Objects.isNull(text2)){
text2 = shortSpacing;
} else {
text2 = StringUtils.join(" ",text2," ");
}
sigUnderline = new Chunk(text2);
}
sigUnderline.setUnderline(0.1F, -2.0F);
paragraph.add(sigUnderline);
document.add(paragraph);
}
/**
* 添加下劃線 Chunk
*/
public Chunk createUnderLineChunk(String text) {
if (Objects.isNull(text)){
text = shortSpacing;
} else {
text = StringUtils.join(" ",text," ");
}
Chunk sigUnderline = new Chunk(text);
sigUnderline.setUnderline(0.1f, -2f);
return sigUnderline;
}
private Document createDocument() throws IOException {
// 1.新建document對象 建立一個Document對象
Document document = new Document(PageSize.A4);
//
PdfUtils.htFile.createNewFile();
// 3.打開文檔
document.open();
document.addTitle("銷售合同");// 標題
document.addAuthor("chuz");// 作者
document.addSubject("Subject@iText pdf sample");// 主題
document.addKeywords("Keywords@iTextpdf");// 關鍵字
document.addCreator("chuz develop");// 創(chuàng)建者
return document;
}
/**
* 添加下劃線 Chunk
*/
public Chunk createUnderLineChunk(Boolean check,String text1,String text2) throws DocumentException {
Chunk sigUnderline = null;
if (check){
if (Objects.isNull(text1)){
text1 = shortSpacing;
} else {
text1 = StringUtils.join(" ",text1," ");
}
sigUnderline = new Chunk(text1);
} else {
if (Objects.isNull(text2)){
text2 = shortSpacing;
} else {
text2 = StringUtils.join(" ",text2," ");
}
sigUnderline = new Chunk(text2);
}
sigUnderline.setUnderline(0.1f, -2f);
return sigUnderline;
}
/**
* 添加下劃線 Chunk
*/
public Chunk createChunk(String text) throws DocumentException {
if (StringUtils.isBlank(text)){
text = shortSpacing;
}
text = StringUtils.join(" ",text," ");
return new Chunk(text);
}
/**
* 添加帶選擇框文本
*/
// public void addCheck(Document document,Boolean check,String text) throws Exception {
// Paragraph paragraph = createTextParagraph("");
// if (check){
// paragraph.add(new Chunk(checkPng,0,0,true));
// } else {
// paragraph.add(new Chunk(unCheckPng,0,0,true));
// }
// Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont);
// paragraph.add(chunk);
// document.add(paragraph);
// }
/**
* 添加帶選擇框文本
*/
// public void addCheck(Paragraph paragraph,Boolean check,String text) throws Exception {
// if (check){
// paragraph.add(new Chunk(checkPng,0,0,true));
// } else {
// paragraph.add(new Chunk(unCheckPng,0,0,true));
// }
// Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont);
// paragraph.add(chunk);
// }
/**
* 添加帶選擇框文本
*/
// public Paragraph addCheck(Boolean check,String text) throws Exception {
// Paragraph paragraph = createTextParagraph("");
// if (check){
// paragraph.add(new Chunk(checkPng,0,0,true));
// } else {
// paragraph.add(new Chunk(unCheckPng,0,0,true));
// }
// Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont);
// paragraph.add(chunk);
// return paragraph;
// }
/**
* 添加帶選擇框文本
*/
// public Paragraph appendCheck(Paragraph paragraph,Boolean check,String text) throws Exception {
// if (check){
// paragraph.add(new Chunk(checkPng,0,0,true));
// } else {
// paragraph.add(new Chunk(unCheckPng,0,0,true));
// }
// Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont);
// paragraph.add(chunk);
// return paragraph;
// }
public void packageDateParagraph(Document document, Paragraph paragraph, Date date) throws DocumentException {
if (Objects.nonNull(date)){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
addUnderLine(paragraph,StringUtils.join(year));
paragraph.add("年");
addUnderLine(paragraph,StringUtils.join(month));
paragraph.add("月");
addUnderLine(paragraph,StringUtils.join(day));
paragraph.add("日");
} else {
addUnderLine(paragraph,StringUtils.join(shortSlash));
paragraph.add("年");
addUnderLine(paragraph,StringUtils.join(shortSlash));
paragraph.add("月");
addUnderLine(paragraph,StringUtils.join(shortSlash));
paragraph.add("日");
}
document.add(paragraph);
}
public MultipartFile fileToMultipartFile(File file) {
FileItem fileItem = createFileItem(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
}
public static FileItem createFileItem(File file) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
public String precision(BigDecimal number){
if (Objects.nonNull(number)){
return number.setScale(0,BigDecimal.ROUND_DOWN).toString();
}
return null;
}5.完整代碼
5.1前端代碼-Vue
downloadPdf(){
api.downloadPdf({
fileName: this.data.contractName+'.pdf',
params: {type:'0',contractId:this.data.id}
})
},5.2控制層代碼
@GetMapping(value = "create")
public void create(@ApiParam(value = "0:銷售合同,1:第三方合同") @RequestParam(name = "type") String type,
@RequestParam(name = "contractId") String contractId,
HttpServletResponse response) throws IOException {
File pdfFile = null;
if ("0".equals(type)) {
/* 合同條款 */
//到業(yè)務方法 xx代替,這里主要是根據(jù)條件查詢從表信息
List<xxx> 1 =getXXX();
//設計到業(yè)務方法 xx代替,這里主要是根據(jù)條件查詢從表信息
List<xxx> 1 =getXXX();
// 儀表經(jīng)驗計費條款
List<xxx> 1 =getXXX();
/* 其它費用 */
List<xxx> 1 =getXXX();
//導出方法
pdfFile = contractPdfService.createContractInfo(createContractInfo);
}
response.setContentType("application/pdf");
if (pdfFile.exists()) {
FileInputStream in = new FileInputStream(pdfFile);
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024 * 5];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
out.flush();
in.close();
out.close();
}
}5.3業(yè)務層代碼
public File createContractInfo(CreateContractInfo contractInfo){
try {
// 1.新建document對象 建立一個Document對象
Document document = new Document(PageSize.A4);
PdfUtils.htFile.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PdfUtils.htFile));
// 3.打開文檔
document.open();
document.addTitle(contractInfo.getContractName());// 標題
document.addAuthor("chuz");// 作者
document.addSubject("Subject@iText pdf sample");// 主題
document.addKeywords("Keywords@iTextpdf");// 關鍵字
document.addCreator("chuz develop");// 創(chuàng)建者
// 4.向文檔中添加內(nèi)容
generatePDF(document,contractInfo);
// 5.關閉文檔
document.close();
writer.close();
return PdfUtils.htFile;
} catch (Exception e) {
e.printStackTrace();
}
return PdfUtils.htFile;
}
// 生成PDF文件
public void generatePDF(Document document,CreateContractInfo contractInfo) throws Exception {
//添加總標題,
PdfUtils.addTitle(document,contractInfo.getContractName(),1);
// 基本信息-一級標題
PdfUtils.addFirstTitle(document,"(一)基本信息",0);
PdfPTable table = PdfUtils.createTable();
PdfUtils.addNoBorderCell(table,StringUtils.join("合同編號:",contractInfo.getContractNo()));
PdfUtils.addNoBorderCell(table,StringUtils.join("出租方:",contractInfo.getFirstPartyName()));
PdfUtils.addNoBorderCell(table,StringUtils.join("出租方:",contractInfo.getFirstPartyName()));
PdfUtils.addNoBorderCell(table,StringUtils.join("租賃方:",contractInfo.getPartyBName()));
PdfUtils.addNoBorderCell(table,StringUtils.join("經(jīng)辦人:",contractInfo.getHandledByName()));
PdfUtils.addNoBorderCell(table,StringUtils.join("簽訂日期:", DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd,contractInfo.getSigningTime())));
PdfUtils.addNoBorderCell(table,StringUtils.join("業(yè)態(tài):",contractInfo.getContractTypeName()));
PdfUtils.addNoBorderCell(table,StringUtils.join("意向來源:",dictTrans("customer_source",contractInfo.getContractSource())));
PdfUtils.addNoBorderCell(table,StringUtils.join("合同標簽:",contractInfo.getContractLabel()));
PdfUtils.addNoBorderCell(table,StringUtils.join("租賃日期:",StringUtils.join(
DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd,contractInfo.getStartTime()),
"~",
DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd,contractInfo.getEndTime()))));
document.add(table);
PdfUtils.addLine(document);
// 合同條款-一級標題
PdfUtils.addFirstTitle(document,"(二)合同條款",0);
PdfUtils.addSecondTitle(document,"合同計費條款",PdfUtils.titleSecondFont,0);
PdfPTable itemTable = PdfUtils.createTitleTable(5,PdfUtils.tableCellFont,"資源","收費項","計費方式","計費周期","計算方式");
for (FreeContractClauseDto contractClauseDto : contractInfo.getContractClauseDtos()) {
PdfUtils.addCell(itemTable,contractClauseDto.getHouseName(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(itemTable,contractClauseDto.getSetName(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(itemTable,dictTrans("free_calculate_way",contractClauseDto.getCalculateWay()),1,PdfUtils.tableCellFont);
PdfUtils.addCell(itemTable,dictTrans("charging_cycle",contractClauseDto.getChargingCycle()),1,PdfUtils.tableCellFont);
PdfUtils.addCell(itemTable,contractClauseDto.getFreeRemarks(),1,PdfUtils.tableCellFont);
}
document.add(itemTable);
PdfUtils.addSecondTitle(document,"儀表/經(jīng)營計費條款",PdfUtils.titleSecondFont,0);
PdfPTable deviceTable = PdfUtils.createTitleTable(4,PdfUtils.tableCellFont,"資源","收費項","計費方式","儀表/錄數(shù)項");
for (FreeContractClauseDto deviceContractClauseDto : contractInfo.getDeviceContractClauseDtos()) {
PdfUtils.addCell(deviceTable,deviceContractClauseDto.getHouseName(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(deviceTable,deviceContractClauseDto.getSetName(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(deviceTable,deviceContractClauseDto.getChargeStandard(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(deviceTable,deviceContractClauseDto.getMeterNo(),1,PdfUtils.tableCellFont);
}
document.add(deviceTable);
PdfUtils.addSecondTitle(document,"其他費用添加",PdfUtils.titleSecondFont,0);
PdfPTable elseFreeTable = PdfUtils.createTitleTable(8,PdfUtils.tableCellFont,"資源","收費項","應收(元)","實收(元)","欠收(元)","應收日期","賬期","備注");
for (FreeBillDetailVo elseFreeBillDetailVo : contractInfo.getElseFreeBillDetailVos()) {
PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getHouseName(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(elseFreeTable,"收費項",1,PdfUtils.tableCellFont);
PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getOughtAmount(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getPracticalAmount(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getOweAmount(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(elseFreeTable,DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd,elseFreeBillDetailVo.getOughtDate()),1,PdfUtils.tableCellFont);
PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getPeriod(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(elseFreeTable,elseFreeBillDetailVo.getRemarks(),1,PdfUtils.tableCellFont);
}
document.add(elseFreeTable);
PdfUtils.addLine(document);
// 其它約定
PdfUtils.addFirstTitle(document,"(三)其它約定",0);
PdfPTable elseTable = PdfUtils.createTable();
PdfUtils.addNoBorderCell(elseTable,"設施/服務:設施/服務");
PdfUtils.addNoBorderCell(elseTable,"特殊約定:特殊約定");
PdfUtils.addNoBorderCell(elseTable,"違約說明:違約說明");
PdfUtils.addNoBorderCell(elseTable,"");
document.add(elseTable);
PdfUtils.addLine(document);
// 合同賬單-自定義
Paragraph paragraph = new Paragraph("(四)合同賬單", new Font(PdfUtils.bfChinese, 14, Font.NORMAL));
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(0); //設置左縮進
paragraph.setIndentationRight(0); //設置右縮進
paragraph.setFirstLineIndent(0); //設置首行縮進
paragraph.setLeading(7f); //行間距
paragraph.setSpacingBefore(20f); //設置段落上空白
paragraph.setSpacingAfter(25f); //設置段落下空白
document.add(paragraph);
PdfPTable billTable = PdfUtils.createTitleTable(10,PdfUtils.tableCellFont,"費用項目","費用類型","費用標識","賬期","起止時間","應收金額(元)","實收金額(元)","欠費金額(元)","繳費時間","狀態(tài)");
List<FreeBillDetailVo> freeBillDetailVos = contractInfo.getFreeBillDetailVos();
for (FreeBillDetailVo freeBillDetailVo : freeBillDetailVos) {
PdfUtils.addCell(billTable,"租金",1,PdfUtils.tableCellFont);
PdfUtils.addCell(billTable,"租金",1,PdfUtils.tableCellFont);
PdfUtils.addCell(billTable,"周期性收費",1,PdfUtils.tableCellFont);
PdfUtils.addCell(billTable,freeBillDetailVo.getPeriod(),1,PdfUtils.tableCellFont);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateTime=sdf.format(freeBillDetailVo.getBeginTime())+"~"+sdf.format(freeBillDetailVo.getEndTime());
PdfUtils.addCell(billTable,dateTime,1,PdfUtils.tableCellFont);
PdfUtils.addCell(billTable,freeBillDetailVo.getPracticalAmount(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(billTable,freeBillDetailVo.getOughtAmount(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(billTable,freeBillDetailVo.getOweAmount(),1,PdfUtils.tableCellFont);
PdfUtils.addCell(billTable,DateFormatUtil.dateToString(DateFormatUtil.yyyy_MM_dd_HHmmss,freeBillDetailVo.getPayTime()),1,PdfUtils.tableCellFont);
PdfUtils.addCell(billTable,"未結清",1,PdfUtils.tableCellFont);
}
document.add(billTable);
}5.4PDF工具類完整代碼
public class PdfUtils {
public static BaseFont bfChinese;
/**
* 定義全局的字體靜態(tài)變量
*/
public static Font titlefont;
public static Font titleSecondFont;
public static Font headfont;
public static Font secondHeadfont;
public static Font textfont;
public static Font secondTitleFont;
public static Font itemFont;
public static Font paragraphFont;
public static Font tableCellFont;
public static Font accessoryFont;
/**
* 圖標
*/
// public static Image checkPng;
// public static Image unCheckPng;
/**
* 間距
*/
public static String shortSpacing = " ";
public static String mediumSpacing = " ";
public static String longSpacing = " ";
public static String maxLongSpacing = " ";
public static String shortSlash = " / ";
public static String mediumSlash = " / ";
public static String longSlash = " / ";
public static String maxLongSlash = " / ";
/**
* 模版
*/
public static String ht;
public static String scan;
public static String htScan;
public static String over;
public static String htSign;
public static String signatureHt;
public static File htFile;
public static File overFile;
public static File htSignFile;
/**
* 初始化字體及勾選、未勾選圖標
*/
static {
try {
// 不同字體(這里定義為同一種字體:包含不同字號、不同style)
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, Font.NORMAL);
titleSecondFont = new Font(bfChinese, 14, Font.NORMAL);
headfont = new Font(bfChinese, 14, Font.BOLD);
secondHeadfont = new Font(bfChinese, 15, Font.BOLD);
textfont = new Font(bfChinese, 16, Font.NORMAL);
secondTitleFont = new Font(bfChinese,18,Font.BOLD);
itemFont = new Font(bfChinese,16,Font.BOLD);
paragraphFont = new Font(bfChinese,11,Font.NORMAL);
accessoryFont = new Font(bfChinese,13,Font.NORMAL);
tableCellFont = new Font(bfChinese,9,Font.NORMAL);
/**
* 判斷當前環(huán)境
*/
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")||osName.contains("mac")) {
// checkPng = Image.getInstance(getResourceBasePath() + "\\templates\\check.png");
// checkPng.scaleAbsolute(14,12);
// unCheckPng = Image.getInstance(getResourceBasePath() + "\\templates\\unCheck.png");
// unCheckPng.scaleAbsolute(14,12);
ht = getResourceBasePath() + "\\templates\\ht.pdf";
scan = getResourceBasePath() + "\\templates\\scan.pdf";
htScan = getResourceBasePath() + "\\templates\\htScan.pdf";
over = getResourceBasePath() + "\\templates\\over.pdf";
htSign = getResourceBasePath() + "\\templates\\htSign.pdf";
htFile = new File(ht);
overFile = new File(over);
htSignFile = new File(htSign);
} else { //todo: linux或unbunt
// checkPng = Image.getInstance("/mnt/jar/chuz-cloud-school/check.png");
// checkPng.scaleAbsolute(14,12);
// unCheckPng = Image.getInstance("/mnt/jar/chuz-cloud-school/unCheck.png");
// unCheckPng.scaleAbsolute(14,12);
ht = "/mnt/jar/chuz-cloud-school/ht.pdf";
scan = "/mnt/jar/chuz-cloud-school/scan.pdf";
htScan = "/mnt/jar/chuz-cloud-school/htScan.pdf";
over = "/mnt/jar/chuz-cloud-school/over.pdf";
htSign = "/mnt/jar/chuz-cloud-school/htSign.pdf";
htFile = new File(ht);
overFile = new File(over);
htSignFile = new File(htSign);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取項目根路徑
*
* @return
*/
public static String getResourceBasePath() {
// 獲取根目錄
File path = null;
try {
path = new File(ResourceUtils.getURL("classpath:").getPath());
} catch (FileNotFoundException e) {
}
if (path == null || !path.exists()) {
path = new File("");
}
File file = new File(path.getAbsolutePath() + "\\templates");
if (!file.exists()){
return path.getAbsolutePath().replace("chuz-cloud-module\\chuz-cloud-school-start","chuz-boot-module-school");
}
return path.getAbsolutePath();
}
public static PdfPTable createTable() throws DocumentException {
PdfPTable table = new PdfPTable(2);
// 設置總寬度
table.setTotalWidth(490);
table.setLockedWidth(true);
// 設置每一列寬度
table.setTotalWidth(new float[] {240,240});
table.setLockedWidth(true);
return table;
}
public PdfPTable createTable(int numColumns) {
PdfPTable table = new PdfPTable(numColumns);
// 設置總寬度
table.setTotalWidth(490);
table.setLockedWidth(true);
return table;
}
public static PdfPTable createTitleTable(int numColumns,Font font, String ... titles) {
PdfPTable table = new PdfPTable(numColumns);
// 設置總寬度
table.setTotalWidth(490);
table.setLockedWidth(true);
for (String title : titles) {
addTitleCell(table,title,1,font);
}
return table;
}
/**
* 添加居中 title
* @param document
* @param text
* @throws DocumentException
* todo: 字體大小16px
*/
public static void addTitle(Document document, String text, int alignment) throws DocumentException {
Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 16, Font.NORMAL));
paragraph.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(0); //設置左縮進
paragraph.setIndentationRight(0); //設置右縮進
paragraph.setFirstLineIndent(0); //設置首行縮進
paragraph.setLeading(10f); //行間距
paragraph.setSpacingBefore(10f); //設置段落上空白
paragraph.setSpacingAfter(10f); //設置段落下空白
document.add(paragraph);
}
/**
* 添加一級標題
* @param document
* @param text
* @throws DocumentException
*/
public static void addFirstTitle(Document document,String text,int alignment) throws DocumentException {
Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 14, Font.NORMAL));
paragraph.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(0); //設置左縮進
paragraph.setIndentationRight(0); //設置右縮進
paragraph.setFirstLineIndent(0); //設置首行縮進
paragraph.setLeading(7f); //行間距
paragraph.setSpacingBefore(20f); //設置段落上空白
paragraph.setSpacingAfter(7f); //設置段落下空白
document.add(paragraph);
}
/**
* 添加二級標題
* @param document
* @param text
* @throws DocumentException
*/
public static void addSecondTitle(Document document,String text,Font font,int alignment) throws DocumentException {
Paragraph paragraph = new Paragraph(text, new Font(bfChinese, 12, Font.NORMAL));
paragraph.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(9); //設置左縮進
paragraph.setIndentationRight(0); //設置右縮進
paragraph.setFirstLineIndent(9); //設置首行縮進
paragraph.setLeading(15f); //行間距
paragraph.setSpacingBefore(10f); //設置段落上空白
paragraph.setSpacingAfter(5f); //設置段落下空白
document.add(paragraph);
}
/**
* 添加分割線
* @param document
* @throws DocumentException
*/
public static void addLine(Document document) throws DocumentException {
LineSeparator ls = new LineSeparator();
ls.setLineWidth(1);
ls.setLineColor(new BaseColor(179,180,164));
Chunk chunk = new Chunk(ls);
document.add(chunk);
}
public static void addNoBorderCell(PdfPTable table,String text) {
PdfPCell cell = new PdfPCell(new Paragraph(text,paragraphFont));
cell.setBorderWidth(0);
cell.setLeading(24,0); //行間距
table.addCell(cell);
}
public static void addTitleCell(PdfPTable table,String text,float borderWidth,Font font) {
Paragraph paragraph = new Paragraph(text, font);
paragraph.setAlignment(1);
paragraph.setLeading(5f);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(borderWidth);
cell.setBackgroundColor(new BaseColor(245,247,251));
cell.setHorizontalAlignment(1);
cell.setVerticalAlignment(1);
table.addCell(cell);
}
public static void addCell(PdfPTable table,String text,float borderWidth,Font font) {
if (StringUtils.isBlank(text)) {
text = " ";
}
Paragraph paragraph = new Paragraph(text, font);
paragraph.setAlignment(1);
PdfPCell cell = new PdfPCell(paragraph);
//水平居中和垂直居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setUseAscender(true);
table.addCell(cell);
}
public static void addCell(PdfPTable table, BigDecimal amount, float borderWidth, Font font) {
Paragraph paragraph = null;
if (Objects.isNull(amount)) {
paragraph = new Paragraph(" ",font);
} else {
paragraph = new Paragraph(amount.toString(),font);
}
paragraph.setAlignment(1);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(borderWidth);
//水平居中和垂直居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setUseAscender(true);
table.addCell(cell);
}
/**
* 添加二級標題
* @param document
* @param text
* @throws DocumentException
*/
public void addSecondTitle(Document document,String text,int alignment,float spacingBefore,float spacingAfter) throws DocumentException {
Paragraph paragraph10 = new Paragraph(text, secondTitleFont);
paragraph10.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph10.setIndentationLeft(12); //設置左縮進
paragraph10.setIndentationRight(12); //設置右縮進
paragraph10.setFirstLineIndent(32); //設置首行縮進
paragraph10.setLeading(30f); //行間距
paragraph10.setSpacingBefore(1f); //設置段落上空白
paragraph10.setSpacingAfter(15f); //設置段落下空白
document.add(paragraph10);
}
/**
* 添加子項標題
* @param document
* @param text
* @throws DocumentException
*/
public void addItemTitle(Document document,String text) throws DocumentException {
Paragraph paragraph = new Paragraph(text, itemFont);
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
paragraph.setSpacingBefore(1f); //設置段落上空白
paragraph.setSpacingAfter(1f); //設置段落下空白
document.add(paragraph);
}
/**
* 添加段落 自動換行
*/
public void addTextParagraph(Document document,String text) throws DocumentException {
Paragraph paragraph = new Paragraph(text,paragraphFont);
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
document.add(paragraph);
}
/**
* 添加段落 自動換行
*/
public Paragraph createTextParagraph() throws DocumentException {
Paragraph paragraph = new Paragraph("",paragraphFont);
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
return paragraph;
}
/**
* 添加段落 自動換行
*/
public Paragraph createTextParagraph(String text) throws DocumentException {
Paragraph paragraph = new Paragraph(text,paragraphFont);
paragraph.setAlignment(0); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
return paragraph;
}
/**
* 創(chuàng)建段落 自動換行
*/
public Paragraph createTextParagraph(String text,int alignment) {
Paragraph paragraph = new Paragraph(text,paragraphFont);
paragraph.setAlignment(alignment); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(32); //設置首行縮進
paragraph.setLeading(30f); //行間距
return paragraph;
}
public void appendParagraph(Document document,Paragraph paragraph,String text) throws DocumentException {
paragraph.add(text);
document.add(paragraph);
}
/**
* 添加下劃線
*/
public Paragraph addUnderLine(Paragraph paragraph,String text){
if (StringUtils.isBlank(text)){
text = shortSpacing;
} else {
text = StringUtils.join(" ",text," ");
}
Chunk sigUnderline = new Chunk(text);
sigUnderline.setUnderline(0.1f, -2f);
paragraph.add(sigUnderline);
return paragraph;
}
/**
* 添加下劃線
*/
public void addUnderLine(Document document,Paragraph paragraph,String text) throws DocumentException {
if (StringUtils.isBlank(text)){
text = shortSpacing;
}
Chunk sigUnderline = new Chunk(StringUtils.join(" ",text," "));
sigUnderline.setUnderline(0.1f, -2f);
paragraph.add(sigUnderline);
document.add(paragraph);
}
/**objStmMark = null
* 追加簽名
*/
public File mergePdf(String [] files,String savePath){
PdfReader pdfReader = null;
Document document = null;
try {
//創(chuàng)建一個與a.pdf相同紙張大小的document
pdfReader = new PdfReader(files[0]);
document = new Document(pdfReader.getPageSize(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream(savePath));
document.open();
for (int i = 0; i < files.length; i++) {
//一個一個的遍歷現(xiàn)有的PDF
PdfReader reader = new PdfReader(files[i]);
int n = reader.getNumberOfPages();//PDF文件總共頁數(shù)
System.out.println("n:"+n);
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
reader.close();
}
document.close();
pdfReader.close();
return new File(savePath);
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
document.close();
pdfReader.close();
}
return null;
}
/**
* 添加下劃線
*/
public Paragraph addUnderLine(Boolean check,Paragraph paragraph,String text1,String text2){
Chunk sigUnderline = null;
if (check){
if (Objects.isNull(text1)){
text1 = shortSpacing;
} else {
text1 = StringUtils.join(" ",text1," ");
}
sigUnderline = new Chunk(text1);
} else {
if (Objects.isNull(text2)){
text2 = shortSpacing;
} else {
text2 = StringUtils.join(" ",text2," ");
}
sigUnderline = new Chunk(text2);
}
sigUnderline.setUnderline(0.1f, -2f);
paragraph.add(sigUnderline);
return paragraph;
}
/**
* 添加下劃線
*/
public void addUnderLine(Document document,Boolean check,Paragraph paragraph,String text1,String text2) throws DocumentException {
Chunk sigUnderline = null;
if (check){
if (Objects.isNull(text1)){
text1 = shortSpacing;
} else {
text1 = StringUtils.join(" ",text1," ");
}
sigUnderline = new Chunk(text1);
} else {
if (Objects.isNull(text2)){
text2 = shortSpacing;
} else {
text2 = StringUtils.join(" ",text2," ");
}
sigUnderline = new Chunk(text2);
}
sigUnderline.setUnderline(0.1F, -2.0F);
paragraph.add(sigUnderline);
document.add(paragraph);
}
/**
* 添加下劃線 Chunk
*/
public Chunk createUnderLineChunk(String text) {
if (Objects.isNull(text)){
text = shortSpacing;
} else {
text = StringUtils.join(" ",text," ");
}
Chunk sigUnderline = new Chunk(text);
sigUnderline.setUnderline(0.1f, -2f);
return sigUnderline;
}
private Document createDocument() throws IOException {
// 1.新建document對象 建立一個Document對象
Document document = new Document(PageSize.A4);
//
PdfUtils.htFile.createNewFile();
// 3.打開文檔
document.open();
document.addTitle("銷售合同");// 標題
document.addAuthor("chuz");// 作者
document.addSubject("Subject@iText pdf sample");// 主題
document.addKeywords("Keywords@iTextpdf");// 關鍵字
document.addCreator("chuz develop");// 創(chuàng)建者
return document;
}
/**
* 添加下劃線 Chunk
*/
public Chunk createUnderLineChunk(Boolean check,String text1,String text2) throws DocumentException {
Chunk sigUnderline = null;
if (check){
if (Objects.isNull(text1)){
text1 = shortSpacing;
} else {
text1 = StringUtils.join(" ",text1," ");
}
sigUnderline = new Chunk(text1);
} else {
if (Objects.isNull(text2)){
text2 = shortSpacing;
} else {
text2 = StringUtils.join(" ",text2," ");
}
sigUnderline = new Chunk(text2);
}
sigUnderline.setUnderline(0.1f, -2f);
return sigUnderline;
}
/**
* 添加下劃線 Chunk
*/
public Chunk createChunk(String text) throws DocumentException {
if (StringUtils.isBlank(text)){
text = shortSpacing;
}
text = StringUtils.join(" ",text," ");
return new Chunk(text);
}
/**
* 添加帶選擇框文本
*/
// public void addCheck(Document document,Boolean check,String text) throws Exception {
// Paragraph paragraph = createTextParagraph("");
// if (check){
// paragraph.add(new Chunk(checkPng,0,0,true));
// } else {
// paragraph.add(new Chunk(unCheckPng,0,0,true));
// }
// Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont);
// paragraph.add(chunk);
// document.add(paragraph);
// }
/**
* 添加帶選擇框文本
*/
// public void addCheck(Paragraph paragraph,Boolean check,String text) throws Exception {
// if (check){
// paragraph.add(new Chunk(checkPng,0,0,true));
// } else {
// paragraph.add(new Chunk(unCheckPng,0,0,true));
// }
// Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont);
// paragraph.add(chunk);
// }
/**
* 添加帶選擇框文本
*/
// public Paragraph addCheck(Boolean check,String text) throws Exception {
// Paragraph paragraph = createTextParagraph("");
// if (check){
// paragraph.add(new Chunk(checkPng,0,0,true));
// } else {
// paragraph.add(new Chunk(unCheckPng,0,0,true));
// }
// Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont);
// paragraph.add(chunk);
// return paragraph;
// }
/**
* 添加帶選擇框文本
*/
// public Paragraph appendCheck(Paragraph paragraph,Boolean check,String text) throws Exception {
// if (check){
// paragraph.add(new Chunk(checkPng,0,0,true));
// } else {
// paragraph.add(new Chunk(unCheckPng,0,0,true));
// }
// Chunk chunk = new Chunk(StringUtils.join(" ",text),textfont);
// paragraph.add(chunk);
// return paragraph;
// }
public void packageDateParagraph(Document document, Paragraph paragraph, Date date) throws DocumentException {
if (Objects.nonNull(date)){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
addUnderLine(paragraph,StringUtils.join(year));
paragraph.add("年");
addUnderLine(paragraph,StringUtils.join(month));
paragraph.add("月");
addUnderLine(paragraph,StringUtils.join(day));
paragraph.add("日");
} else {
addUnderLine(paragraph,StringUtils.join(shortSlash));
paragraph.add("年");
addUnderLine(paragraph,StringUtils.join(shortSlash));
paragraph.add("月");
addUnderLine(paragraph,StringUtils.join(shortSlash));
paragraph.add("日");
}
document.add(paragraph);
}
public MultipartFile fileToMultipartFile(File file) {
FileItem fileItem = createFileItem(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
}
public static FileItem createFileItem(File file) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
public String precision(BigDecimal number){
if (Objects.nonNull(number)){
return number.setScale(0,BigDecimal.ROUND_DOWN).toString();
}
return null;
}
}總結
解決每一個bug,開發(fā)每一個功能都是對程序員能力上、心里上的修煉。既然翻不過浪浪山,那就要適應浪浪山。
到此這篇關于Java用itextpdf導出PDF的文章就介紹到這了,更多相關Java導出PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringSecurity6自定義JSON登錄的實現(xiàn)
目前最新版的Spring Boot已經(jīng)到了3.0.5了,隨之而來Spring Security 目前的版本也到了6.0.2了,Spring Security寫法的變化特別多,本文就來介紹下,感興趣的可以了解一下2023-12-12
詳解Spring Cloud Config采用Git存儲時兩種常用的配置策略
這篇文章主要介紹了詳解Spring Cloud Config采用Git存儲時兩種常用的配置策略,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
Java簡單實現(xiàn)猜數(shù)字游戲附C語言版本
猜數(shù)字是興起于英國的益智類小游戲,起源于20世紀中期,一般由兩個人或多人玩,也可以由一個人和電腦玩。游戲規(guī)則為一方出數(shù)字,一方猜,今天我們來用Java和C語言分別把這個小游戲?qū)懗鰜砭毦毷?/div> 2021-11-11
Java基于堆結構實現(xiàn)優(yōu)先隊列功能示例
這篇文章主要介紹了Java基于堆結構實現(xiàn)優(yōu)先隊列功能,結合實例形式分析了java優(yōu)先隊列的簡單定義與使用方法,需要的朋友可以參考下2017-11-11
Jackson2的JsonSchema實現(xiàn)java實體類生成json方式
這篇文章主要介紹了Jackson2的JsonSchema實現(xiàn)java實體類生成json,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
springboot+dynamicDataSource動態(tài)添加切換數(shù)據(jù)源方式
這篇文章主要介紹了springboot+dynamicDataSource動態(tài)添加切換數(shù)據(jù)源方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01最新評論

