java导出pdf文件工具类

最近频繁用到itextpdf将数据导出为pdf文件,每次都要写一些基本的方法,太麻烦,就写了一个工具类,可以降低代码的冗余

下面是工具类:

首先引入itextpdf jar包,然后引入下面工具类:

import java.io.File;
import java.io.IOException;
import java.util.List;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.jfinal.kit.PathKit;
import com.xc.cfg.Preference;

/**
 * @Description pdf工具类
 * @author GuoMing
 * @date 2016年11月29日 下午7:38:09 
 * @version V0.1
 */
public final class PdfTool {
	//正文body 字体
	 public static Font setChineseFont() throws DocumentException, IOException {
		    File font = new File(PathKit.getWebRootPath()  + Preference.PDF_FONT_PATH);
			BaseFont bfChinese = BaseFont.createFont(font.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			Font FontChinese = new Font(bfChinese, 12, Font.NORMAL); 
	        return FontChinese;
	    }
	//table thead 字体
	 public static Font setTheadFont() throws DocumentException, IOException {
		    File font = new File(PathKit.getWebRootPath()  + Preference.PDF_FONT_PATH);
			BaseFont bfChinese = BaseFont.createFont(font.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			Font FontChinese = new Font(bfChinese, 11, Font.NORMAL); 
	        return FontChinese;
	    }
	 //table tbody 字体
	 public static Font setTbodyFont() throws DocumentException, IOException {
		    File font = new File(PathKit.getWebRootPath()  + Preference.PDF_FONT_PATH);
			BaseFont bfChinese = BaseFont.createFont(font.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			Font FontChinese = new Font(bfChinese, 9, Font.NORMAL); 
	        return FontChinese;
	    }
	 //文档一号标题
	 public static Font setDheadFont() throws DocumentException, IOException {
		    File font = new File(PathKit.getWebRootPath()  + Preference.PDF_FONT_PATH);
			BaseFont bfChinese = BaseFont.createFont(font.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			Font FontChinese = new Font(bfChinese, 14, Font.NORMAL); 
	        return FontChinese;
	    }
	 //获取字符长度(为了让汉字和字母长度统一)
	 public static int length(String s) {
			if (s == null)
				return 0;
			char[] c = s.toCharArray();
			int len = 0;
			for (int i = 0; i < c.length; i++) {
				len++;
				if (!isLetter(c[i])) {
					len++;
				}
			}
			return len;
		}

		public static boolean isLetter(char c) {
			int k = 0x80;
			return c / k == 0 ? true : false;
		}
	 /**
	  * @Description 添加行内容
	  * @author GuoMing
	  * @date 2016年11月29日 下午3:33:06 
	  * @param document  文档对象
	  * @param list      行内容列表
	  * @return          返回添加行后的文档对象
	 * @throws DocumentException 
	  */
	 public static Document addParagraph(Document document,List<String> list,Font font) throws DocumentException{
		 for(String p : list){
			 document.add(new Paragraph(p,font));
		 }
		 return document;
	 }
	 
	 /**
	  * @Description 添加表格
	  * @author GuoMing
	  * @date 2016年11月29日 下午3:34:27 
	  * @param document  文档对象
	  * @param thead     表头列表
	  * @param thead     内容列表
	  * @return          添加表格之后的文档对象
	 * @throws DocumentException 
	  */
	 public static Document addTable(Document document,PdfPTable table,List<String> thead,List<List<String>> tbody,Font TBFont,Font THFont) throws DocumentException{
		//添加表头
		 for(String p:thead){
			 PdfPCell cell=new PdfPCell(new Phrase(p,THFont));
			 cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			 cell.setBackgroundColor(new BaseColor(216, 218, 220));
			 table.addCell(cell);
		 }
		 //添加表内容
		 for(List<String> p:tbody){
			 for(String c:p){
				 PdfPCell cell=new PdfPCell(new Phrase(c,TBFont));
				 cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				 table.addCell(cell);
			 }
		 }
		 document.add(table);
		 return document;
	 }
	//设置行距
	public static void addParaAfter(Document document,float i) throws DocumentException {
		// TODO Auto-generated method stub
		Paragraph p=new Paragraph();
		p.setSpacingAfter(i);
		document.add(p);
	}
	
	public static void addParaBefore(Document document,float i) throws DocumentException {
		// TODO Auto-generated method stub
		Paragraph p=new Paragraph();
		p.setSpacingBefore(i);
		document.add(p);
	}
}

设置页码

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * @Description 设置底部页码
 * @author GuoMing
 * @date 2016年12月8日 下午7:06:46 
 * @version V0.1
 */
public class HeaderFooter extends PdfPageEventHelper{
    public void onEndPage (PdfWriter writer, Document document) {
        Rectangle rect = writer.getBoxSize("art");
        switch(writer.getPageNumber() % 2) {
        case 0:
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_RIGHT, new Phrase(""),
                    rect.getRight(), rect.getTop(), 0);
            break;
        case 1:
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_LEFT, new Phrase(""),
                    rect.getLeft(), rect.getTop(), 0);
            break;
        }
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_CENTER, new Phrase(String.format("第  %d 页", writer.getPageNumber())),
                (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
    }
}


调用过程

1:前端调用接口

public class ExportController extends CommonAdminController {
public static DeviceCheckInfo info=new DeviceCheckInfo();//这是一个自建的bean类,将所有需要打印在pdf中的数据都封装在里面
	public void exportDeviceCheckPdf(){
Document document = new Document(PageSize.A4, 40f, 40f, 100f, 20f);// 创建文档 大小	
		document.setMargins(40, 40, 15, 45); // 左,右,上,下  
		...中间封装数据过程略...
		Base64ToImg.exportDeviceCheckPdf(document,info, path, pdfName);
		renderFile(pdfName);
	}
}

2,调用业务逻辑层方法:

public class Base64ToImg {
	/**
	 * @Description 
	 * @param info 导出数据bean
	 * @param path  存储路径
	 * @param pdfName 文件名称
	 * 自定义字体方法
		 	BaseFont bfChinese = BaseFont.createFont(fpath.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			Font font1 = new Font(bfChinese, 16, Font.NORMAL); // 标题字体
	 */
	public static void exportDeviceCheckPdf(Document document,DeviceCheckInfo info, String path, String pdfName) {
		
		PdfWriter writer;
		File fpath = new File(PathKit.getWebRootPath() + Preference.PDF_FONT_PATH);
		try {
			Font DHFont = PdfTool.setDheadFont();                                                // 标题字体
			Font THFont = PdfTool.setTheadFont();                                                 // thead字体
			Font TBFont = PdfTool.setTbodyFont();                                                 // tbody字体
			Font font = PdfTool.setChineseFont();                                                  // 正文字体
			BaseFont bfChinese = BaseFont.createFont(fpath.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			Font font1 = new Font(bfChinese, 11, Font.BOLD); // 标题字体
			writer = PdfWriter.getInstance(document, new FileOutputStream(path + "/" + pdfName));
			Rectangle rect = new Rectangle(36, 54, 559, 788);                                         // 设置页面大小  
		    rect.setBackgroundColor(BaseColor.WHITE);                                            // 页面背景色  
			rect.setBorderColor(BaseColor.BLACK);
			writer.setBoxSize("art", rect);
			document.open(); 
			//设置页脚
			HeaderFooter footer = new HeaderFooter();
			writer.setPageEvent(footer);
			   
			                                                                 
			Paragraph p11 = new Paragraph("设备巡检记录", DHFont);                   
			p11.setAlignment(1);                                                                 //居中
			p11.setSpacingBefore(20);                                                            //行间距
			p11.setSpacingAfter(20);
			document.add(p11);
			
			Anchor anchorTarget = new Anchor("设备巡检记录", DHFont);
			document.addTitle("设备巡检记录");                  
			
			List<String> paragraphsList1=new ArrayList<String>();
			List<String> paragraphsList=new ArrayList<String>();
			String value="设备总数:"+info.getDeviceNums() + "    "+"正常:"+info.getNormalNums()+
						 "    "+"离线:"+info.getOutLineNums()+ "    "+"维保:"+info.getProtectNums()+
						 "    "+"异常:"+info.getErrNums()    + "    "+"报警:"+info.getAlarmNums();
			String checkUser=info.getCheckUser();
			
			paragraphsList1.add(value);
			paragraphsList.add("巡检账户:"+checkUser+"     巡检时间:"+info.getCheckTime()+"    巡检人(签名):");
			
			
			
			PdfPTable t=new PdfPTable(9);
			t.setWidthPercentage(100);
			t.setSpacingBefore(15);
			t.setSpacingAfter(15);
			
			t.setTotalWidth(new float[] { 5, 8, 9, 10, 10, 10, 24, 5, 19});               //设置表头列宽
			
			List<String> thead=new ArrayList<String>() ;
			thead.add("序号");                                                                //设置数据表头
			thead.add("名称");	
			thead.add("型号");
			thead.add("序列号");
			thead.add("位置");
			thead.add("最后记录时间");
			thead.add("当前值");
			thead.add("状态");
			thead.add("设备所有人");
			
			List<List<String>> tbody=new ArrayList<List<String>>();
			for (int j = 0; j <info.getList().size(); j++) {                               //封装表格body内容 
				List<String> tCells=new ArrayList<String>(); 
				tCells.add(""+(j+1));
				tCells.add(info.getList().get(j).getDeviceName());	
				tCells.add(info.getList().get(j).getDeviceModel());
				tCells.add(info.getList().get(j).getDeviceId());
				tCells.add(info.getList().get(j).getDeviceAddr());
				tCells.add(info.getList().get(j).getUploadTime());
				tCells.add(info.getList().get(j).getChannelInfos());
				tCells.add(info.getList().get(j).getStatus());
				tCells.add(info.getList().get(j).getAlarmUsers());
				tbody.add(tCells);
			}
			
			
			PdfTool.addParagraph(document, paragraphsList1,font1);                          //输出正文
			//PdfTool.addParaAfter(document,10);
			PdfTool.addParagraph(document, paragraphsList,font);
			PdfTool.addParaAfter(document,-10);
			PdfTool.addTable(document, t,thead, tbody,TBFont,THFont);                         //输出表格
			
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			
			document.close();
		}
		
	}
}

如果广大网友觉得这篇文章有用,可以用    666导航网   收藏起来,方便随时查看



  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值