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;
}
}
相關文章
- Java匯出Pdf格式表單Java
- java模板匯出PDF檔案Java
- Java整合FreeMarker匯出Pdf檔案Java
- PHP 匯出 PDFPHP
- 前端(vue)匯出pdf前端Vue
- Java與React輕鬆匯出Excel/PDF資料JavaReactExcel
- Vue框架下實現匯入匯出Excel、匯出PDFVue框架Excel
- CAD工具——匯出PDF
- NPOI匯出和匯入Excel,Word和PDFExcel
- Laravel-snappy匯出PDFLaravelAPP
- 如何使用Java建立資料透視表並匯出為PDFJava
- 使用Laravel-snappy匯出PDFLaravelAPP
- laravel 推薦優雅匯出pdfLaravel
- 【匯出PDF-專案應用】
- java匯出Excel定義匯出模板JavaExcel
- Java匯出ExcelJavaExcel
- 匯出 VuePress構建的網站為 PDFVue網站
- React專案實現匯出PDF的功能React
- 轉java操作excel匯入匯出JavaExcel
- 將SAP CRM WebClient UI的表格匯出成PDFWebclientUI
- 如何將SAP WebClient UI的表格匯出成PDFWebclientUI
- 是程式設計師,就用python匯出pdf程式設計師Python
- vue-前端匯出 pdf 並且壓縮 zipVue前端
- 如何用低程式碼實現批次匯出PDF?
- Java 通過Xml匯出Excel檔案,Java Excel 匯出工具類,Java匯出Excel工具類JavaXMLExcel
- java 匯入匯出Excel工具類ExcelUtilJavaExcel
- Gradle環境下匯出Swagger為PDFGradleSwagger
- 【實戰】通過 JS 將 HTML 匯出為 PDF 文件JSHTML
- 網頁中Office和pdf相關檔案匯出網頁
- C# word或者excel儲存或匯出為PDFC#Excel
- java匯出Excel檔案JavaExcel
- java poi 匯出excel加密JavaExcel加密
- java匯出CSV檔案Java
- Java之POI操作Excel表-匯入匯出JavaExcel
- 關於java中Excel的匯入匯出JavaExcel
- 前端網頁列印外掛print.js(可匯出pdf)前端網頁JS
- poi 匯出Excel java程式碼ExcelJava
- java使使用者EasyExcel匯入匯出excelJavaExcel