/**
* 创建段落
* Paragraph 和 Text 关系,
* 同一个设置如果 Text 存在,则以 Text 设置为显示方式
* 如果 Text 没有设置,以 Paragraph 设置为显示方式
* 对齐模式以 Paragraph 对齐模式设置为显示方式
* Paragraph需要特别注意的一点,想要段落文字居中,不要用setHorizontalAlignment(HorizontalAlignment.CENTER);
* 这是组件的居中对段落无效,甚至在段落里你放Text也无效,需要改用setTextAlignment(TextAlignment.CENTER);
* .setFontSize(14)//设置字体大小
* .setBold()//设置文字为粗体
* .setFontColor(new DeviceRgb(0,0,0))//设置字体颜色
* .setTextAlignment(TextAlignment.CENTER)//文字水平居中
* .setFixedLeading(14);//类似于css中的行高
*/
@SneakyThrows
public void createPdf(String filePath, HttpServletResponse response) {
//创建输出流
OutputStream outputStream = response.getOutputStream();
// pdf 输出流
PdfWriter pdfWriter = new PdfWriter(outputStream);
// 处理 pdf 的主入口点
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
// 设置pdf的页面大小
PageSize pageSize = new PageSize(PageSize.A4);
// 文档对象,用于添加文档中的各种元素,,元素只能添加 AreaBreak、Image对象和IBlockElement接口的实现类对象
Document document = new Document(pdfDocument, pageSize);
//设置长宽高
document.setMargins(40, 40, 20, 40);
// 创建字体
PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
//利用div包装
Div div = new Div();
Paragraph title = new Paragraph().setFont(font).setFontSize(14);
Paragraph paragraph = new Paragraph().setFont(font).setFontSize(10);
Text text = new Text("shijuan"+"\n");
title.add(text).setTextAlignment(TextAlignment.CENTER).setBold();
paragraph.add("部门:"+space);
paragraph.add("岗位:"+space);
paragraph.add("姓名:"+space);
paragraph.add("工号:"+space);
paragraph.add("最高得分:");
div.add(paragraph);
document.add(title);
document.add(div);
//保证试题过多可以立马换页
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
// 设置浏览器响应的格式
String fileName = URLEncoder.encode("试卷", "UTF-8");
response.setContentType("application/pdf; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
document.close();
response.flushBuffer();
// 输出的最后处理
document.close();
pdfWriter.close();
}
Java使用IText7导出自定义PDF
最新推荐文章于 2024-05-11 17:07:57 发布