java匯出pdf

呂建奎發表於2015-11-14

列印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;
  }
}


相關文章