当前位置:网站首页>Drawing PDF tables (I) drawing excel table styles in PDF and downloading them through iText (supporting Chinese fonts)
Drawing PDF tables (I) drawing excel table styles in PDF and downloading them through iText (supporting Chinese fonts)
2022-07-25 17:50:00 【Suddenly】
Catalog
Preface
Encapsulating data as excel Table style , And take PDF Download in the form of , have access to Itextpdf To implement , You can also use it Aspose Through the conversion between streams , Reference resources :
《SpringBoot Realization Excel、Word Convert to PDF》
《Aspose Upload Excel、Word Convert to PDF And download 》
1、 introduce POM
<dependencies>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.2.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
</dependencies>
2、 find font
For Chinese Fonts textpdf Writing font names directly is not supported , So you need to specify it manually ttc perhaps ttf Type of font , Need to find the font location installed on this machine , such as :C:\Windows\Fonts, The steps to find the font correctly are as follows :
First step : Get into C:\Windows\Fonts:
Enter the font installation directory ,Windows The default is C:\Windows\Fonts
The second step : View font information
For example, we choose In black , So bold simsun.ttc
3、 Write a tool class
3.1 Font configuration
public class PdfUtils {
/** * Set the default font value * * @return * @throws DocumentException * @throws IOException */
private static BaseFont createBaseFont(String fontName) throws DocumentException, IOException {
// The default is Song typeface
if (fontName == null) {
fontName = "simsun.ttc";
}
String fontPre = fontName.substring(fontName.lastIndexOf(".") + 1);
if (fontPre.equals("ttc")) {
// ttc Format fonts need to be suffixed
fontName = fontName + ",0";
}
String font = FONT_PATH + fontName;
return BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
/** * Set the font * * @return */
public static Font setFont() {
return setFont(null, null, null, null);
}
public static Font setFont(Integer fontSize) {
return setFont(null, fontSize, null, null);
}
public static Font setFont(Integer fontSize, BaseColor fontColor) {
return setFont(null, fontSize, null, fontColor);
}
/** * @param fontName Font name Default Arial * @param fontSize font size Default 12 Number * @param fontStyle Font style * @param fontColor The font color Default black * @return */
public static Font setFont(String fontName, Integer fontSize, Integer fontStyle, BaseColor fontColor) {
try {
BaseFont baseFont = createBaseFont(fontName);
Font font = new Font(baseFont);
if (fontSize != null) {
font.setSize(fontSize);
}
if (fontStyle != null) {
font.setStyle(fontStyle);
}
if (fontColor != null) {
font.setColor(fontColor);
}
return font;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(" Setting font failed !");
}
}
}
3.2 establish pdf file
public class PdfUtils {
/** * The paper size */
private static Rectangle RECTANGLE = PageSize.A4;
/** * establish pdf file * * @param response * @param fileName * @return */
public static Document createDocument(HttpServletResponse response, String fileName) {
try {
response.reset();
response.setHeader("Content-Type", "application/pdf-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
} catch (Exception e) {
e.printStackTrace();
}
// Set size
RECTANGLE = PageSize.A4;
return new Document(RECTANGLE, 50, 50, 80, 50);
}
}
3.3 Create paragraph title
public class PdfUtils {
/** * Set table contents * * @param headFont * @param textFont * @param title * @param list * @return */
public static PdfPTable setTable(Font headFont, Font textFont, String[] title, List<User> list) {
// Four columns
PdfPTable table = createTable(new float[]{
120, 120, 120, 120});
for (String head : title) {
table.addCell(createCell(head, headFont));
}
for (User user : list) {
table.addCell(createCell(user.getName(), textFont));
table.addCell(createCell(user.getGender(), textFont));
table.addCell(createCell(Integer.toString(user.getAgx()), textFont));
table.addCell(createCell(user.getAddress(), textFont));
}
return table;
}
private static PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
// Set table size
table.setTotalWidth(RECTANGLE.getWidth() - 100);
table.setLockedWidth(true);
// In the middle
table.setHorizontalAlignment(Element.ALIGN_CENTER);
// Frame
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
private static PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
// level 、 Vertical center
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
}
3.4 Set up the form
public class PdfUtils {
/** * Draw the title * * @param font * @param titleName * @return */
public static Paragraph setParagraph(Font font, String titleName) {
Paragraph paragraph = new Paragraph(titleName, font);
// Center text
paragraph.setAlignment(Element.ALIGN_CENTER);
// Row spacing
paragraph.setLeading(5f);
// Set the space on the paragraph
paragraph.setSpacingBefore(-20f);
// Set the space below the paragraph
paragraph.setSpacingAfter(15f);
return paragraph;
}
}
3.5 Tool class complete code
public class PdfUtils {
/** * Font storage path , The default is 'C:\Windows\Fonts\' */
private static final String FONT_PATH = "C:\\Windows\\Fonts\\";
/** * The paper size */
private static Rectangle RECTANGLE = PageSize.A4;
/** * Set the default font value * * @return * @throws DocumentException * @throws IOException */
private static BaseFont createBaseFont(String fontName) throws DocumentException, IOException {
// The default is Song typeface
if (fontName == null) {
fontName = "simsun.ttc";
}
String fontPre = fontName.substring(fontName.lastIndexOf(".") + 1);
if (fontPre.equals("ttc")) {
// ttc Format fonts need to be suffixed
fontName = fontName + ",0";
}
String font = FONT_PATH + fontName;
return BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
/** * Set the font * * @return */
public static Font setFont() {
return setFont(null, null, null, null);
}
public static Font setFont(Integer fontSize) {
return setFont(null, fontSize, null, null);
}
public static Font setFont(Integer fontSize, BaseColor fontColor) {
return setFont(null, fontSize, null, fontColor);
}
/** * @param fontName Font name Default Arial * @param fontSize font size Default 12 Number * @param fontStyle Font style * @param fontColor The font color Default black * @return */
public static Font setFont(String fontName, Integer fontSize, Integer fontStyle, BaseColor fontColor) {
try {
BaseFont baseFont = createBaseFont(fontName);
Font font = new Font(baseFont);
if (fontSize != null) {
font.setSize(fontSize);
}
if (fontStyle != null) {
font.setStyle(fontStyle);
}
if (fontColor != null) {
font.setColor(fontColor);
}
return font;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(" Setting font failed !");
}
}
/** * establish pdf file * * @param response * @param fileName * @return */
public static Document createDocument(HttpServletResponse response, String fileName) {
try {
response.reset();
response.setHeader("Content-Type", "application/pdf-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
} catch (Exception e) {
e.printStackTrace();
}
// Set size
RECTANGLE = PageSize.A4;
return new Document(RECTANGLE, 50, 50, 80, 50);
}
/** * Draw the title * * @param font * @param titleName * @return */
public static Paragraph setParagraph(Font font, String titleName) {
Paragraph paragraph = new Paragraph(titleName, font);
// Center text
paragraph.setAlignment(Element.ALIGN_CENTER);
// Row spacing
paragraph.setLeading(5f);
// Set the space on the paragraph
paragraph.setSpacingBefore(-20f);
// Set the space below the paragraph
paragraph.setSpacingAfter(15f);
return paragraph;
}
/** * Set up * Form and content * * @param headFont * @param textFont * @param title * @param list * @return */
public static PdfPTable setTable(Font headFont, Font textFont, String[] title, List<User> list) {
// Four columns
PdfPTable table = createTable(new float[]{
120, 120, 120, 120});
for (String head : title) {
table.addCell(createCell(head, headFont));
}
for (User user : list) {
table.addCell(createCell(user.getName(), textFont));
table.addCell(createCell(user.getGender(), textFont));
table.addCell(createCell(Integer.toString(user.getAgx()), textFont));
table.addCell(createCell(user.getAddress(), textFont));
}
return table;
}
private static PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
// Set table size
table.setTotalWidth(RECTANGLE.getWidth() - 100);
table.setLockedWidth(true);
// In the middle
table.setHorizontalAlignment(Element.ALIGN_CENTER);
// Frame
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
private static PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
// level 、 Vertical center
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
}
4、pdf Build implementation
Code :
@RestController
@RequestMapping("/test")
public class ExcelController {
@GetMapping("/pdf")
public void downloadPDF(HttpServletResponse response) {
try (BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream())) {
// 1. Set the name of the output file
String fileName = " Attendance report .pdf";
// 2. establish pdf file , And set the paper size to A4
Document document = PdfUtils.createDocument(response, fileName);
PdfWriter.getInstance(document, os);
// 3. Open the document
document.open();
// 4. Set title
String titleName = " this individual yes mark topic ";
// Set the font style : In black 20 Number In bold Red
Font titleFont = PdfUtils.setFont("simhei.ttf", 20, Font.BOLD, BaseColor.RED);
Paragraph paragraph = PdfUtils.setParagraph(titleFont, titleName);
// 5. Set up the form
// Define column names
String[] title = {
" full name ", " Gender ", " Age ", " Address "};
// Get list data
// Set header font style : In black 14 Number In bold black
// Set body font style :12 Number
Font headFont = PdfUtils.setFont("simhei.ttf", 12, Font.BOLD, BaseColor.BLACK);
Font textFont = PdfUtils.setFont(12);
// Analog data acquisition
List<User> dataList = getData();
PdfPTable table = PdfUtils.setTable(headFont, textFont, title, dataList);
// 8. Fill in the content
document.add(paragraph);
document.add(table);
// close resource
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/** * Simulate getting data from a database * * @return */
private List<User> getData() {
List<User> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
User user = new User();
user.setName(" name -" + i);
user.setAddress(" Address -" + i);
user.setAgx(20);
user.setGender(" male ");
list.add(user);
}
return list;
}
effect :
边栏推荐
猜你喜欢

Stm32 paj7620u2 gesture recognition module (IIC communication) program source code explanation

面试官:说说 log.Fatal 和 panic 的区别

EDI docking commercehub orderstream

Redis源码与设计剖析 -- 17.Redis事件处理

8 年产品经验,我总结了这些持续高效研发实践经验 · 研发篇

Food safety | eight questions and eight answers take you to know crayfish again! This is the right way to eat!

绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体、水印、logo、页眉、页码

Lwip之内存与包缓冲管理

Interviewer: talk about log The difference between fatal and panic

OSPF --- open shortest priority path protocol
随机推荐
Three dimensional function display of gray image
Take you to a preliminary understanding of multiparty secure computing (MPC)
UFT (QTP) - summary points and automated test framework
绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体、水印、logo、页眉、页码
Unity 贝塞尔曲线的创建
I'm also drunk. Eureka delayed registration and this pit!
go channel简单笔记
Highlights
Automated test Po design model
Redistemplate solves the problem of oversold inventory in the seckill system with high speed - redis transaction + optimistic lock mechanism
Type assertion of go interface variables
PageHelper can also be combined with lambda expressions to achieve concise paging encapsulation
STM32 PAJ7620U2手势识别模块(IIC通信)程序源码详解
自动化测试 PO设计模型
世界各地的标志性建筑物
【解决方案】Microsoft Edge 浏览器 出现“无法访问该页面”问题
itextpdf实现多PDF文件合并为一个PDF文档
Excel表格 / WPS表格中怎么在下拉滚动时让第一行标题固定住?
IDEA集成SVN代码管理常用功能
带你初步了解多方安全计算(MPC)