這篇文章將為大家詳細(xì)講解有關(guān)spring-boot中怎么實(shí)現(xiàn)一個(gè)PDF打印功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

10年的禹王臺(tái)網(wǎng)站建設(shè)經(jīng)驗(yàn),針對(duì)設(shè)計(jì)、前端、開(kāi)發(fā)、售后、文案、推廣等六對(duì)一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。營(yíng)銷型網(wǎng)站建設(shè)的優(yōu)勢(shì)是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整禹王臺(tái)建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無(wú)論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。成都創(chuàng)新互聯(lián)從事“禹王臺(tái)網(wǎng)站設(shè)計(jì)”,“禹王臺(tái)網(wǎng)站推廣”以來(lái),每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。
1.導(dǎo)入jar(一定要注意版本,踩過(guò)很多坑)
<!--pdf依賴--> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.1</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.工具類
package com.sungrow.sgframe.api.isolarapi.machineconfigservice.util;
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 lombok.extern.log4j.Log4j2;
import org.sg.tools.config.SungwsConfig;
import org.sg.tools.util.UUIDUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author shihaifeng
* @date 2019-09-29 11:03
* @desc (PDF工具類)
**/
@Log4j2
public class PDFUtil {
private static Document document = null;// 建立一個(gè)Document對(duì)象
private static int maxWidth = 520;
private static Font headfont;// 設(shè)置字體大小
private static Font keyfont;// 設(shè)置字體大小
private static Font textfont;// 設(shè)置字體大小
static {
BaseFont bfChinese;
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
headfont = new Font(bfChinese, 10, Font.BOLD);// 設(shè)置字體大小
keyfont = new Font(bfChinese, 8, Font.BOLD);// 設(shè)置字體大小
textfont = new Font(bfChinese, 8, Font.NORMAL);// 設(shè)置字體大小
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
}
/**
* 初始化文檔
*/
private static void initDocument(File file) {
document = new Document();//每一次初始化一個(gè)document 不然會(huì)有問(wèn)題 open()方法有問(wèn)題
document.setPageSize(PageSize.A4);// 設(shè)置頁(yè)面大小
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfWriter.getInstance(document, fileOutputStream)
.setViewerPreferences(PdfWriter.PageModeUseThumbs);
document.open();
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
}
/**
* 創(chuàng)建table
*
* @param colNumber
* @return
*/
private static PdfPTable createTable(int colNumber) {
PdfPTable table = new PdfPTable(colNumber);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
return table;
}
/**
* 創(chuàng)建table
*
* @param widths
* @return
*/
private PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
return table;
}
/**
* 創(chuàng)建 空table
*
* @return
*/
private static PdfPCell createBlankTable() {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
Paragraph paragraph = new Paragraph("", getPdfChineseFont());
cell.setPhrase(paragraph);
return cell;
}
/**
* 創(chuàng)建列
*
* @param value
* @param font
* @param align
* @return
*/
private PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
Paragraph paragraph = new Paragraph(String.valueOf(value), getPdfChineseFont());
cell.setPhrase(paragraph);
return cell;
}
/**
* 創(chuàng)建列
*
* @param value
* @param font
* @return
*/
private static PdfPCell createHeadCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBackgroundColor(new BaseColor(22022022));
cell.setFixedHeight(25.0f);
Font headFont = getPdfChineseFont();
headFont.setColor(new BaseColor(0xff0000));
headFont.setSize(14);
headFont.setStyle("bold");
Paragraph paragraph = new Paragraph(String.valueOf(value), headFont);
cell.setPhrase(paragraph);
return cell;
}
/**
* 創(chuàng)建列
*
* @param value
* @param font
* @param rowSpan 占多列
* @param colspan 占多行
* @return
*/
private static PdfPCell createCell(String value, Font font, int rowSpan, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setRowspan(rowSpan);
cell.setColspan(colspan);
Paragraph paragraph = new Paragraph(String.valueOf(value), getPdfChineseFont());
cell.setPhrase(paragraph);
return cell;
}
/**
* 創(chuàng)建列
*
* @param value
* @param font
* @param align
* @param colspan
* @param boderFlag
* @return
*/
private static PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
Paragraph paragraph = new Paragraph(String.valueOf(value), getPdfChineseFont());
cell.setPhrase(paragraph);
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(15.0f);
cell.setPaddingBottom(8.0f);
}
return cell;
}
/**
* 增加中文顯示
*
* @return
*/
private static Font getPdfChineseFont() {
BaseFont bfChinese = null;
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
log.error(e.getMessage(), e);
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
return fontChinese;
}
/**
* 創(chuàng)建pdf
*/
public static String createPDF(Map<String, Object> tittle, List<Object> listObj, Map<String, Object> pojectMap, String language) throws IOException, DocumentException {
File file = null;
try {
String tmpDir = SungwsConfig.INSTANCE.getConfig().get("tmp.dir");//臨時(shí)文件夾
File tmpDirFile = new File(tmpDir);
if (!tmpDirFile.exists()) {
tmpDirFile.mkdir();
}
String fileName = UUIDUtil.getRandomStringByLength(6).toUpperCase();
String fileUrl = tmpDir + File.separator + fileName + ".pdf";
file = new File(fileUrl);
// file.createNewFile();
initDocument(file);
PdfPTable table = createTable(tittle, listObj, pojectMap, language);
document.add(table);
System.out.println("文件創(chuàng)建成功: " + fileUrl);
return fileUrl;
} finally {
if (document != null) {
document.close();
}
}
}
/**
* 組裝table
*
* @param tittle
* @param listObj
* @param pojectMap
* @param language
* @return
*/
private static PdfPTable createTable(Map<String, Object> tittle, List<Object> listObj, Map<String, Object> pojectMap, String language) {
System.out.println("tittle" + tittle);
System.out.println("listObj" + listObj);
AtomicInteger index = new AtomicInteger(1);//記錄下表數(shù)
AtomicInteger allColsSize = new AtomicInteger(0);//記錄總列數(shù)
float width = 100;
float height = 40;
int tittleSize = tittle.size();
PdfPTable table = createTable(tittleSize);
//1 設(shè)置標(biāo)題
tittle.forEach((key, value) -> {
PdfPCell cell = null; //表格的單元格
if ("zh".equals(language)) {
cell = createHeadCell(String.valueOf(value), textfont);
} else {
cell = createHeadCell(key, textfont);
}
table.addCell(cell);
allColsSize.getAndIncrement();
});
//2 設(shè)置 內(nèi)容
listObj.forEach(obj -> {
if (obj instanceof List) {
List<Map> comptents = (List<Map>) obj;
comptents.forEach(comptent -> {
Object obj1 = comptent.get("parts");
AtomicInteger rowSpan1 = new AtomicInteger(0);
List<Map> parts = null;
if (obj1 instanceof List && ((List) obj1).size() > 0) {
//rowSpan1 需要嵌套多層
parts = (List<Map>) obj1;
parts.forEach(part -> {
Object obj2 = part.get("items");
if (obj2 instanceof List && ((List) obj2).size() > 0) {
rowSpan1.addAndGet(((List) obj2).size());
} else {
rowSpan1.addAndGet(1);
}
});
} else {
rowSpan1.addAndGet(1);
}
//添加編號(hào)
PdfPCell cellNo = createCell(String.valueOf(index.getAndIncrement()), textfont, rowSpan1.get(), 1);
table.addCell(cellNo);
//組件
String component_name = String.valueOf(comptent.get("component_name"));
PdfPCell cell1 = createCell(component_name, textfont, rowSpan1.get(), 1);
table.addCell(cell1);
if (parts != null) {
//部件
parts.forEach(part -> {
Object obj2 = part.get("items");
List<Map> items = null;
int rowSpan2 = 1;
if (obj2 instanceof List && ((List) obj2).size() > 0) {
items = (List<Map>) obj2;
rowSpan2 = items.size();
}
//部件Custmization
String part_name = String.valueOf(part.get("part_name"));
PdfPCell cell2 = createCell(part_name, textfont, rowSpan2, 1);
table.addCell(cell2);
if (items != null) {
//item
items.forEach(item -> {
//從標(biāo)題的第三個(gè)key開(kāi)始遍歷titile,獲取數(shù)據(jù)
Set<String> keys = tittle.keySet();
Iterator<String> iterator = keys.iterator();
iterator.next();//排除第一個(gè)NO
iterator.next();//排除第二個(gè)Components
iterator.next();//排除第三個(gè)Items
while (iterator.hasNext()) {
String key = iterator.next();
Object o = item.get(key);
if (o != null) {
PdfPCell cell3 = createCell(String.valueOf(o), textfont, 1, 1);
table.addCell(cell3);
} else {
table.addCell(createBlankTable());
}
}
});
} else {
//剩下的列沒(méi)有數(shù)據(jù)填空
for (int i = 0; i < allColsSize.get() - 3; i++) {
table.addCell(createBlankTable());
}
}
});
} else {
//剩下的列沒(méi)有數(shù)據(jù)填空
for (int i = 0; i < allColsSize.get() - 2; i++) {
table.addCell(createBlankTable());
}
}
});
}
});
//3 設(shè)置消費(fèi)者信息
// table.addCell(createCell("", textfont, 1, allColsSize.get()));//中間空一行
//添加編號(hào)
PdfPCell cellNo = createCell(String.valueOf(index.getAndIncrement()), textfont, 10, 1);
table.addCell(cellNo);
Map<String, Object> projectTitle = (Map<String, Object>) pojectMap.get("projectTitle");//標(biāo)題
Map<String, Object> projectValue = (Map<String, Object>) pojectMap.get("projectValue");//值
//項(xiàng)目概述
table.addCell(createCell(String.valueOf(pojectMap.get("component_name")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectTitle.get("components_name")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("components_name")), textfont, 1, allColsSize.get() - 3));
table.addCell(createCell(String.valueOf(pojectMap.get("customer_inputs")), textfont, 9, 1));
table.addCell(createCell(String.valueOf(projectTitle.get("components_location")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("components_location")), textfont, 1, allColsSize.get() - 3));
table.addCell(createCell(String.valueOf(projectTitle.get("plant_capacity")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("plant_capacity")), textfont, 1, allColsSize.get() - 3));
table.addCell(createCell(String.valueOf(projectTitle.get("site_conditions")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("site_conditions")), textfont, 1, allColsSize.get() - 3));
table.addCell(createCell(String.valueOf(projectTitle.get("altitude")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("altitude")), textfont, 1, allColsSize.get() - 3));
table.addCell(createCell(String.valueOf(projectTitle.get("dc_ac_ratio")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("dc_ac_ratio")), textfont, 1, allColsSize.get() - 3));
table.addCell(createCell(String.valueOf(projectTitle.get("inverter_dc_input_cable")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("inverter_dc_input_cable")), textfont, 1, allColsSize.get() - 3));
table.addCell(createCell(String.valueOf(projectTitle.get("mv_switchgear_output_cable")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("mv_switchgear_output_cable")), textfont, 1, allColsSize.get() - 3));
table.addCell(createCell(String.valueOf(projectTitle.get("grid_voltage")), textfont, 1, 1));
table.addCell(createCell(String.valueOf(projectValue.get("grid_voltage")), textfont, 1, allColsSize.get() - 3));
return table;
}
}關(guān)于spring-boot中怎么實(shí)現(xiàn)一個(gè)PDF打印功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
分享標(biāo)題:spring-boot中怎么實(shí)現(xiàn)一個(gè)PDF打印功能
本文URL:http://www.jbt999.com/article40/jsdjeo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營(yíng)銷、域名注冊(cè)、網(wǎng)站建設(shè)、微信小程序、面包屑導(dǎo)航、搜索引擎優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:[email protected]。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)