java导出pdf

打印pdf首先要有iText-2.1.7.jar,iTextAsian.jar

首先查询数据把想要打印的数据查询出来

我这里写的是一个task

package com.hengeasy.gris.task;

import java.io.File;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.hengeasy.commons.bean.User;
import com.hengeasy.commons.platform.transaction.Transaction;
import com.hengeasy.commons.scheduler.exception.TaskExecutionException;
import com.hengeasy.commons.scheduler.task.WorkItem;
import com.hengeasy.commons.util.DateTimeUtils;
import com.hengeasy.gris.bean.ConsumeLog;
import com.hengeasy.gris.dao.ConsumeLogDAO;
import com.hengeasy.gris.dao.factory.DAOInstances;
import com.hengeasy.gris.messages.GrisMessages;
import com.hengeasy.gris.platform.GrisPlatform;
import com.hengeasy.gris.transaction.TransactionFactory;
import com.hengeasy.gris.util.PdfUtils;
import com.hengeasy.profiles.dao.UserDAO;

public class ConsumeLogConvertPdfTask extends WorkItem
{
  public ConsumeLogConvertPdfTask()
  {
    super(false);
  }

  private static final Logger log = Logger.getLogger(ConsumeLogConvertPdfTask.class.getName());

  private static final DAOInstances DAO = new DAOInstances();

  private static final UserDAO<User> UserDAO = new com.hengeasy.profiles.dao.factory.DAOInstances().User;

  private static final ConsumeLogDAO<ConsumeLog> ConsumeLogDAO = DAO.CONSUME_LOG;

  private static final Locale LOCALE = GrisPlatform.SYSTEM_LOCALE;

  private static final int YESTERDAY = -1;

  @Override
  public void runWork() throws Throwable
  {
    if (log.isLoggable(Level.FINER))
    {
      log.entering(ConsumeLogConvertPdfTask.class.getName(), "runWork()");
    }

    Transaction transaction = TransactionFactory.getTransaction();
    Date endDate = DateTimeUtils.getCurrentDate();
    Date beginDate = DateTimeUtils.calculateDate(endDate, YESTERDAY);

    try
    {
      transaction.begin();

      Set<Long> gymIds = ConsumeLogDAO.getGymId(transaction.getConnection(), beginDate, endDate);
      ;

      if (gymIds.size() > 0)
      {
        // pdf保存路径
        File file = new File("c:" + File.separator + beginDate);
        if (!file.exists())
        {
          file.mkdir();
        }

        Timestamp now = DateTimeUtils.getCurrentTimestamp();
        for (Long gymId : gymIds)
        {
          List<ConsumeLog> consumeLogs = ConsumeLogDAO.getByGymId(transaction.getConnection(), ConsumeLogDAO.verbosity().PDF_VIEW, gymId,
              beginDate, endDate);

          if (consumeLogs != null && consumeLogs.size() > 0)
          {
            Set<Long> userIds = new HashSet<Long>();
            for (ConsumeLog consumeLog : consumeLogs)
            {
              userIds.add(consumeLog.getLastUpdateUser());
            }
            Map<Long, User> users = UserDAO.getByIds(com.hengeasy.profiles.transaction.TransactionFactory.getTransaction().getConnection(),
                UserDAO.verbosity().SAME_AREA_USERS_VIEW, new ArrayList<Long>(userIds));

            //打印pdf调用方法
            PdfUtils.consumeLogPdf(consumeLogs, users, file.getPath() + File.separator + gymId + ".pdf");
          }
        }
        System.out.println("task 执行完毕!");
      }

      transaction.commit();
    }
    catch (Throwable e)
    {
      transaction.rollback();

      log.log(Level.SEVERE, GrisMessages.RUN_TASK_ERROR_1.formatMessage(LOCALE, new Object[] { ConsumeLogConvertPdfTask.class.getName() }),
          e);

      throw new TaskExecutionException(e);
    }
    finally
    {
      if (log.isLoggable(Level.FINER))
      {
        log.exiting(ConsumeLogConvertPdfTask.class.getName(), "runWork()");
      }
    }
  }
}

打印pdf的类

package com.hengeasy.gris.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.hengeasy.commons.bean.User;
import com.hengeasy.gris.bean.ConsumeLog;
import com.hengeasy.gris.bean.Order.PayStyle;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

public class PdfUtils
{
  private static final String CONSUMELOG_TITLE[] = { "操作员", "消费者", "金额", "会员卡号", "会员卡余额", "日期", "消费类型" };

  private static final float WIDTH = 30f;

  private static final float[] widths = new float[] { 1f * WIDTH, 1f * WIDTH, 1f * WIDTH, 1.5f * WIDTH, 1f * WIDTH, 1f * WIDTH, 1f * WIDTH };

  private static final String THIRDPARTY_PAY = "第三方支付流水";

  private static final String MEMBER_CARD = "会员卡支付流水";

  private static final String CASH = "现金支付流水";

  private static final String AMOUNT = "金额 :  ";

  private static BaseFont bfChinese;

  private static Font titleFont;

  private static Font contextFont;

  static
  {
    try
    {// 设置中文字体
      bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
      // 正文字体风格
      contextFont = new Font(bfChinese, 5, Font.NORMAL);
      // 标题字体风格
      titleFont = new Font(bfChinese, 6, Font.NORMAL);
    }
    catch (DocumentException e)
    {
      e.printStackTrace();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }

  }

