热门系列:

  • 【Java编程系列】WebService的使用

  • 【Java编程系列】在Spring MVC中使用工具类调用Service层时,Service类为null如何解决

  • 【Java编程系列】Spring中使用代码实现动态切换主从库(多数据源)

  • 【Java编程系列】log4j配置日志按级别分别生成日志文件

  • 【Java编程系列】使用Java进行串口SerialPort通讯

  • 【Java编程系列】comet4j服务器推送实现

  • 【Java编程系列】使用JavaMail通过SMTP协议发送局域网(内网)邮件

  • 【Java编程系列】解决Java获取前端URL中加号(+)被转换成空格的问题

  • 【Java编程系列】使用List集合对百万数据量高效快速过滤去重筛选

  • 【Java编程系列】Java与Mysql数据类型对应表

  • 【Java编程系列】Java自定义标签-Tag

  • 【Java编程系列】二进制如何表示小数?0.3+0.6为什么不等于0.9?纳尼!!!

  • 程序人生,精彩抢先看


目录

1、前言

2、使用POI生成并下载PPT文件

2.1、环境准备

2.2、PPT文件生成工具类

2.3、用例实现

3、使用Itex生成并下载PDF文件

3.1、环境准备

3.2、PDF文件生成工具类

3.3、用例实现

4、结尾


1、前言

近期接到一个需要生成PPT、PDF文件的需求,虽然以前也弄过相关的一些相关的文件生成的开发,例如Excel、Word、PDF、PPT、XML等等类型。但之前没有写过相关的博客留作记录和分享,所以趁着片刻闲暇之际,记录此次开发经历。利人利己,也希望能够帮到正在学习或是需要使用到此功能的小伙伴们。下面,咱们开整~~~


2、使用POI生成并下载PPT文件

2.1、环境准备

首先,需要引入相关POI的Maven依赖包:

<!--PPT生成所需POI包-->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.14</version>
</dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.14</version>
</dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.14</version>
</dependency>

2.2、PPT文件生成工具类

其实开发关键,就在于这个工具类的方法。所以,这里是重点,仔细看:

