热门系列:

【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文档、幻灯片、文本域、图片、表格等!以上方法可谓是工具类通用方法,所以有一些文档的样式,排版,文字设计等个性化操作,没有一一列出,大家可参考以下在线文档或下载文档,按需实现:

 

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 {

    @Autowired
    private 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);

        //点击下载ppt
        String 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文件效果如下:

java生成ppt文件 java生成ppt的代码_poi

以上截图就是我们的用例方法所生成的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;
	    }
	    
		@Override
	    public 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();
        }
    }
 
    // 打开文档时,创建一个总页数的模版
	@Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        PdfContentByte cb =writer.getDirectContent();
        totalPage = cb.createTemplate(30, 16);
    }
    
    // 一页加载完成触发,写入页眉和页脚
    @Override
    public 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模版写到指定位置
	@Override
    public 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 {
	
	@Resource
	private 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开启,使用完后需要close
			document.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;
	}
	
}

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

java生成ppt文件 java生成ppt的代码_poi生成ppt_02

以上就是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生成ppt文件 java生成ppt的代码_itext_03