  public static void consumeLogPdf(List<ConsumeLog> consumeLogs, Map<Long, User> users, String path) throws DocumentException, IOException
  {
    Document document = getDocument(path);
    // 打开文档。
    document.open();

    Table tableOne = createTable(widths.length, widths);
    Table tableTwo = createTable(widths.length, widths);
    Table tableThree = createTable(widths.length, widths);

    // 表的标题栏
    createTbaleTitle(tableOne, CONSUMELOG_TITLE);
    createTbaleTitle(tableTwo, CONSUMELOG_TITLE);
    createTbaleTitle(tableThree, CONSUMELOG_TITLE);

    // 表的数据
    double thirdparty_pay_coount = 0;
    double member_card_count = 0;
    double cash_cout = 0;

    for (ConsumeLog consumeLog : consumeLogs)
    {
      if (PayStyle.THIRDPARTY_PAY.equals(consumeLog.getPayStyle()))
      {
        // 第三方支付方式
        createTbaleDate(tableOne, consumeLog, users);
        thirdparty_pay_coount += consumeLog.getCost();
      }
      else if (PayStyle.MEMBER_CARD.equals(consumeLog.getPayStyle()))
      {
        // 会员卡
        createTbaleDate(tableTwo, consumeLog, users);
        member_card_count += consumeLog.getCost();
      }
      else
      {
        // 现金支付
        createTbaleDate(tableThree, consumeLog, users);
        cash_cout += consumeLog.getCost();
      }
    }

    document.add(getParagraph(THIRDPARTY_PAY, titleFont, Element.ALIGN_LEFT));
    // 第三方支付删除会员卡与会员卡余额
    tableOne.deleteColumn(3);
    tableOne.deleteColumn(3);
    document.add(tableOne);
    document.add(getParagraph(AMOUNT + thirdparty_pay_coount + "\n\n\n\n", titleFont, Element.ALIGN_RIGHT));

    document.add(getParagraph(MEMBER_CARD, titleFont, Element.ALIGN_LEFT));
    document.add(tableTwo);
    document.add(getParagraph(AMOUNT + member_card_count + "\n\n\n\n", titleFont, Element.ALIGN_RIGHT));

    document.add(getParagraph(CASH, titleFont, Element.ALIGN_LEFT));
    // 现金支付删除会员卡与会员卡余额
    tableThree.deleteColumn(3);
    tableThree.deleteColumn(3);
    document.add(tableThree);
    document.add(getParagraph(AMOUNT + cash_cout + "\n\n\n\n", titleFont, Element.ALIGN_RIGHT));
    document.close();
  }

  private static Paragraph getParagraph(String title, Font font, int direction)
  {
    Paragraph paragraph = new Paragraph(title, font);
    paragraph.setAlignment(direction);
    return paragraph;
  }

  /**
   * 创建表的表头
   * 
   * @param table
   * @param title
   * @throws BadElementException
   */
  private static void createTbaleTitle(Table table, String[] title) throws BadElementException
  {
    for (int i = 0; i < title.length; i++)
    {
      table.addCell(new Cell(new Paragraph(title[i], contextFont)));
    }
  }

  /**
   * 创建表的数据
   * 
   * @param table
   * @param consumeLog
   * @param users
   * @param count
   * @throws BadElementException
   */
  private static void createTbaleDate(Table table, ConsumeLog consumeLog, Map<Long, User> users) throws BadElementException
  {
    // "操作员", "消费者", "金额", "会员卡号", "会员卡余额", "日期","消费类型";
    table.addCell(new Cell(new Paragraph(users.get(consumeLog.getLastUpdateUser()).getName(), contextFont)));
    table.addCell(new Cell(new Paragraph(consumeLog.getName(), contextFont)));
    table.addCell(new Cell(new Paragraph(String.valueOf(consumeLog.getCost()), contextFont)));
    table.addCell(new Cell(new Paragraph(String.valueOf(consumeLog.getMemberCardNo()), contextFont)));
    table.addCell(new Cell(new Paragraph(String.valueOf(consumeLog.getBalance()), contextFont)));
    table.addCell(new Cell(new Paragraph(consumeLog.getSysCreateDate().toString()
        .substring(0, consumeLog.getSysCreateDate().toString().indexOf(".")), contextFont)));
    table.addCell(new Cell(new Paragraph(consumeLog.getCostType().getCostTypeName(), contextFont)));
  }

  /**
   * 初始化表
   * 
   * @param table
   * @throws BadElementException
   */
  private static Table createTable(int cell, float[] widths) throws BadElementException
  {
    Table table = new Table(cell);
    table.setWidths(widths);
    table.setWidth(100);// 占页面宽度比例
    table.setBorder(0);
    // table.setBorderWidth(0);// 边框宽度
    table.setAlignment(Element.ALIGN_CENTER);// 居中
    // table.setAlignment(Element.ALIGN_MIDDLE);// 垂直居中
    table.setAutoFillEmptyCells(true);// 自动填满
    // table.setLockedWidth(true);
    table.setPadding(2.2f);
    return table;
  }

  private static Document getDocument(String path) throws DocumentException, IOException
  {
    // 建立com.lowagie.text.Document对象的实例。
    Document document = new Document(PageSize.A4, 20, 20, 0, 0);
    // 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(path)));
    // 设置页页事件监听器
    // writer.setPageEvent(new PDFUtil());
    return document;
  }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值