springboot生成二维码在word文档,并下载到本地
分为两部分演示,第一部分简单的生成word文档并保存到本地;第二部分生成二维码在word文档,并保存到本地。
第一部分
首先引入word的依赖资源
<!--word相关jar-->
<!--iText是一个非常著名的能够快速产生 PDF 文件的 Java 类库。支持文本,表格,图形的操作,可以方便的跟 Servlet 进行结合-->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<!-- itext-rtf是生成word需要用到的资源 -->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext-rtf</artifactId>
<version>2.1.7</version>
</dependency>
<!-- 使用itext-asian解决中文不显示的问题 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
创建Word,并且写入IO流中,前端获取文件流才能保存在本地
public void createWord(HttpServletResponse response)throws DocumentException, UnsupportedEncodingException{
// 以A4纸大小输出word
Document doc = new Document(PageSize.A4);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 把word与输出流绑定
RtfWriter2.getInstance(doc, baos);
// 开始写入word,必须调用这个方法才能进行word的写入
doc.open();
// 加载额外字体的第一种方法:iText本身支持的字体少,这个时候可以使用系统自带的字体
FontFactory.register("C:\\user\\download\\simsun.ttc");
// 这是另一种加载字体的方法,把字体文件放到webapp下,防止某些电脑并没有第一种方法中的字体.
String realPath = req.getSession().getServletContext().getRealPath("/") + "font/";
FontFactory.register(realPath + "FZSTK.TTF"); // 方正舒体
FontFactory.register(realPath + "simfang.ttf"); // simfang
FontFactory.register(realPath + "simhei.ttf"); // 黑体
FontFactory.register(realPath + "simkai.ttf");
// 对字体文件右键查看详细信息的标题,可以获取getFont方法中第一个参数的字符串.
// 第二个参数不用管是编码集, 第三个参数是字体大小
Font titlefont = FontFactory.getFont("simsun", BaseFont.WINANSI, 13);
// 设置字体大小
titlefont.setSize(14);
// 设置字体格式,只能设置一种格式
titlefont.setStyle(Font.BOLD);
// 设置字体的重载方法,可以传递多种样式,比如加粗倾斜
titlefont.setStyle("bold, italic");
// 加入一个段落,第一个参数是段落内容,第二个是字体
Paragraph paragraph = new Paragraph("第一个段落", titlefont);
// 设置段落的首行缩进
paragraph.setFirstLineIndent(50);
// 设置段落的段前间距,单位是float,这里与word本身不同不是磅值是厘米
paragraph.setSpacingBefore(5);
// 设置段落的段后间距,单位是float,这里与word本身不同不是磅值是厘米
paragraph.setSpacingAfter(5);
// 设置段落的右侧间距
paragraph.setIndentationRight(30);
// 设置段落的左侧间距
paragraph.setIndentationLeft(30);
// 将段落添加到word
doc.add(paragraph);
// 申明一个6行的表格
Table table = new Table(6);
// 设置表格宽度
table.setBorderWidth(1);
// 设置表格每行的单元格的宽度,数组的长度表明了每行的单元格数量
int[] widths = {10, 13, 13, 15, 15, 15};
// 设置每行的单元格
table.setWidths(widths);
// 设置表格所占的%
table.setWidth(91);
// 设置表格的对齐方式
table.setAlignment(ALIGN_MIDDLE);
table.setAlignment(ALIGN_CENTER);
for (int j = 0; j < 6; j++)