服务器存储一个url,通过url访问合同
pom 导入jar包
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<type>jar</type>
<scope>compile</scope>
</dependency>
controller层代码:
/**
* @description: 打印合同* @param response
* @param orderId
* @author:wangchong
* @createTime:2015年7月15日 上午8:49:35
*/
@RequestMapping(value = MyOrderURL.PRINTPDF, method = RequestMethod.GET)
public void printPDF(HttpServletResponse response,long orderId)
{
String url = mallOrderService.printOrderPDF(orderId);
if (StringUtils.isEmpty(url))
{
return;
}
InputStream inputStream = null;
ServletOutputStream outputStream = null;
try
{
response.setContentType("application/pdf");
inputStream = FastDFSClient.downloadFile(url);
outputStream = response.getOutputStream();
if (inputStream != null)
{
byte b[] = new byte[inputStream.available()];
while ((inputStream.read(b)) != -1)
{
outputStream.write(b);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if (inputStream != null)
{
inputStream.close();
}
if (outputStream != null)
{
outputStream.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
AO层代码实现:
public String printOrderPDF(long orderId)
{
String url = "";
Order order = orderService.findOrderById(orderId, false);
if (order != null && order.getContractCode() != null)
{
if (StringUtils.isEmpty(order.getUrl()))
{
String path = AppUtils.getWebRootPath() + "/order/contract/" + order.getContractCode() + ".pdf";
File f = new File(path);
url = createOrderCNTPDF(order, f);
order.setUrl(url);
orderService.modifyOrder(order);
}
else
{
url = order.getUrl();
}
}
return url;
}
/**
* @description: 创建合同PDF
* @param order
* @author:wangchong
* @createTime:2015年7月14日 下午5:29:30
*/
private String createOrderCNTPDF(Order order, File f)
{
String url = "";
Map<String, Object> dataMap = new HashMap<String, Object>();
//获取合同内容
dataMap = previewContract(order);
try
{
String pdfFilePath = "/home/order/contract/";
AppUtils.mkdirs(pdfFilePath);
OrderCntPdfUtil.createOrderContPdf(pdfFilePath + order.getContractCode() + ".pdf", dataMap);
url = FastDFSClient.uploadFile(f, ".pdf");
}
catch (DocumentException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return url;
}
@Override
public Map<String, Object> previewContract(Order order)
{
long orderId = order.getId();
OrderContractVO orderContractVO = null;
Receipt receipt = null;
String adminName = " ";
String adminPhone = " ";
// 仓库明细
List<Warehouse> warehouseList = new ArrayList<Warehouse>();
if (order != null && !CollectionUtils.isEmpty(order.getDetails()))
{
orderContractVO = OrderContractVO.toOrderContractVO(order);
orderContractVO.setSumAmtCN(NumberTools.amtEnConvertCn(String.valueOf(order.getSumAmt())));
Shop shop = shopService.findShopById(order.getShopId(), false);
orderContractVO.setStoreName(shop == null ? "" : shop.getName());
String contractTime = (order.getContractTime() == 0 ? DateUtils.formatDate(order.getCreatTime(), "yyyy-MM-dd") : DateUtils.formatDate( order.getContractTime(), "yyyy-MM-dd"));
orderContractVO.setYear(contractTime.split("-")[0]);
orderContractVO.setMonth(contractTime.split("-")[1]);
orderContractVO.setDay(contractTime.split("-")[2]);
// 乙方信息
Member member = companyService.findMemberById(order.getMemberId());
if (member != null)
{
orderContractVO.setMemberAddress(member.getAddress());
User user = userService.fidUserById(order.getUserId());
orderContractVO.setMemberAdmin(user != null ? user.getName() : "");
orderContractVO.setMemberPhone(user != null ? user.getMobile() : "");
orderContractVO.setMemberFax(member.getFax());
orderContractVO.setMemberName(member.getName());
InvoiceQualifications invoiceQualifications = companyService.findInvoiceQualificationsByMemberId(order.getMemberId());
if(invoiceQualifications != null)
{
orderContractVO.setMemberBank(invoiceQualifications.getBank());
orderContractVO.setMemberAccount(invoiceQualifications.getAccount());
}
}
// 甲方信息
member = companyService.findMemberById(order.getGoodsMemberId());
if (member != null)
{
orderContractVO.setShopAdmin(member.getName());
orderContractVO.setShopPhone(member.getPhone());
orderContractVO.setShopAddress(member.getAddress());
orderContractVO.setShopFax(member.getFax());
}
receipt = receiptService.getReceiptByOrderId(orderId);
// 仓库明细
Map<String, Warehouse> warehouseMap = new HashMap<String, Warehouse>();
List<OrderDetail> orderDetailList = order.getDetails();
if (!CollectionUtils.isEmpty(orderDetailList))
{
for (OrderDetail orderDetail : orderDetailList)
{
String warehouseName = orderDetail.getWarehouse();
if (!warehouseMap.containsKey(warehouseName))
{
Warehouse warehouse = warehouseService.getWarehouseByCode(orderDetail.getWarehouseCode());
if (warehouse == null)
{
warehouse = new Warehouse();
warehouse.setName(warehouseName);
warehouse.setAddress(" ");
warehouse.setPhone(" ");
}
warehouseMap.put(warehouseName, warehouse);
warehouseList.add(warehouse);
}
}
}
// 经办人员和联系方式
Employee employee = employeeService.getEmployeeById(NumberUtils.parseLong(orderContractVO.getAdminId()));
if (employee != null)
{
adminName = employee.getName();
adminPhone = employee.getPhone() != null ? employee.getPhone() : employee.getMobile();
}
}
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("orderContractVO", orderContractVO);
dataMap.put("receipt", receipt);
dataMap.put("warehouseList", warehouseList);
dataMap.put("adminName", adminName);
dataMap.put("adminPhone", adminPhone);
return dataMap;
}
util工具类:
OrderCntPdfUtil
package com.banksteel.order.utils.pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import cn.mysteel.util.NumberUtils;
import cn.mysteel.warehouse.entity.Warehouse;
import com.banksteel.order.utils.NumberTools;
import com.banksteel.order.vo.OrderContractVO;
import com.banksteel.order.vo.OrderDetailVO;
import com.banksteel.pay.entity.Receipt;
import com.lowagie.text.Chunk;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
public class OrderCntPdfUtil
{
// 创建pdf
public static void createOrderContPdf(String filePath, Map<String, Object> dataMap) throws DocumentException, IOException
{
String tempFilePath = filePath.replace(".pdf", "_temp.pdf");
PdfUtils pt = new PdfUtils();
// 创建并打开document
pt.openDocument(pt ,0, tempFilePath, dataMap.get("adminName").toString(), dataMap.get("adminPhone").toString());
// 插入内容
pt = insertConetxt(pt, dataMap);
// 关闭document
pt.closeDocument();
// 对已生成的pdf添加印章水印
addPdfMark(pt, tempFilePath, filePath);
}
/**
* @description: pdf添加印章水印
*
* @param filePath
* @author: zhangyf
* @createTime:2015年4月29日 上午10:26:02
*/
private static void addPdfMark(PdfUtils pt, String tempFilePath, String filePath) throws DocumentException, IOException
{
PdfReader reader = new PdfReader(tempFilePath);
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(filePath));
Image img = pt.getHTZImg();
Random random = new Random();
int pageSize = reader.getNumberOfPages();
for(int i = 1; i < pageSize; i++)
{
img.setRotationDegrees(random.nextInt(360));//旋转
img.setAbsolutePosition(150 + random.nextInt(40), 350 + random.nextInt(40));
PdfContentByte under = stamp.getUnderContent(i);
under.addImage(img);
}
stamp.close();// 关闭
File tempfile = new File(tempFilePath);
if(tempfile.exists())
{
tempfile.delete();
}
}
/**插入pdf内容
*
* @param pt
* @return
* @throws DocumentException
* @throws IOException
*/
private static PdfUtils insertConetxt(PdfUtils pt, Map<String, Object> dataMap) throws DocumentException, IOException
{
OrderContractVO orderContractVO= (OrderContractVO) dataMap.get("orderContractVO");
Assert.notNull(orderContractVO, "协议信息不能为空");
Paragraph paragraph = null;
Chunk chunk = null;
// 设置文档标题
pt.insertTitle("电子交易合同");
pt.insertContext1("", 12, Font.NORMAL, Element.ALIGN_LEFT);
// 设置文档正文
pt.insertContext1("甲方(供方):上海钢银电子商务有限公司 合同编号:" + orderContractVO.getContractCode() , 12, Font.NORMAL, Element.ALIGN_LEFT);
paragraph = new Paragraph();
chunk = pt.getChunk("乙方(需方):", 12, Font.NORMAL);
paragraph.add(chunk);
String partyAName = orderContractVO.getMemberName();
int partyANameLen = 12 - partyAName.length();
chunk = pt.getChunk(partyAName + getSpace((partyANameLen<0?0:partyANameLen)*2), 12, Font.UNDERLINE);
paragraph.add(chunk);
chunk = pt.getChunk(getSpace(12 - (partyANameLen>0?0:0-partyANameLen)*2) + " 签订时间、地点 :" + "", 12, Font.NORMAL);
paragraph.add(chunk);
chunk = pt.getChunk(" " + orderContractVO.getYear() + " ", 12, Font.UNDERLINE);
paragraph.add(chunk);
chunk = pt.getChunk("年", 12, Font.NORMAL);
paragraph.add(chunk);
chunk = pt.getChunk(" " + orderContractVO.getMonth() + " ", 12, Font.UNDERLINE);
paragraph.add(chunk);
chunk = pt.getChunk("月", 12, Font.NORMAL);
paragraph.add(chunk);
chunk = pt.getChunk(" " + orderContractVO.getDay() + " ", 12, Font.UNDERLINE);
paragraph.add(chunk);
chunk = pt.getChunk("日 上海市宝山区", 12, Font.NORMAL);
paragraph.add(chunk);
pt.insertContext1(paragraph, 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext1("", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("甲乙双方就现货销售事宜,经平等、自愿协商,达成如下一致意见:", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("一、合同标的", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext1("", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext1("", 12, Font.NORMAL, Element.ALIGN_LEFT);
//生成三列表格
PdfPTable aTable = new PdfPTable(12);
//设置表格具体宽度
aTable.setWidthPercentage(100);
//设置每一列所占的长度
aTable.setWidths(new int[]{ 7, 7, 12, 7, 7, 14, 13, 5, 7, 7, 7, 7});
PdfPCell cell = pt.newCell( "产品\n名称", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("质量问题描述", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("规格\n(MM)", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("材质", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("产地", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("仓库", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("捆包号", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("件数\n(件)", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("数量\n(吨)", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("单价\n(元/吨)", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("出库费单价\n(元)", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("金额\n(元)", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
List<OrderDetailVO> detailVOs = orderContractVO.getDetailVOs();
int items = 0;
if (!CollectionUtils.isEmpty(detailVOs))
{
for (OrderDetailVO orderDetailVO : detailVOs)
{
cell = pt.newCell( orderDetailVO.getBreed(), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(orderDetailVO.getQualityRemark(), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(orderDetailVO.getSpec(), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(orderDetailVO.getMaterial(), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(orderDetailVO.getBrand(), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(orderDetailVO.getWarehouse(), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(orderDetailVO.getSerialNo(), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(String.valueOf(orderDetailVO.getItems()), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
int weightWay = orderDetailVO.getWeightWay();
String weghtWayStr = "";
if (weightWay == 0)
{
weghtWayStr = "理重";
}
else if (weightWay == 1)
{
weghtWayStr = "过磅";
}
else
{
weghtWayStr = "抄码";
}
cell = pt.newCell(weghtWayStr + "\n" + roundDouble(orderDetailVO.getQty(), 4), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(roundDouble(orderDetailVO.getPrice(), 2), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
if(NumberUtils.parseDouble(orderDetailVO.getInOutWarehousePrice()) == 0D)
{
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
}
else
{
cell = pt.newCell(roundDouble(orderDetailVO.getInOutWarehousePrice(), 2), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
}
cell = pt.newCell(roundDouble(NumberTools.add(NumberTools.multi(NumberUtils.parseDouble(orderDetailVO.getPrice()),NumberUtils.parseDouble(orderDetailVO.getQty())),NumberTools.multi(NumberUtils.parseDouble(orderDetailVO.getInOutWarehousePrice()),NumberUtils.parseDouble(orderDetailVO.getQty()))), 2), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
items = items + NumberUtils.parseInt(orderDetailVO.getItems());
}
}
Receipt orderReceipt = (Receipt) dataMap.get("receipt");
double jifenExchangeAmount = 0D;
double rebateAmount = 0D;
if (orderReceipt != null)
{
jifenExchangeAmount = orderReceipt.getJifenExchangeAmount();
if (jifenExchangeAmount > 0)
{
cell = pt.newCell("积分抵扣", 10, 7);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(roundDouble(jifenExchangeAmount ,2), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
}
rebateAmount = orderReceipt.getRebateAmount();
if (rebateAmount > 0)
{
cell = pt.newCell("返利抵扣", 10, 7);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(roundDouble(rebateAmount, 2), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
}
}
if (jifenExchangeAmount > 0 || rebateAmount > 0)
{
cell = pt.newCell("合计", 10, 7);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(items + "", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(roundDouble(NumberUtils.parseDouble(orderContractVO.getSumQty()), 4), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(roundDouble(orderReceipt.getAccountAmount(), 2), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
}
else
{
cell = pt.newCell("合计", 10, 7);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(String.valueOf(items), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(roundDouble(NumberUtils.parseDouble(orderContractVO.getSumQty()), 4), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell("-", 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(roundDouble(NumberUtils.parseDouble(orderContractVO.getSumAmt()), 2), 10, 1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
}
cell = pt.newCell("人民币(大写)", 10, 7);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
cell = pt.newCell(orderContractVO.getSumAmtCN(), 10, 5);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell);
pt.getDocument().add(aTable);
pt.insertContext("二、交(提)货地点:", 12, Font.NORMAL, Element.ALIGN_LEFT);
// 仓库明细
@SuppressWarnings("unchecked")
List<Warehouse> warehouseList = (List<Warehouse>)dataMap.get("warehouseList");
if (!CollectionUtils.isEmpty(warehouseList))
{
for (Warehouse warehouse : warehouseList)
{
paragraph = new Paragraph();
chunk = pt.getChunk(" 仓库名称:", 12, Font.NORMAL);
paragraph.add(chunk);
chunk = pt.getChunk(warehouse.getName(), 12, Font.UNDERLINE);
paragraph.add(chunk);
chunk = pt.getChunk(" 仓库地址:", 12, Font.NORMAL);
paragraph.add(chunk);
chunk = pt.getChunk(warehouse.getAddress(), 12, Font.UNDERLINE);
paragraph.add(chunk);
chunk = pt.getChunk(" 仓库电话:", 12, Font.NORMAL);
paragraph.add(chunk);
chunk = pt.getChunk(warehouse.getPhone(), 12, Font.UNDERLINE);
paragraph.add(chunk);
pt.insertContext(paragraph, 12, Font.NORMAL, Element.ALIGN_LEFT);
}
}
pt.insertContext("三、提货相关费用以本合同第一条为准,以实际出库码单作为结算依据,如有其它未列明的费用,乙方自理。", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("四、验收质量标准:按货物生产厂商相关质量、技术标准验收。", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("五、数量异议:双方约定磅差千分之三以内为合理范围,超出合理范围,封存货物后可通过第三方机构复磅。", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("六、质量异议的期限:需方在提货后5 日内提出书面异议并封存货物,供方依据生产厂商标准处理相关质量问题,逾期提出异议或提出异议后对货物继续进行加工的,视为无异议;协议品,乙方不向甲方提出质量异议。", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("七、结算方式及期限:本合同货款为现款含税价,乙方应于本合同签订后当日内付清全款;若以承兑汇票方式付款的,按甲方财务政策计算贴息费用;甲方确认收到全额货款后,乙方可凭甲方提供的有效凭证提货。", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("八、结算银行:\n 收款银行1:\n 账户名称:上海钢银电子商务有限公司 \n 开户行:中国银行上海祁连山路支行\n 账号:437766844376\n 行号:104290040083\n 收款银行2:\n 账户名称:上海钢银电子商务有限公司\n 开户行:中国建设银行股份有限公司上海吴淞支行\n 账号:31001526100050015124\n 行号:105290068059", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("九、违约责任:若乙方未能按照本合同第七条规定将货款付给甲方,甲方有权解除本合同,并自行处理该批货 物,乙方应当承担因此给甲方造成的所有损失。如有其他违约,由违约方承担责任,依照《中华人民共和国合同法 》的相关规定执行。", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("十、合同争议的解决方式:本合同项下发生的争议,由双方当事人协商解决,协商不成,可依法向合同签订地 人民法院起诉。", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext("十一、本合同传真件盖章有效。", 12, Font.NORMAL, Element.ALIGN_LEFT);
pt.insertContext1("", 12, Font.NORMAL, Element.ALIGN_LEFT);
//生成2列表格
aTable = new PdfPTable(2);
//设置表格具体宽度
aTable.setWidthPercentage(100);
//设置每一列所占的长度
aTable.setWidths(new int[]{ 45, 55});
String str = " 甲 方\n";
str = str + "单位名称:上海钢银电子商务有限公司\n";
str = str + "单位地址:上海市宝山区园丰路68号\n";
str = str + "法定代表人:朱军红\n";
str = str + "委托代理人:\n";
str = str + "电话:\n";
str = str + "传真:\n";
str = str + "税号:310113671173033";
cell = pt.newCell1(str, 12, 1);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setHorizontalAlignment(Element.ALIGN_TOP);
aTable.addCell(cell);
str = " 乙 方\n";
str = str + "单位名称:" + orderContractVO.getMemberName() + "\n";
str = str + "单位地址:" + orderContractVO.getMemberAddress() + "\n";
str = str + "法定代表人:\n";
str = str + "委托代理人:" + orderContractVO.getMemberAdmin() + "\n";
str = str + "电话:" + orderContractVO.getMemberPhone() + "\n";
str = str + "传真:" + orderContractVO.getMemberFax() + "\n";
str = str + "开户银行:" + orderContractVO.getMemberBank() + "\n";
str = str + "账号:" + orderContractVO.getMemberAccount() + "\n";
str = str + "税号:" + orderContractVO.getMemberTax();
cell = pt.newCell2(str, 12, 1);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setHorizontalAlignment(Element.ALIGN_TOP);
aTable.addCell(cell);
pt.getDocument().add(aTable);
return pt;
}
private static String getSpace(int len)
{
String str = "";
if (len > 0)
{
str = String.format("%" + len + "d", 0).replace("0", " ");
}
return str;
}
/**
* 四舍五入小数
*
* @param finalDouble
* @param num 小数位数
*
* @return
*/
public static String roundDouble(Object arg1, Object arg2)
{
double finalDouble = (arg1 == null ? 0.0 : NumberUtils.parseDouble(arg1.toString().trim()));
int num = (arg2 == null ? 0 : NumberUtils.parseInt(arg2.toString().trim()));
String s = String.valueOf(NumberTools.roundDouble(finalDouble, num));
int i = s.indexOf("."); // 判断小数点后是否有num位数字
int differ = (i + 1 + num) - s.length();
if (differ > 0) // 如果没有则将空余的补0
{
for (int j = 0; j < differ; j++)
{
s += "0";
}
}
return s;
}
}
PdfUtils
package com.banksteel.order.utils.pdf;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfWriter;
/**
* 根据itext提供的java类库,构建word模板,并添加相应的内容,从而导出word报告;平台不相关
* 需要引入iText-2.1.7.jar;iTextAsian.jar;iText-rtf-2.1.7.jar
*
* @author zhangyf
*/
public class PdfUtils
{
private static String imagePath = "/home/assets/img/contract/";
// private static String imagePath = "d:\\";//本地运行
private Document document;
private BaseFont bfChinese;
public Document getDocument()
{
return this.document;
}
/**
* 打开document
*
* @param paperType 纸张类型0.纵向,1.横向
* @param filePath 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
* @throws DocumentException
* @throws IOException
*/
public void openDocument(PdfUtils pt,int paperType, String filePath, String adminName, String adminPhone) throws DocumentException, IOException
{
// 设置中文字体
try
{
//bfChinese = BaseFont.createFont("D:/simsun.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// bfChinese = BaseFont.createFont("C:/Windows/Fonts/simsun.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//本地
bfChinese = BaseFont.createFont("/usr/share/fonts/chinese/TrueType/simsun.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
catch (DocumentException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
if (paperType == 0)
{
Rectangle pageSize = new Rectangle(677, 960); // 设置文档大小
this.document = new Document(pageSize);
this.document.setMargins(this.document.leftMargin(), this.document.rightMargin(), 10, this.document.bottomMargin());
}
else
{
Rectangle pageSize = new Rectangle(960, 677); // 设置文档大小
this.document = new Document(pageSize);
}
// 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
PdfWriter.getInstance(this.document, new FileOutputStream(filePath));
// 设置页眉
insertHeader(paperType, adminName, adminPhone);
// 设置页脚
insertFooter(paperType);
// 打开document
this.document.open();
}
/**
* 页眉
*/
public void insertHeader(int paperType, String adminName, String adminPhone) throws DocumentException, IOException
{
// 添加页眉
Image headerImage1 = Image.getInstance(imagePath + "header1.png");
headerImage1.setAlignment(Image.ALIGN_LEFT);
headerImage1.scalePercent(30, 29);
headerImage1.setBorder(0);
Image headerImage2 = Image.getInstance(imagePath + "header2.jpg");
headerImage2.setAlignment(Image.ALIGN_CENTER);
if (paperType == 0)
{
headerImage2.scalePercent(25, 23);
}
else
{
headerImage2.scalePercent(36, 23);
}
headerImage2.setBorder(0);
headerImage2.setAbsolutePosition(18, 880);
Paragraph headerParagraph = new Paragraph();
headerParagraph.add(headerImage1);
headerParagraph.add(getHeaderTexParagraph(adminName, adminPhone));
headerParagraph.add(headerImage2);
HeaderFooter header = new HeaderFooter(headerParagraph,false);
header.setBorder(Rectangle.NO_BORDER);
this.document.setHeader(header);
}
public Paragraph getHeaderTexParagraph(String adminName, String adminPhone)
{
Paragraph paragraph = new Paragraph();
adminName = adminName.replace("\r\n", "").replace("\n", "");
adminPhone = adminPhone.replace("\r\n", "").replace("\n", "");
Chunk chunk = getChunk(getSpace(93 - (adminName+adminPhone).length()) + "经办人员:", 10, Font.NORMAL);
paragraph.add(chunk);
chunk = getChunk(" " + adminName + " ", 10, Font.UNDERLINE);
paragraph.add(chunk);
chunk = getChunk(" 联系方式:", 10, Font.NORMAL);
paragraph.add(chunk);
chunk = getChunk(" " + adminPhone + " ", 10, Font.UNDERLINE);
paragraph.add(chunk);
return paragraph;
}
/**
* 页脚
*/
public void insertFooter(int paperType) throws DocumentException
{
Font font = new Font(bfChinese, 8, Font.NORMAL);
HeaderFooter footer = null;
if (paperType == 0)
{
footer = new HeaderFooter(new Phrase("第 ", font), new Phrase(" 页\n 钢铁电商 赢在钢银", font));
}
else
{
footer = new HeaderFooter(new Phrase("第 ", font), new Phrase(" 页\n 钢铁电商 赢在钢银", font));
}
footer.setAlignment(HeaderFooter.ALIGN_CENTER);
footer.setBorder(Rectangle.NO_BORDER);
this.document.setFooter(footer);
}
/**
* 标题
*
* @throws DocumentException
*/
public void insertTitle(String title) throws DocumentException
{
Paragraph paragraph = new Paragraph();
Chunk chunk = getChunk(title, 18, Font.BOLD);
paragraph.add(chunk);
// 设置标题格式对齐方式
paragraph.setAlignment(Element.ALIGN_CENTER);
paragraph.setSpacingBefore(5);
paragraph.setSpacingAfter(0);
paragraph.setLeading(18f);
this.document.add(paragraph);
}
/**
* 一级目录
*
* @param titleStr 标题
* @param fontsize 字体大小
* @param fontStyle 字体样式
* @param elementAlign 对齐方式
* @throws DocumentException
*/
public void insertTitleFir(String titleStr,int fontsize,int fontStyle,int elementAlign) throws DocumentException
{
Paragraph paragraph = new Paragraph();
Chunk chunk = getChunk(titleStr, fontsize, fontStyle);
paragraph.add(chunk);
// 设置标题格式对齐方式
paragraph.setAlignment(elementAlign);
paragraph.setSpacingBefore(5);
paragraph.setSpacingAfter(0);
paragraph.setLeading(18f);
this.document.add(paragraph);
}
/**
* 正文(首行缩进)
*
* @param contextStr 内容
* @param fontsize 字体大小
* @param fontStyle 字体样式
* @param elementAlign 对齐方式
* @throws DocumentException
*/
public void insertContext(String contextStr,int fontsize,int fontStyle,int elementAlign) throws DocumentException
{
Paragraph paragraph = new Paragraph();
Chunk chunk = getChunk(contextStr, fontsize, fontStyle);
paragraph.add(chunk);
//设置行距
paragraph.setLeading(18f);
// 正文格式左对齐
paragraph.setAlignment(elementAlign);
// 离上一段落(标题)空的行数
paragraph.setSpacingBefore(5);
// 设置第一行空的列数
paragraph.setFirstLineIndent(20);
this.document.add(paragraph);
}
/**
* 正文(首行缩进)
*
* @param contextStr 内容
* @param fontsize 字体大小
* @param fontStyle 字体样式
* @param elementAlign 对齐方式
* @throws DocumentException
*/
public void insertContext(Paragraph paragraph,int fontsize,int fontStyle,int elementAlign) throws DocumentException
{
//设置行距
paragraph.setLeading(18f);
// 正文格式左对齐
paragraph.setAlignment(elementAlign);
// 离上一段落(标题)空的行数
paragraph.setSpacingBefore(5);
// 设置第一行空的列数
paragraph.setFirstLineIndent(20);
this.document.add(paragraph);
}
/**
* 正文(首行不缩进)
*
* @param contextStr 内容
* @param fontsize 字体大小
* @param fontStyle 字体样式
* @param elementAlign 对齐方式
* @throws DocumentException
*/
public void insertContext1(String contextStr,int fontsize,int fontStyle,int elementAlign) throws DocumentException
{
Paragraph paragraph = new Paragraph();
Chunk chunk = getChunk(contextStr, fontsize, fontStyle);
paragraph.add(chunk);
//设置行距
paragraph.setLeading(18f);
// 正文格式左对齐
paragraph.setAlignment(elementAlign);
// 离上一段落(标题)空的行数
paragraph.setSpacingBefore(5);
this.document.add(paragraph);
}
/**
* 正文(首行不缩进)
*
* @param contextStr 内容
* @param fontsize 字体大小
* @param fontStyle 字体样式
* @param elementAlign 对齐方式
* @throws DocumentException
*/
public void insertContext1(Paragraph paragraph,int fontsize,int fontStyle,int elementAlign) throws DocumentException
{
//设置行距
paragraph.setLeading(18f);
// 正文格式左对齐
paragraph.setAlignment(elementAlign);
// 离上一段落(标题)空的行数
paragraph.setSpacingBefore(5);
this.document.add(paragraph);
}
/**
* 插入合同图片
*/
public Image getHTZImg() throws DocumentException, IOException
{
Image image = Image.getInstance(imagePath + "contract.png");
image.setAlignment(Image.ALIGN_LEFT|Image.UNDERLYING);
image.setBorder(0);
image.scalePercent(80, 80);
Random random = new Random();
image.setRotationDegrees(random.nextInt(360));//旋转
return image;
}
/**
* 生成块内容
*
* @param context 内容
* @param fontsize 字体大小
* @param fontStyle 字体样式
* @return
*/
public Chunk getChunk(String context,int fontsize, int fontStyle)
{
Chunk chunk = new Chunk();
Font font = new Font(bfChinese, fontsize, fontStyle);
chunk.append(context);
chunk.setFont(font);
return chunk;
}
/**
* 关闭document
*
* @throws DocumentException
*/
public void closeDocument() throws DocumentException
{
this.document.close();
}
/**
* 新增一行 默认上下左右居中 默认高度20f
*
* @param aTable
* @param text
* @param fixedHeight
*/
public PdfPCell newCell(String text, int fontsize, int colspan)
{
Font font = new Font(bfChinese, fontsize, Font.NORMAL);
PdfPCell pCell = new PdfPCell(new Phrase(text, font));
pCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
pCell.setColspan(colspan);
return pCell;
}
/**
* 新增一行 默认上下左右居中 默认高度20f
*
* @param aTable
* @param text
* @param fixedHeight
*/
public PdfPCell newCell1(String text, int fontsize, int colspan)
{
PdfPCell pCell = new PdfPCell();
try
{
Chunk ck = getChunk(text, fontsize, Font.NORMAL);
pCell.addElement(ck);
ck = new Chunk(getHTZImg(), 30, 38);
pCell.addElement(ck);
}
catch (DocumentException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
pCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pCell.setVerticalAlignment(Element.ALIGN_TOP);
pCell.setColspan(colspan);
return pCell;
}
/**
* 新增一行 默认上下左右居中 默认高度20f
*
* @param aTable
* @param text
* @param fixedHeight
*/
public PdfPCell newCell2(String text, int fontsize, int colspan)
{
PdfPCell pCell = new PdfPCell();
Chunk ck = getChunk(text, fontsize, Font.NORMAL);
pCell.addElement(ck);
pCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pCell.setVerticalAlignment(Element.ALIGN_TOP);
pCell.setColspan(colspan);
return pCell;
}
/**
* 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
* @param String s 需要得到长度的字符串
* @return int 得到的字符串长度
*/
public static int length(String s)
{
s = s.replaceAll("[^\\x00-\\xff]", "**");
int length = s.length();
return length;
}
private static String getSpace(int len)
{
String str = "";
if (len > 0)
{
str = String.format("%" + len + "d", 0).replace("0", " ");
}
return str;
}
}
AppUtils
package com.banksteel.order.utils;
import java.io.File;
public abstract class AppUtils
{
private static final String APPLICATION_ROOT_PATH = "/home";
public static String getWebRootPath()
{
return APPLICATION_ROOT_PATH;
}
/**
* 根据指定目录路径创建一个目录
*
* @param sFolder 完整目录路径
* @return true 创建成功,false 创建失败
*/
public static boolean mkdirs(String sFolder)
{
File file = new File(sFolder);
if (file.exists())
{
if (!file.isDirectory())
{
return file.mkdirs();
}
else
{
return true;
}
}
else
{
return file.mkdirs();
}
}
public static String getWebRealPath(String path)
{
String appRootPath = APPLICATION_ROOT_PATH;
if (appRootPath != null)
{
if (path.startsWith(File.separator))
{
appRootPath += path + File.separator;
}
else
{
appRootPath += File.separator + path + File.separator;
}
}
return appRootPath;
}
}
FastDFS分布式文件系统操作客户端 .
package cn.mysteel.mfdfs;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClientExtend;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
/**
* @description: FastDFS分布式文件系统操作客户端 .
* @projectName:shgl-mfdfs
* @className:FastDFSClient.java
* @see: cn.mysteel.mfdfs
* @createTime:2015年4月6日 下午5:50:17
* @version 1.0
*/
public class FastDFSClient {
private static final String CONF_FILENAME = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "/config/fdfs_client.conf";
//private static final String CONF_FILENAME = "src/main/resources/config/fdfs_client.conf";
private static StorageClientExtend storageClient1 = null;
private static Logger logger = Logger.getLogger(FastDFSClient.class);
/**
* 只加载一次.
*/
static {
try {
logger.info("=== CONF_FILENAME:" + CONF_FILENAME);
ClientGlobal.init(CONF_FILENAME);
TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group);
TrackerServer trackerServer = trackerClient.getConnection();
if (trackerServer == null) {
logger.error("getConnection return null");
}
StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
if (storageServer == null) {
logger.error("getStoreStorage return null");
}
storageClient1 = new StorageClientExtend(trackerServer, storageServer);
} catch (Exception e) {
logger.error(e);
}
}
/**
*
* @param file
* 文件
* @param fileName
* 文件名
* @return 返回Null则为失败
*/
public static String uploadFile(InputStream fis, String fileName) {
try {
NameValuePair[] meta_list = null; // new NameValuePair[0];
byte[] file_buff = null;
if (fis != null) {
int len = fis.available();
file_buff = new byte[len];
fis.read(file_buff);
}
String fileid = storageClient1.upload_file1(file_buff, getFileExt(fileName), meta_list);
return fileid;
} catch (Exception ex) {
logger.error(ex);
return null;
}finally{
if (fis != null){
try {
fis.close();
} catch (IOException e) {
logger.error(e);
}
}
}
}
/**
*
* @param file
* 文件
* @param fileName
* 文件名
* @return 返回Null则为失败
*/
public static String uploadFile(File file, String fileName) {
FileInputStream fis = null;
try {
NameValuePair[] meta_list = null; // new NameValuePair[0];
fis = new FileInputStream(file);
byte[] file_buff = null;
if (fis != null) {
int len = fis.available();
file_buff = new byte[len];
fis.read(file_buff);
}
String fileid = storageClient1.upload_file1(file_buff, getFileExt(fileName), meta_list);
return fileid;
} catch (Exception ex) {
logger.error(ex);
return null;
}finally{
if (fis != null){
try {
fis.close();
} catch (IOException e) {
logger.error(e);
}
}
}
}
/**
* 根据组名和远程文件名来删除一个文件
*
* @param groupName
* 例如 "group1" 如果不指定该值,默认为group1
* @param fileName
* 例如"M00/00/00/wKgxgk5HbLvfP86RAAAAChd9X1Y736.jpg"
* @return 0为成功,非0为失败,具体为错误代码
*/
public static int deleteFile(String groupName, String fileName) {
try {
int result = storageClient1.delete_file(groupName == null ? "group1" : groupName, fileName);
return result;
} catch (Exception ex) {
logger.error(ex);
return 0;
}
}
/**
* 根据fileId来删除一个文件(我们现在用的就是这样的方式,上传文件时直接将fileId保存在了数据库中)
*
* @param fileId
* file_id源码中的解释file_id the file id(including group name and filename);例如 group1/M00/00/00/ooYBAFM6MpmAHM91AAAEgdpiRC0012.xml
* @return 0为成功,非0为失败,具体为错误代码
*/
public static int deleteFile(String fileId) {
try {
int result = storageClient1.delete_file1(fileId);
return result;
} catch (Exception ex) {
logger.error(ex);
return 0;
}
}
/**
* 修改一个已经存在的文件
*
* @param oldFileId
* 原来旧文件的fileId, file_id源码中的解释file_id the file id(including group name and filename);例如 group1/M00/00/00/ooYBAFM6MpmAHM91AAAEgdpiRC0012.xml
* @param file
* 新文件
* @param filePath
* 新文件路径
* @return 返回空则为失败
*/
public static String modifyFile(String oldFileId, File file, String filePath) {
String fileid = null;
try {
// 先上传
fileid = uploadFile(file, filePath);
if (fileid == null) {
return null;
}
// 再删除
int delResult = deleteFile(oldFileId);
if (delResult != 0) {
return null;
}
} catch (Exception ex) {
logger.error(ex);
return null;
}
return fileid;
}
/**
* 文件下载
*
* @param fileId
* @return 返回一个流
*/
public static InputStream downloadFile(String fileId) {
try {
byte[] bytes = storageClient1.download_file1(fileId);
InputStream inputStream = new ByteArrayInputStream(bytes);
return inputStream;
} catch (Exception ex) {
logger.error(ex);
return null;
}
}
/**
* 获取文件后缀名(不带点).
*
* @return 如:"jpg" or "".
*/
private static String getFileExt(String fileName) {
if (StringUtils.isBlank(fileName) || !fileName.contains(".")) {
return "";
} else {
return fileName.substring(fileName.lastIndexOf(".") + 1); // 不带最后的点
}
}
}