package xxx.xxx.data.util;import lombok.extern.slf4j.Slf4j;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.TableCell;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFTable;
import org.apache.poi.xslf.usermodel.XSLFTableCell;
import org.apache.poi.xslf.usermodel.XSLFTableRow;
import org.apache.poi.xslf.usermodel.XSLFTextBox;
import org.apache.poi.xslf.usermodel.XSLFTextRun;import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;/*** @Author: Yangy* @Date: 2020/11/4 16:12* @Description ppt生成工具类*/
@Slf4j
public class PptCreateUtil {/*** @Author Yangy* @Description 获取一个ppt实例* @Date 16:37 2020/11/4* @Param []* @return org.apache.poi.xslf.usermodel.XMLSlideShow**/public static XMLSlideShow getPptInstance(){// 创建ppt:XMLSlideShow ppt = new XMLSlideShow();//设置幻灯片的大小:Dimension pageSize = ppt.getPageSize();pageSize.setSize(800,700);return ppt;}/*** @Author Yangy* @Description 创建幻灯片* @Date 16:39 2020/11/4* @Param ppt* @return org.apache.poi.xslf.usermodel.XSLFSlideMaster**/public static XSLFSlide createSlide(XMLSlideShow ppt,XSLFSlideLayout layout){//通过布局样式创建幻灯片XSLFSlide slide = ppt.createSlide(layout);//清理掉模板内容slide.clear();return slide;}/*** @Author Yangy* @Description 生成一个文本框及内容* @Date 10:10 2020/11/5* @Param content=内容,fontSize=字大小,fontFamily=字体风格,color=字颜色* @return org.apache.poi.xslf.usermodel.XMLSlideShow**/public static void addTextBox(XSLFSlide slide,String content,Double fontSize,String fontFamily,Color color,int x,int y,int w,int h){XSLFTextBox textBox = slide.createTextBox();//设置坐标、宽高textBox.setAnchor(new Rectangle2D.Double(x, y, w, h));XSLFTextRun projectInfo = textBox.addNewTextParagraph().addNewTextRun();projectInfo.setText(content);projectInfo.setFontSize(fontSize);projectInfo.setFontFamily(fontFamily);projectInfo.setFontColor(color);}/*** @Author Yangy* @Description 添加图片,设置图片坐标、宽高* @Date 16:47 2020/11/4* @Param slide=幻灯片实例,picBytes=图片字节流,picType=图片类型* @return org.apache.poi.xslf.usermodel.XMLSlideShow**/public static void addPicture(XMLSlideShow ppt,XSLFSlide slide,byte [] picBytes,PictureData.PictureType picType,int x,int y,int w,int h){XSLFPictureData idx = ppt.addPicture(picBytes, picType);XSLFPictureShape pic = slide.createPicture(idx);//设置当前图片在ppt中的位置,以及图片的宽高pic.setAnchor(new java.awt.Rectangle(x, y, w, h));}/*** @Author Yangy* @Description 添加表格* @Date 16:55 2020/11/4* @Param [ppt]* @return org.apache.poi.xslf.usermodel.XMLSlideShow**/public static void addTable(XSLFSlide slide,List<List<String>> dataList,int x,int y,int w,int h){XSLFTable table = slide.createTable();//此处还可以自行添加表格样式参数//dataList第一个列表为行数据,内嵌列表为每一行的列数据for (int i = 0; i < dataList.size(); i++) {List<String> row = dataList.get(i);if (Objects.isNull(row)) continue;XSLFTableRow row1 = table.addRow();for (int j = 0; j < row.size(); j++) {XSLFTableCell cell = row1.addCell();cell.setBorderColor(TableCell.BorderEdge.top,Color.BLACK);cell.setBorderColor(TableCell.BorderEdge.right,Color.BLACK);cell.setBorderColor(TableCell.BorderEdge.bottom,Color.BLACK);cell.setBorderColor(TableCell.BorderEdge.left,Color.BLACK);cell.setText(row.get(j));}}//这个设置必须有,否则表格不显示Rectangle2D rectangle2D = new Rectangle2D.Double(x,y,w,h);table.setAnchor(rectangle2D);}/*** @Author Yangy* @Description 写入指定路径的ppt文件* @Date 16:59 2020/11/4* @Param [ppt, fileOutputStream]* @return void**/public static void pptWirteOut(XMLSlideShow ppt, FileOutputStream fileOutputStream){try {ppt.write(fileOutputStream);System.out.println("create PPT successfully");fileOutputStream.close();} catch (IOException e) {e.printStackTrace();log.error("An exception occurred in PPT writing...");}}/*** @Author Yangy* @Description* @Date 14:22 2020/11/5* @Param [ppt, outputStream]* @return void**/public static void pptWirteOut(XMLSlideShow ppt, ServletOutputStream outputStream){try {ppt.write(outputStream);System.out.println("download PPT successfully");outputStream.close();ppt.close();} catch (IOException e) {e.printStackTrace();log.error("An exception occurred in PPT download...");}}}

上述方法,都给到了具体说明,可以满足PPT文件生成开发的基本使用了,包括了创建PPT文档、幻灯片、文本域、图片、表格等!以上方法可谓是工具类通用方法,所以有一些文档的样式,排版,文字设计等个性化操作,没有一一列出,大家可参考以下在线文档或下载文档,按需实现:

