itext java代码生成PDF文档

使用java代码生成打印

itext5首先生成PDF文件有两种方式,1:利用Adobe Acrobat 8 Professional专业版来制作PDF模板 2:就是用PdfWriter去生成。

最近项目上需要做打印功能,本以为之前写的方式一可以复用,但模板中表格稍微复杂,多个表格循环打印,而且表格分布不均 ,不适用与模板打印。下面是方式二生成打印PDF文档(后续有时间,更一篇使用方式一做打印) 。

一般的图表pdf文档是可以满足的;

文件效果图:

代码:

/**
 *
 * @(#) PdfText.java
 * @Package com.eport.web
 * 
 * Copyright © Singlewindow Corporation. All rights reserved.
 *
 */

package com.sw.busi.exbweb.util.printPdf;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 
 * Description : 
 * Author:        linyi                
 * Create Date:   2018年7月24日 下午2:30:57
 *
 */
public class printPdfTest {

	
	public static void main(String[] args) throws Exception {
		
		//创建文本  
        Document document = new Document(PageSize.A4, 70, 70, 20, 100);//上下左右页边距
        try {  
        	
        	int i=(int) (Math.random()*100);
          //写入文本到文件中  文件生成地址:C盘
          PdfWriter.getInstance(document, new FileOutputStream("C:\\cancelBillPrintPDF"+i+".pdf"));
          //打开文本  
          document.open();
          BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
          BaseFont baseFontHei = BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
          
          //标题
          Paragraph paragraph = new Paragraph(40);//边距
          //1 2 3  中右左
          paragraph.setAlignment(1);  //对齐方式
          Font font = new Font(baseFontHei);//字体
          font.setSize(14);//字体大小
          paragraph.setFont(font);//设置段落字体
          Chunk chunk = new Chunk("展览品核销清单");  
          paragraph.add(chunk);  
          document.add(paragraph);
          
          Paragraph paragraph1 = new Paragraph(10);
          //1 2 3  中右左
          paragraph1.setAlignment(2);  //对齐方式
          Font font1 = new Font(baseFontHei);//字体
          font1.setSize(10);
          paragraph1.setFont(font1);
          Chunk chunk1 = new Chunk("仅对核供用");  
          paragraph1.add(chunk1); 
          paragraph1.setSpacingBefore(-15);
          //paragraph1.setSpacingAfter(-50);//往下距离200
          document.add(paragraph1);
          
          
          Paragraph paragraph2 = new Paragraph(50);
          //1 2 3  中右左
          paragraph2.setAlignment(3);  //对齐方式
          Font font2 = new Font(baseFontHei);//字体
          font2.setSize(10);
          paragraph2.setFont(font1);
          Chunk chunk2 = new Chunk("展览品核销清单预录入号:"+"展览品核销清单编号:");  
          paragraph2.add(chunk2); 
          paragraph2.setSpacingAfter(5);
          document.add(paragraph2);
          
          //画表头第一行
          PdfPTable table = new PdfPTable(6);
          table.setTotalWidth(500);
          float[] columnWidth={80,160,80,100,50,30};
          table.setTotalWidth(columnWidth);
          table.setLockedWidth(true);//宽度算正确
          
          //标题与表格中间的距离
          Paragraph p = new Paragraph(50);
          Font f = new Font(baseFont);//字体
          f.setSize(18);//字体大小
          p.setFont(f);//设置段落字体
          Chunk c = new Chunk(" ");  
          p.add(c);  
          document.add(p);

           //cell=new PdfPCell();
          table.addCell(drawPdfPCell("展览会名称",baseFontHei,10,1,80));   
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));  
          table.addCell(drawPdfPCell("展览会编号",baseFontHei,10,1,80));  
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));  
          table.addCell(drawPdfPCell("核销方式",baseFontHei,10,1,80));  
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));  
          document.add(table);
          
          //画表头第二行
          table = new PdfPTable(6);
          table.setTotalWidth(500);
          float[] columnWidth1={80,60,100,180,50,30};
          table.setTotalWidth(columnWidth1);
          table.setLockedWidth(true);//宽度算正确
          
          table.addCell(drawPdfPCell("申报日期",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("申报单位代码/名称",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("进出口日期",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
          document.add(table);
          
          //画表头第三行
          table = new PdfPTable(10);
          table.setTotalWidth(500);
          float[] columnWidth2={80,80,50,50,30,50,30,50,50,30};
          table.setTotalWidth(columnWidth2);
          table.setLockedWidth(true);//宽度算正确
          
          table.setLoopCheck(true);
          table.addCell(drawPdfPCell("运输方式",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("提运单号",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("件数",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("毛重",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("净重",baseFontHei,10,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
          document.add(table);
          
          //画表头第四行
          table = new PdfPTable(4);
          table.setTotalWidth(500);
          float[] columnWidth3={80,100,50,270};
          table.setTotalWidth(columnWidth3);
          table.setLockedWidth(true);//宽度算正确
          PdfPCell cell2 = new PdfPCell();
          cell2.setFixedHeight(60);
          cell2.setBorderWidthTop(200);
          cell2.setBorderWidthLeft(100);
          cell2= drawPdfPCell("随附单据",baseFontHei,5,1,80);//表格第一个标题
          table.addCell(drawPdfPCell("随附单据",baseFontHei,5,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,5,1,80));
          table.addCell(drawPdfPCell("备注",baseFontHei,5,1,80));
          table.addCell(drawPdfPCell("",baseFontHei,5,1,80));
          document.add(table);
          //画表体部分
          
          for(int m=0;m<5;m++){
        	  table = new PdfPTable(4);
              table.setTotalWidth(500);
              float[] columnWidth4={100,150,100,150};
              table.setTotalWidth(columnWidth4);
              table.setLockedWidth(true);//宽度算正确
              table.addCell(drawPdfPCell("展商名称",baseFontHei,10,1,80));
              table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
              table.addCell(drawPdfPCell("展商国别",baseFontHei,10,1,80));
              table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
              document.add(table);
              
             
            	  table = new PdfPTable(11);
                  table.setTotalWidth(500);
                  float[] columnWidth5={30,64,64,64,30,30,30,30,30,64,64};
                  table.setTotalWidth(columnWidth5);
                  table.setLockedWidth(true);//宽度算正确
                  table.addCell(drawPdfPCell("序号",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("商品编码",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("商品名称",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("规格型号",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("数量",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("单位",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("单价",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("总价",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("币制",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("原产国",baseFontHei,10,1,80));
                  table.addCell(drawPdfPCell("证件代码",baseFontHei,10,1,80));
                  document.add(table);
             
                  for(int n=0;n<3;n++){
                	  table = new PdfPTable(11);
                      table.setTotalWidth(500);
                      float[] columnWidth6={30,64,64,64,30,30,30,30,30,64,64};
                      table.setTotalWidth(columnWidth6);
                      table.setLockedWidth(true);//宽度算正确
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  table.addCell(drawPdfPCell("",baseFontHei,10,1,80));
                	  document.add(table);
                  }
          }
          
           //关闭文本  
          document.close();  
        } catch (DocumentException e) {  
          e.printStackTrace();  
        } catch (FileNotFoundException e) {  
          e.printStackTrace();  
        }  
	}
	/**
	 * 
	 * Method description : 画一行中的一列(格子)
	 * Author:        linyi                
	 * Create Date:   2018年7月24日 下午2:17:07
	 * History:  2018年7月24日 下午2:17:07   linyi   Created.
	 * @param cellText 格子的文字
	 * @param baseFont 字体类型
	 * @param size 字体大小
	 * @param alignment 对齐方式
	 * @return
	 * @throws Exception
	 *
	 */
	private static   PdfPCell drawPdfPCell(String cellText,BaseFont baseFont,float size,int alignment,int minimumHeight ) throws Exception{
		//为null会报错  防止报错
		if(cellText==null){
			cellText=" ";
		}
		//表格开始
        Paragraph paragraph = new Paragraph();
        paragraph.setAlignment(alignment);  //对齐方式
        Font font = new Font(baseFont);//字体
        font.setSize(size);//字体大小
        paragraph.setFont(font);//设置段落字体
        Chunk chunk = new Chunk(cellText);  
        paragraph.add(chunk);  
        PdfPCell cell = new PdfPCell();
        cell.setUseAscender(true);
        cell.setVerticalAlignment(cell.ALIGN_MIDDLE);//设置cell垂直居中
        cell.setMinimumHeight(minimumHeight);//设置单元格最小高度,当前行最小高度
        cell.addElement(paragraph);
		return cell;
	}

}

遇到的坑:

1:会报找不到字体的错误,这里的解决方式就是通过使用自己的字体就好,simsun.ttc是Windows下面自带的字体(简体宋体:C:\Windows\Fonts下面有很多字体可以使用),在应用项目时

private static final String FONT = "static/fonts/SIMSUN.TTC,1";//仿宋体字库位置

                  //拿到字体
                      String FONT_PATH="";
                    String path = this.getClass().getResource("/").getPath();// 得到d:/tomcat/webapps/工程名WEB-INF/classes/路径
                    if(path.indexOf("WEB-INF/classes")!=-1){
                        path = path.substring(1, path.indexOf("WEB-INF/classes"));// 从路径字符串中取出工程路劲
                         FONT_PATH = path + FONT+"";
                    }else{
                        //单元测试文件
                        path = path.substring(1,path.length());// 从路径字符串中取出工程路劲
                        FONT_PATH=path+"file/simfang.ttf";
                    }

2:在迁移至项目时,本地是没有问题,发布至开发环境,测试环境会报错,还是字体找不到

原因:开发环境处于Linux,加上判断即可:

                      if (SEnv.WINDOWS) {
                          Logger.info(this, "====static字库地址WINDOWS,FONT_PATH=======:"+FONT_PATH);
                      } else if (SEnv.LINUX || SEnv.SUN_OS) {
                          FONT_PATH = "/" + FONT_PATH;
                          //FONTHEI_PATH= "/" + FONTHEI_PATH;
                          Logger.info(this, "====static字库地址LINUX,SUN_OS,FONT_PATH=======:"+FONT_PATH);
                      }

猜你喜欢

转载自blog.csdn.net/weixin_37020977/article/details/81254613