  • Apache POI在线API文档
  • Apache POI文档手册

2.3、用例实现

下面,看下我们的实现用例,代码如下:

package xxx.xxx.data.service;import xxx.xxx.common.bean.base.Result;
import xxx.xxx.data.constant.DataFileConstant;
import xxx.xxx.data.util.CommonUtils;
import xxx.xxx.data.util.PptCreateUtil;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;/*** @Author: Yangy* @Date: 2020/11/4 17:07* @Description ppt业务逻辑处理实现*/
@Service("pptOperationImpl")
public class PptOperationImpl {@Autowiredprivate HttpServletResponse response;/*** @Author Yangy* @Description 生成并下载ppt* @Date 9:48 2020/11/5* @Param []* @return xxx.xxx.common.bean.base.Result**/public Result createPPTFile(){Result result = null;try {XMLSlideShow ppt = PptCreateUtil.getPptInstance();//获取幻灯片主题列表:List<XSLFSlideMaster> slideMasters = ppt.getSlideMasters();XSLFSlideLayout layout = slideMasters.get(0).getLayout(SlideLayout.TITLE_AND_CONTENT);//因为每一页排版都不同,所以每个幻灯片都需要单独生成XSLFSlide slide1 = PptCreateUtil.createSlide(ppt,layout);//获取需生成ppt的数据,此处数据可来源于指定文件,亦或是动态获取的数据//此处用指定文件数据为例File file = new File("C:\\Users\\xxx\\Desktop\\record\\timg.jpg");FileInputStream fis = new FileInputStream(file);byte [] bytes = IOUtils.toByteArray(fis);//添加图片 PptCreateUtil.addPicture(ppt,slide1,bytes,PictureData.PictureType.JPEG,100,100,100,100);fis.close();//再生成多个幻灯片XSLFSlide slide2 = PptCreateUtil.createSlide(ppt,layout);PptCreateUtil.addTextBox(slide2,"测试",18D,"",Color.CYAN,100,100,50,50);//添加表格XSLFSlide slide3 = PptCreateUtil.createSlide(ppt,layout);//测试数据List<List<String>> rowList = new ArrayList<>();List<String> cell1List = new ArrayList<>();cell1List.add("jack");cell1List.add("22");List<String> cell2List = new ArrayList<>();cell2List.add("lily");cell2List.add("20");rowList.add(cell1List);rowList.add(cell2List);PptCreateUtil.addTable(slide3,rowList,50,50,500,300);//在指定路径生成ppt
//        File newPpt = new File("C:\\Users\\xxx\\Desktop\\record\\new.pptx");
//        FileOutputStream fileOutputStream = new FileOutputStream(newPpt);
//        PptCreateUtil.pptWirteOut(ppt,fileOutputStream);//点击下载pptString name = "DownloadData.pptx";response = CommonUtils.getServletResponse(response,DataFileConstant.PPT,name);PptCreateUtil.pptWirteOut(ppt,response.getOutputStream());} catch (IOException e) {e.printStackTrace();}return result;}}

通用方法CommonUtils.getServletResponse以及常量类,我这边也给大家贴一下吧(这些方法和类待会生成PDF时也会用到):

public static HttpServletResponse getServletResponse(HttpServletResponse response,String fileType,String name){try {response.setCharacterEncoding("UTF-8");if(DataFileConstant.PPT.equals(fileType)){//设置输出文件类型为pptx文件response.setContentType(DataFileConstant.CONTENT_TYPE_OF_PPT);}else if(DataFileConstant.PDF.equals(fileType)){//设置输出文件类型为pptx文件response.setContentType(DataFileConstant.CONTENT_TYPE_OF_PDF);}//通知浏览器下载文件而不是打开response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode(name, DataFileConstant.CHARSET_OF_UTF8));response.setHeader("Pragma", java.net.URLEncoder.encode(name, DataFileConstant.CHARSET_OF_UTF8));} catch (UnsupportedEncodingException e) {log.error("happened exception when set httpServletResponse!!!");e.printStackTrace();}return response;
}
package xxx.xxx.data.constant;/*** @Author: Yangy* @Date: 2020/11/5 14:28* @Description*/
public class DataFileConstant {//文件类型简称public final static String PPT = "PPT";public final static String PDF = "PDF";//文件的内容类型public final static String CONTENT_TYPE_OF_PPT = "application/vnd.ms-powerpoint";public final static String CONTENT_TYPE_OF_PDF = "application/pdf";//编码格式public final static String CHARSET_OF_UTF8 = "UTF-8";public final static String CHARSET_OF_GBK = "GBK";
}

通过调用以上方法,就可以生成PPT文件啦!因为我这边是要达到用户点击直接下载文件的效果,所以输出流是通过HttpServletResponse来操作的!上面我有注释的地方,也是可以生成到指定路径下的文件中的,各位按需修改!生成后的PPT文件效果如下:

以上截图就是我们的用例方法所生成的PPT文件啦,是不是So Easy!但是在这里有个点需要和大家提一下:

①创建幻灯片后需要调用此方法,清理掉模板内容

slide.clear();

②创建表格时,这个设置必须有,否则表格不显示

Rectangle2D rectangle2D = new Rectangle2D.Double(x,y,w,h);

table.setAnchor(rectangle2D);


3、使用Itex生成并下载PDF文件

3.1、环境准备

同样,先需要引入相关Itext的Maven依赖包:

<!--pdf文件生成依赖-->
<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>         

3.2、PDF文件生成工具类

直接上代码,工具类代码如下:

package xxx.xxx.data.util;import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import xxx.xxx.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;import java.io.IOException;
import java.util.List;
import java.util.Objects;/*** @Author: Yangy* @Date: 2020/11/4 15:53* @Description pdf生成工具类*/
@Slf4j
public class PdfCreateUtil {/*** @Author Yangy* @Description 创建document* @Date 16:24 2020/11/5* @Param []* @return com.itextpdf.text.Document**/public static Document getDocumentInstance(){//此处方法可以初始化document属性,document默认A4大小Document document = new Document();return document;}/*** @Author Yangy* @Description 设置document基本属性* @Date 16:24 2020/11/5* @Param [document]* @return com.itextpdf.text.Document**/public static Document setDocumentProperties(Document document,String title,String author,String subject,String keywords,String creator){// 标题document.addTitle(title);// 作者document.addAuthor(author);// 主题document.addSubject(subject);// 关键字document.addKeywords(keywords);// 创建者document.addCreator(creator);return document;}/*** @Author Yangy* @Description 创建段落,可设置段落通用格式* @Date 16:24 2020/11/5* @Param []* @return com.itextpdf.text.Paragraph**/public static Paragraph getParagraph(String content,Font fontStyle,int align,int lineIdent,float leading){//设置内容与字体样式Paragraph p = new Paragraph(content,fontStyle);//设置文字居中 0=靠左,1=居中,2=靠右p.setAlignment(align); //首行缩进p.setFirstLineIndent(lineIdent);//设置左缩进
//      p.setIndentationLeft(12); //设置右缩进
//      p.setIndentationRight(12);//行间距     p.setLeading(leading);//设置段落上空白p.setSpacingBefore(5f); //设置段落下空白p.setSpacingAfter(10f); return p;}/*** @Author Yangy* @Description 获取图片* @Date 16:39 2020/11/5* @Param [imgUrl]* @return com.itextpdf.text.Image**/public static Image getImage(String imgUrl,int align,int percent){Image image = null;try {image = Image.getInstance(imgUrl);} catch (BadElementException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}//设置图片位置image.setAlignment(align);//依照比例缩放image.scalePercent(percent); return image;}/*** @Author Yangy* @Description 创建表格* @Date 16:43 2020/11/5* @Param [dataList=数据集合,maxWidth=表格最大宽度,align=位置(0,靠左   1,居中     2,靠右)* @return com.itextpdf.text.pdf.PdfPTable**/public static PdfPTable getTable(List<List<String>> dataList,int maxWidth,int align,Font font){if(Objects.isNull(dataList) || dataList.size() == 0){log.warn("data list is empty when create table");return null;}int columns = dataList.get(0).size();PdfPTable table = new PdfPTable(columns);table.setTotalWidth(maxWidth);table.setLockedWidth(true);table.setHorizontalAlignment(align);//设置列边框table.getDefaultCell().setBorder(1);//此处可自定义表的每列宽度比例,但需要对应列数
//      int width[] = {10,45,45};//设置每列宽度比例
//      table.setWidths(width);   table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中    //边距:单元格的边线与单元格内容的边距table.setPaddingTop(1f);  //间距:单元格与单元格之间的距离table.setSpacingBefore(0);table.setSpacingAfter(0);for (int i = 0; i < dataList.size(); i++) {for (int j = 0; j < dataList.get(i).size(); j++) {table.addCell(createCell(dataList.get(i).get(j),font));}}return table;}/*** @Author Yangy* @Description 自定义表格列样式属性* @Date 16:54 2020/11/5* @Param [value, font]* @return com.itextpdf.text.pdf.PdfPCell**/private static PdfPCell createCell(String value, Font font) {PdfPCell cell = new PdfPCell();//设置列纵向位置,居中cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置列横向位置,居中cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setPhrase(new Phrase(value, font));return cell;}/*** @Author Yangy* @Description 获取自定义字体* @Date 11:38 2020/11/6* @Param [size=字大小, style=字风格, fontFamily=字体, color=颜色]* @return com.itextpdf.text.Font**/public static Font setFont(float size, int style, String fontFamily, BaseColor color)throws IOException, DocumentException {//设置中文可用BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Font font = new Font(bfChinese,size,style);font.setFamily(fontFamily);font.setColor(color);return font;}/*** @Author Yangy* @Description 创建水印设置* @Date 12:04 2020/11/6* @Param [markContent]* @return xxx.xxx.data.util.PdfCreateUtil.Watermark**/public static Watermark createWaterMark(String markContent) throws IOException, DocumentException {return new Watermark(markContent);}/*** @Author Yangy* @Description 设置水印* @Date 12:03 2020/11/6* @Param * @return **/public static class Watermark extends PdfPageEventHelper {Font FONT = PdfCreateUtil.setFont(30f, Font.BOLD, "",new GrayColor(0.95f));private String waterCont;//水印内容public Watermark() throws IOException, DocumentException {}public Watermark(String waterCont) throws IOException, DocumentException {this.waterCont = waterCont;}@Overridepublic void onEndPage(PdfWriter writer, Document document) {for (int i = 0; i < 5; i++) {for (int j = 0; j < 5; j++) {ColumnText.showTextAligned(writer.getDirectContentUnder(),Element.ALIGN_CENTER,new Phrase(StringUtils.isEmpty(this.waterCont) ? "" : this.waterCont, FONT),(50.5f + i * 350),(40.0f + j * 150),writer.getPageNumber() % 2 == 1 ? 45 : -45);}}}}public static HeaderFooter createHeaderFooter(){return new HeaderFooter();}/*** @Author Yangy* @Description 页眉/页脚* @Date 12:25 2020/11/6* @Param * @return **/public static class HeaderFooter extends PdfPageEventHelper {// 总页数PdfTemplate totalPage;Font hfFont;{try {hfFont = setFont(8, Font.NORMAL,"",BaseColor.BLACK);} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}// 打开文档时,创建一个总页数的模版@Overridepublic void onOpenDocument(PdfWriter writer, Document document) {PdfContentByte cb =writer.getDirectContent();totalPage = cb.createTemplate(30, 16);}// 一页加载完成触发,写入页眉和页脚@Overridepublic void onEndPage(PdfWriter writer, Document document) {PdfPTable table = new PdfPTable(3);try {table.setTotalWidth(PageSize.A4.getWidth() - 100);table.setWidths(new int[] { 24, 24, 3});table.setLockedWidth(true);table.getDefaultCell().setFixedHeight(-10);table.getDefaultCell().setBorder(Rectangle.BOTTOM);table.addCell(new Paragraph("我是页眉/页脚", hfFont));table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);table.addCell(new Paragraph("第" + writer.getPageNumber() + "页/", hfFont));// 总页数PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));cell.setBorder(Rectangle.BOTTOM);table.addCell(cell);// 将页眉写到document中,位置可以指定,指定到下面就是页脚table.writeSelectedRows(0, -1, 50,PageSize.A4.getHeight() - 20, writer.getDirectContent());} catch (Exception de) {throw new ExceptionConverter(de);}}// 全部完成后,将总页数的pdf模版写到指定位置@Overridepublic void onCloseDocument(PdfWriter writer,Document document) {String text = "总" + (writer.getPageNumber()) + "页";ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,hfFont), 2, 2, 0);}}}

以上工具类主要包括的方法主要有:创建文档、段落文本、图片、表格、字体、水印、页眉页脚等!

3.3、用例实现

再看实现方法具体代码如下:

package xxx.xxx.data.service;import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import xxx.xxx.common.bean.base.Result;
import xxx.xxx.data.constant.DataFileConstant;
import xxx.xxx.data.util.CommonUtils;
import xxx.xxx.data.util.PdfCreateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;/*** @Author: Yangy* @Date: 2020/11/5 17:05* @Description pdf业务逻辑实现类*/
@Slf4j
@Service("pdfOperationImpl")
public class PdfOperationImpl {@Resourceprivate HttpServletResponse response;public Result createPDFFile(){Result result = null;Document document = null;try {document = PdfCreateUtil.getDocumentInstance();String fileName = "test.pdf";response = CommonUtils.getServletResponse(response,DataFileConstant.PDF,fileName);//此处需要注意,必须将writer设置在document打开之前,否则内容无法正常写入,pdf无法正常打开PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());writer.setPageEmpty(false);//设置水印PdfCreateUtil.Watermark watermark = PdfCreateUtil.createWaterMark("这是一个水印");writer.setPageEvent(watermark);//设置页眉页脚PdfCreateUtil.HeaderFooter headerFooter = PdfCreateUtil.createHeaderFooter();writer.setPageEvent(headerFooter);//document开启,使用完后需要closedocument.open();//设置字体Font font1 = PdfCreateUtil.setFont(10f,Font.NORMAL,"",BaseColor.BLACK);//以下为测试数据//创建段落Paragraph graph1 = PdfCreateUtil.getParagraph("This is test content....",font1,1,24,20f);graph1.add(new Chunk(new LineSeparator()));Paragraph graph2 = PdfCreateUtil.getParagraph("page2",font1,1,24,20f);//获取数据List<List<String>> rowList = new ArrayList<>();List<String> cell1List = new ArrayList<>();cell1List.add("jack");cell1List.add("22");List<String> cell2List = new ArrayList<>();cell2List.add("lily");cell2List.add("20");rowList.add(cell1List);rowList.add(cell2List);PdfPTable table = PdfCreateUtil.getTable(rowList,500,1,font1);//添加图片Image image = PdfCreateUtil.getImage("C:\\Users\\xxx\\Desktop\\record\\关注.gif",1,100);document.add(graph1);document.add(table);document.add(image);//添加新页document.newPage();document.add(graph2);} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if (Objects.nonNull(document)) document.close();}return result;}}

执行一下,咱们看下效果:

以上就是PDF的全部实现啦。下面来说说开发过程中需要注意的点

①PdfWriter必须创建和设置在Document打开之前,即在document.open()方法调用之前,否则内容无法正常写入,会不显示!

②Pdf文档中,如果要使用中文,比如文本、水印等,只要是需要设置字体的地方,必须用添加如下设置,否则内容不显示,没有相应效果出现!

BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

再用以上对象设置到字体中,如:Font font = new Font(bfChinese,size,style);


4、结尾

以上内容理解和使用起来并不难,但在一般的开发中,相信大家都会经常用到。所以,希望这篇文章,能够帮到正在学习或是编码的你。也希望以上提出的注意点,各位能着重留意,比避免走弯路!

本博客皆为学习、分享、探讨为本,欢迎各位朋友评论、点赞、收藏、关注!

【Java编程系列】java用POI、Itext生成并下载PPT、PDF文件相关推荐

  1. 【Java编程系列】JWT秘钥生成

    热门系列: [算法系列]实战篇:Diffie-Hellman算法实现通信秘钥流程 目录 1.JWT简介 2.JWT的优缺点 3.JWT组成部分 4.JWT的使用 4.1 生成公钥私钥命令 4.2 JW ...

  2. jFreeChart+itext生成带统计图的pdf文件

    jar包依赖 <!-- iText start--><!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --& ...

  3. 【Java编程系列】Java判断世界各时区的夏令时、冬令时

    热门系列: [Java编程系列]java用POI.Itext生成并下载PPT.PDF文件 [Java编程系列]二进制如何表示小数?0.3+0.6为什么不等于0.9?纳尼!!! 程序人生,精彩抢先看 目 ...

  4. 【Java编程系列】log4j配置日志按级别分别生成日志文件

    热门系列: [Java编程系列]WebService的使用 [Java编程系列]在Spring MVC中使用工具类调用Service层时,Service类为null如何解决 [Java编程系列]Spr ...

  5. 【Java编程系列】Minio实现文件上传下载

    热门系列: [Java编程系列]Amazon S3实现文件上传下载 目录 热门系列: 1.前言 2.Minio实战代码 2.1 Minio环境部署 2.2 Minio的Sdk对接实现 2.2.1 Mi ...

  6. 【Java编程系列】Java自定义标签-Tag

    热门系列: [Java编程系列]WebService的使用 [Java编程系列]在Spring MVC中使用工具类调用Service层时,Service类为null如何解决 [Java编程系列]Spr ...

  7. 【Java编程系列】使用Java进行串口SerialPort通讯

    热门系列: [Java编程系列]WebService的使用 [Java编程系列]在Spring MVC中使用工具类调用Service层时,Service类为null如何解决 [Java编程系列]Spr ...

  8. Re0:Java编程系列-3 进阶排序思维分析与对比

    Re0:Java编程系列 作者参加校招,在复习Java的同时,决定开一打系列博客.复习的同时,作者希望能留下材料,方便也服务一些新入门的小伙伴. 本系列文章从基础入手,由简单的功能函数开始,再扩展为类 ...

  9. 【Java编程系列】gateway限流实践时发生的问题和解决方案

    前期回顾: [Java编程系列]Springcloud-gateway自带限流方案实践篇 1.实践中发生的问题 主要有以下几个问题: 1.限流返回的响应数据无法自定义 (LogFormatUtils. ...

最新文章

  1. npm全局安装和本地安装和本地开发安装(npm install --g/--save/--save-dev)
  2. 1.为什么要学习MATLAB
  3. CodeForces 797C Minimal string
  4. API---有意思的API
  5. centos6.5系统自带python2.6升级到python2.7
  6. 衡量试卷难度信度_我们可以通过数字来衡量语言难度吗?
  7. AGC 26 F Manju Game
  8. vue-router 动态路由
  9. 代替嵌套循环java_蓝石榴_个人博客_Java中for循环嵌套的替换优化
  10. java怎么对用户做自定义模版打印_Printing tools 自定义模板打印的实现
  11. 提升 10 倍!阿里云对象存储 OSS 可用性 SLA 技术揭秘
  12. 【21.09-21.10】近日Paper Quichthrough汇总
  13. 4、6、7、8、9、11、13、27的倍数的特征
  14. 院校-美国:麻省理工学院(MIT)
  15. turtle库使用教程 及 绘制 浪漫樱花 五角星 彩虹玫瑰 谢尔宾斯基三角形 实例
  16. TI C2000介绍
  17. 利用Python+OpenCV对图像加密/解密
  18. ae制作小球轨迹运动_AE教程AE特效:教你如何用AE创建一个弹跳运动的小球特效...
  19. 基于深度学习的手写数字识别Matlab实现
  20. 【论文解读】HIN2Vec: Explore Meta-paths in Heterogeneous Information Networks for Representation Learning

热门文章

  1. FrameMaker 格式的本地化流程(续1)
  2. python数据分析师前景及待遇怎么样_数据分析师未来五年发展前景怎么样?
  3. java 坦克大战画坦克_java简易坦克大战(2)
  4. linux常用面试题
  5. 两种领导力:温柔与严厉
  6. HCU混和动力控制器,HEV混动串并联 混动车辆
  7. 上海市的某快递公司根据投送目的地距离公司的远近,将全国划分成5个区域: 0区 1区 2区 3区 4区 同城 临近两省 1500公里(含)以内 1500——2500公里 2500公里以上 上海 江苏
  8. 黑马程序员 python 基础版 哪个老师_(看黑马程序员Python基础班视频挺好,犹豫该不该报班?)...
  9. 移动硬盘数据莫名丢失,如何才能恢复
  10. OneDNS助力高校行业网络安全