Commit c3d62b18 authored by 吴琼's avatar 吴琼

交易凭证

parent 0a28b76a
......@@ -253,7 +253,26 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
</dependencies>
</project>
package cn.quantgroup.customer.entity;
import lombok.*;
import javax.persistence.*;
@Entity
@Table(name = "transaction_receipt_record")
@ToString
@Builder
@Getter
@Setter
@AllArgsConstructor
public class TransactionReceiptRecord {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Integer userId;
@Column(name = "user_name")
private String userName;
@Column(name = "serial_no")
private String serialNo;
@Column(name = "import_status")
private Integer importStatus;
@Column(name = "export_status")
private Integer exportStatus;
@Column(name = "order_no")
private String orderNo;
@Column(name = "batch_no")
private Long batchNo;
@Column(name = "sign_status")
private Long signStatus;
@Column(name = "pdf_status")
private Long pdfStatus;
public TransactionReceiptRecord() {
}
}
package cn.quantgroup.customer.repo;
import cn.quantgroup.customer.entity.TransactionReceiptRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import javax.transaction.Transactional;
import java.util.List;
public interface TransactionReceiptRecordRepo extends JpaRepository<TransactionReceiptRecord, Long>, JpaSpecificationExecutor<TransactionReceiptRecord> {
@Query(value = "select max(batch_no) from transaction_receipt_record where export_status =?1 ", nativeQuery = true)
Long findMaxbatchNo(Integer status);
@Query(value = "select count(1) from transaction_receipt_record where user_id =?1 and user_name =?2 and order_no =?3 ", nativeQuery = true)
Long selectCountByUserIdAndOrderNo(Integer userId,String userName,String orderNo);
@Query(value = "select * from transaction_receipt_record where import_status = ?1 ", nativeQuery = true)
List<TransactionReceiptRecord> selectRecordsByImportStatus(Integer status);
@Query(value = "select count(1) from transaction_receipt_record where import_status =?1 ", nativeQuery = true)
Long selectCountByImportStatus(Integer status);
@Modifying
@Transactional
@Query(value = "update transaction_receipt_record set import_status = ?1 where order_no =?2 ", nativeQuery = true)
Long updateTransactionStatusByImportStatus(Integer status,String orderNo);
@Modifying
@Transactional
@Query(value = "update transaction_receipt_record set sign_status = ?1 where order_no =?2 ", nativeQuery = true)
Long updatePDFStatusByOrderNo(Integer status,String orderNo);
}
package cn.quantgroup.customer.rest;
import cn.quantgroup.customer.rest.param.transactionreceipt.TransactionReceiptRecordQuery;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.transaction.*;
import cn.quantgroup.customer.service.ITransactionReceiptRecordService;
import cn.quantgroup.customer.service.http.IHttpService;
import cn.quantgroup.customer.util.FileToZip;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Slf4j
@RestController
@RequestMapping("/transactionReceiptRecord")
public class TransactionReceiptRecordRest {
@Autowired
private ITransactionReceiptRecordService transactionReceiptRecordService;
@Autowired
private IHttpService httpService;
/**
* 根据筛选条件进行查询
* @param query
* @return
*/
@RequestMapping("/orderQuery/query_page")
public JsonResult queryPage(@RequestBody TransactionReceiptRecordQuery query) {
if (query.getPageNo()== null || query.getPageNo() < 1) {
log.error("[TransactionReceiptRecordRest_queryPage]查询参数pageNumber错误,pageNo={}", query.getPageNo());
return JsonResult.buildErrorStateResult("查询参数pageNo错误");
}
Integer pageNo = query.getPageNo() - 1;
query.setPageNo(pageNo);
if (query.getPageSize() == null) {
log.error("[workOrderRest_queryPage]查询参数pageSize错误,pageSize={}", query.getPageSize());
return JsonResult.buildErrorStateResult("查询参数pageSize错误");
}
return transactionReceiptRecordService.findRecordsByQuery(query);
}
/**
* 导入excel表格
*/
@RequestMapping("/orderQuery/importTransactionReceiptRecord")
public JsonResult importTransactionReceiptRecord(MultipartFile file) {
try{
return transactionReceiptRecordService.importTransactionReceiptRecord(file);
}catch(IOException e){
e.printStackTrace();
return JsonResult.buildErrorStateResult("上传文件出现错误");
}
}
/**
* 导出压缩包之前先校验
*/
@RequestMapping("/orderQuery/checkCanExport")
public JsonResult checkCanExport() {
return transactionReceiptRecordService.checkCanExport();
}
@RequestMapping("/test")
public JsonResult test() {
String userIds="70356056,70356055";
String url ="http://passportapi-qa2.liangkebang.net/api/sync/listByUserIds";
Map param = Maps.newHashMap();
param.put("userIds",userIds);
String userResult = httpService.get(url,param);
JSONObject jsonObject = JSONObject.parseObject(userResult);
String dataStr = jsonObject.getString("data");
JSONArray userArray = JSONArray.parseArray(dataStr);
for(int i=0;i<userArray.size();i++){
JSONObject object= (JSONObject) userArray.get(i);
}
return JsonResult.buildSuccessResult("success", userArray);
}
@RequestMapping("/testKdsp")
public JsonResult testKdsp() {
String url = "http://kdsp-operation-qa2.liangkebang.net/api/kdsp/op/fa-cui/transaction-proof/query";
try {
Map<String, String> header = Maps.newHashMap();
header.put("Content-type", "application/json");
header.put("qg-tenant-id", "560761");
Map param = Maps.newHashMap();
List<Map> paramList =new ArrayList<>();
//param.put("userId", 70356062);
//param.put("orderNo", "1495958974917529600");
param.put("userId", 70356067);
param.put("orderNo", "1496312159003762688");
paramList.add(param);
//得到json字符串
String result = httpService.post(url, header, paramList);
//转换成json 对象
JSONObject json =JSONObject.parseObject(result);
String jsonResult = json.getString("data");
String businessCode = json.getString("businessCode");
if(!"0000".equals(businessCode)){
return JsonResult.buildErrorStateResult("订单信息查询报错");
}
if(jsonResult != null){
JSONObject jsonObject = JSONObject.parseObject(jsonResult);
JSONArray jsonArray = jsonObject.getJSONArray("dataList");
if(jsonArray.isEmpty()){
return JsonResult.buildErrorStateResult("未查询到对应的订单信息");
}
List<TransactionReceiptVO> transactionReceiptVOList = jsonArray.toJavaList(TransactionReceiptVO.class);
//生成pdf
String basicPath="D:\\交易凭证0222";
String filePath =basicPath +"\\"+"wuq";
FileToZip.mkdir(filePath);
filePath = filePath +"\\"+"1493905629528739840"+".pdf";
transactionReceiptRecordService.generatePDF(transactionReceiptVOList.get(0),filePath);
}
return JsonResult.buildSuccessResult("success",null);
} catch (Exception e) {
log.error("[TransactionReceiptRecordServiceImpl][exportZipFile] 网络通讯异常,userId:{},ex:{}", e.getMessage());
return JsonResult.buildErrorStateResult(e.getMessage());
}
}
/**
* 后台更新交易凭证状态
* @return
*/
@RequestMapping("/orderQuery/updateTransactionRecordsStatus")
public JsonResult updateTransactionRecordsStatus() {
return transactionReceiptRecordService.updateTransactionRecordsStatus();
}
//导出压缩包
@RequestMapping("/orderQuery/exportTransactionZipFile")
public JsonResult exportTransactionZipFile() {
try{
return transactionReceiptRecordService.exportZipFile();
}catch(Exception e){
e.printStackTrace();
return JsonResult.buildErrorStateResult("导出文件出现错误");
}
}
//pdf签章后回调接口更新pdf是否签章成功
@RequestMapping("/orderQuery/updateSignStatus")
public JsonResult updateSignStatus(@RequestBody TransactionReceiptRecordQuery query) {
try{
return transactionReceiptRecordService.updatePDFSignStatus(query.getSuccessList(),query.getFailList());
}catch(Exception e){
e.printStackTrace();
return JsonResult.buildErrorStateResult("更新签章状态失败");
}
}
}
package cn.quantgroup.customer.rest.param.transactionreceipt;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.validation.constraints.NotNull;
import java.util.List;
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class TransactionReceiptRecordQuery {
/**
* 交易单号
*/
private String orderNo;
/**
* 导入状态
*/
private String importStatus;
/**
* 导出状态
*/
private String exportStatus;
/**
* 当前页数
*/
@NotNull(message = "当前页数不能为空")
private Integer pageNo;
/**
* 每页多少条数据
*/
@NotNull(message = "每页条数不能为空")
private Integer pageSize;
//更新成功list
private List<String> successList;
//更新失败list
private List<String> failList;
}
package cn.quantgroup.customer.rest.vo.transaction;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.List;
@Data
public class LogisticsVO {
/**
* 发货时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String postTime;
/**
* 确认收货时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String completeTime;
/**
* 订单状态
*/
private String statusName;
/**
* 订单类型
*/
private String typeName;
/**
* 物流公司
*/
private String expressCompany;
/**
* 物流单号
*/
private String deliveryNo;
/**
* 物流详情
*/
private List<logisticsDetailVO> detailList;
}
package cn.quantgroup.customer.rest.vo.transaction;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@Data
public class OrderVO {
/**
* 订单号
*/
private String orderNo="/";
/**
* 供应商订单ID
*/
private String merchantOrderId ="/";
/**
* 供应链订单号
*/
private String keyStoneOrderNo="/";
/**
* 商品渠道
*/
private String skuSourceName = "/";
/**
* 下单平台
*/
private String tenantName="/";
/**
* 平台账号id
*/
private Long userId;
/**
* 平台绑定手机号
*/
private String mobile="/";
/**
* 订单创建时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String createdAt;
/**
* 支付完成时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String payTime;
/**
* 订单金额
*/
private String orderAmount;
/**
* 实付金额
*/
private String payAmount;
/**
* 支付方式
*/
private String payTypeName;
}
package cn.quantgroup.customer.rest.vo.transaction;
import lombok.Data;
@Data
public class ReceiverVO {
/**
* 收货人电话
*/
private String receiverMobile;
/**
* 收货人姓名
*/
private String receiverName;
/**
* 收货地址
*/
private String fullAddress;
}
package cn.quantgroup.customer.rest.vo.transaction;
import lombok.Data;
@Data
public class SkuVO {
/**
* 商品名称
*/
private String skuName;
/**
* 商品属性
*/
private String skuAttr;
/**
* 商品数量
*/
private String count;
}
package cn.quantgroup.customer.rest.vo.transaction;
import lombok.Data;
@Data
public class TransactionReceiptRecordVO {
private Integer userId;
private String userName;
private String serialNo;
private Integer importStatus;
private Integer exportStatus;
private String tradeNo;
private Integer id;
}
package cn.quantgroup.customer.rest.vo.transaction;
import lombok.Data;
import java.util.List;
@Data
public class TransactionReceiptVO {
/**
* 订单信息
*/
private OrderVO order;
/**
* 商品信息
*/
private List<SkuVO> skuList;
/**
* 物流信息
*/
private List<LogisticsVO> logisticsList;
/**
* 物流信息
*/
private ReceiverVO receiver;
}
package cn.quantgroup.customer.rest.vo.transaction;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@Data
public class logisticsDetailVO {
/**
* 时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String time;
/**
*描述
*/
private String desc;
}
package cn.quantgroup.customer.service;
import cn.quantgroup.customer.rest.vo.transaction.TransactionReceiptRecordVO;
import cn.quantgroup.customer.rest.param.transactionreceipt.TransactionReceiptRecordQuery;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.transaction.TransactionReceiptVO;
import org.springframework.data.domain.Page;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
public interface ITransactionReceiptRecordService {
JsonResult<Page<TransactionReceiptRecordVO>> findRecordsByQuery(TransactionReceiptRecordQuery query);
JsonResult importTransactionReceiptRecord(MultipartFile file) throws IOException;
JsonResult exportZipFile() throws Exception;
JsonResult checkCanExport();
JsonResult updateTransactionRecordsStatus();
JsonResult updatePDFSignStatus(List<String> sucessList, List<String>failList);
void generatePDF(TransactionReceiptVO transactionReceiptVO, String filePath);
}
package cn.quantgroup.customer.service.impl;
import cn.quantgroup.customer.entity.TransactionReceiptRecord;
import cn.quantgroup.customer.exception.BusinessException;
import cn.quantgroup.customer.rest.vo.transaction.TransactionReceiptRecordVO;
import cn.quantgroup.customer.repo.TransactionReceiptRecordRepo;
import cn.quantgroup.customer.rest.param.transactionreceipt.TransactionReceiptRecordQuery;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.transaction.*;
import cn.quantgroup.customer.service.ITransactionReceiptRecordService;
import cn.quantgroup.customer.service.http.IHttpService;
import cn.quantgroup.customer.util.ExcelUtil;
import cn.quantgroup.customer.util.FileToZip;
import cn.quantgroup.customer.util.ITextPDFUtil;
import cn.quantgroup.customer.util.SFTPUtil;
import cn.quantgroup.user.retbean.XUser;
import cn.quantgroup.user.vo.UserSysResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.persistence.criteria.Predicate;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service("transactionReceiptRecordService")
public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptRecordService {
@Autowired
private TransactionReceiptRecordRepo transactionReceiptRecordRepo;
@Autowired
private ExcelUtil excelUtil;
@Autowired
private IHttpService httpService;
@Autowired
private UserSdkImpl userSdk;
@Value("${kdsp-operation}")
private String kdspOperationUrl;
@Value("${passportapi2.http}")
private String userSysUrl;
//@Value("${customer.host}")
private String host;
//@Value("${customer.port}")
private int port;
//@Value("${customer.username}")
private String username;
//@Value("${customer.privateKey}")
private String password;
//@Value("${customer.basePath}")
private String basePath;
@Override
public JsonResult<Page<TransactionReceiptRecordVO>> findRecordsByQuery(TransactionReceiptRecordQuery query) {
Page<TransactionReceiptRecord> page = transactionReceiptRecordRepo.findAll((root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
//交易单号
if (Objects.nonNull(query.getOrderNo())) {
predicates.add(criteriaBuilder.equal(root.get("orderNo"), query.getOrderNo()));
}
if (StringUtils.isNotEmpty(query.getImportStatus())) {
predicates.add(criteriaBuilder.equal(root.get("importStatus"), query.getImportStatus()));
}
if (StringUtils.isNotEmpty(query.getExportStatus())) {
predicates.add(criteriaBuilder.equal(root.get("exportStatus"), query.getExportStatus()));
}
// 设置查询条件
criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
// 指定排序
//criteriaQuery.orderBy(criteriaBuilder.desc(root.get("id")));
return criteriaQuery.getRestriction();
}, new PageRequest(query.getPageNo(), query.getPageSize()));
Page<TransactionReceiptRecordVO> map = page.map(it -> {
TransactionReceiptRecordVO workOrderVO = new TransactionReceiptRecordVO();
workOrderVO.setTradeNo(it.getOrderNo());
workOrderVO.setUserId(it.getUserId());
workOrderVO.setUserName(it.getUserName());
workOrderVO.setSerialNo(it.getSerialNo());
workOrderVO.setExportStatus(it.getExportStatus());
workOrderVO.setImportStatus(it.getImportStatus());
workOrderVO.setId(workOrderVO.getId());
return workOrderVO;
});
if (map != null) {
return JsonResult.buildSuccessResult("查询成功", map);
} else {
return JsonResult.buildErrorStateResult("查询失败");
}
}
@Override
public JsonResult importTransactionReceiptRecord(MultipartFile file) throws IOException {
//查询未导出数据最大批次号
Long maxBatchNo = transactionReceiptRecordRepo.findMaxbatchNo(0);
if(maxBatchNo == null || maxBatchNo.longValue() ==0l){
maxBatchNo = 1l;
}
//读取所有数据
List<TransactionReceiptRecord> readList = read(file.getOriginalFilename(), file.getInputStream());
//0代表初始状态,1代表导入成功,2代表导入失败
for(TransactionReceiptRecord record : readList){
//保存时如果有其中一项为空则默认为导入失败,其他则默认初始状态
if(record.getUserId() ==null || record.getUserId() ==0 || StringUtils.isEmpty(record.getUserName()) || StringUtils.isEmpty(record.getOrderNo())){
record.setImportStatus(2);
//默认导出失败
record.setExportStatus(2);
}else{
record.setImportStatus(0);
//默认导出初始状态
record.setExportStatus(0);
}
//存储批次号
record.setBatchNo(maxBatchNo);
transactionReceiptRecordRepo.save(record);
}
return JsonResult.buildSuccessResult("success",null);
}
public List<TransactionReceiptRecord> read(String filename, InputStream is) throws IOException {
/**
* 总行数
*/
int totalRows = 0;
/**
* 总列数
*/
int totalCols = 0;
/** 验证文件是否合法 */
if (!excelUtil.validateExcel(filename)) {
throw new RuntimeException("文件格式不合法 ");
}
/** 判断文件的类型,是2003还是2007 */
Workbook wb = null;
if (!excelUtil.isExcel2007(filename)) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
List<TransactionReceiptRecord> recordList = new ArrayList<>();
/** 得到第一个shell */
Sheet sheet = wb.getSheetAt(0);
/** 得到Excel的行数 */
totalRows = sheet.getPhysicalNumberOfRows();
/** 得到Excel的列数 */
if (totalRows >= 1 && sheet.getRow(0) != null) {
totalCols = sheet.getRow(0).getPhysicalNumberOfCells();
}
/** 循环Excel的行 */
for (int r = 0; r < totalRows; r++) {
if(r == 0){
continue;
}
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
/** 循环Excel的列 */
for (int c = 0; c < totalCols; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类型
switch (cell.getCellType()) {
case 0: // 数字
cellValue = cell.getNumericCellValue() + "";
break;
case 1: // 字符串
cellValue = cell.getStringCellValue();
break;
case 4: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case 2: // 公式
cellValue = cell.getCellFormula() + "";
break;
case 3: // 空值
cellValue = "";
break;
case 5: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
if(r == 1){
continue;
}
if (org.springframework.util.StringUtils.isEmpty(cellValue)) {
continue;
}
TransactionReceiptRecord record = new TransactionReceiptRecord();
if(c == 1){
record.setSerialNo(cellValue);
}else if(c == 2){
record.setUserId(Integer.valueOf(cellValue));
}else if(c == 3){
record.setUserName(cellValue);
}else if(c == 4){
record.setOrderNo(cellValue);
}
recordList.add(record);
}
}
return recordList;
}
//导出zip压缩包文件
public JsonResult exportZipFile() throws Exception {
//调用电商接口获取对应数据
final String logPre = "TransactionReceiptRecordServiceImpl.exportZipFile";
//查询需要导出的数据-导入成功的数据
List<TransactionReceiptRecord> transactionReceiptRecordList= transactionReceiptRecordRepo.selectRecordsByImportStatus(1);
if(CollectionUtils.isEmpty(transactionReceiptRecordList)){
return JsonResult.buildErrorStateResult("没有可以导出得数据");
}
for(TransactionReceiptRecord record : transactionReceiptRecordList){
Integer userId = record.getUserId();
String orderNo = record.getOrderNo();
//调用kdsp接口获取交易凭证订单信息
String url = kdspOperationUrl + "/api/kdsp/op/fa-cui/transaction-proof/query";
try {
Map<String, String> header = Maps.newHashMap();
header.put("Content-type", "application/json");
header.put("qg-tenant-id", "560761");
Map param = Maps.newHashMap();
if (Objects.nonNull(userId)) {
param.put("userId", userId);
}
if (StringUtils.isNotBlank(orderNo)) {
param.put("orderNo", orderNo);
}
List<Map> paramList =new ArrayList<>();
paramList.add(param);
//得到json字符串
String result = httpService.post(url, header, paramList);
//转换成json 对象
JSONObject json = JSONObject.parseObject(result);
String jsonResult = json.getString("data");
String businessCode = json.getString("businessCode");
//查询报错
if(!"0000".equals(businessCode)){
return JsonResult.buildErrorStateResult("订单信息查询报错");
}
if(jsonResult != null){
JSONObject jsonObject = JSONObject.parseObject(jsonResult);
JSONArray jsonArray = jsonObject.getJSONArray("dataList");
if(jsonArray.isEmpty()){
return JsonResult.buildErrorStateResult("未查询到对应的订单信息");
}
List<TransactionReceiptVO> transactionReceiptVOList = jsonArray.toJavaList(TransactionReceiptVO.class);
if(transactionReceiptVOList.isEmpty()){
return JsonResult.buildErrorStateResult("未查询到对应的订单信息");
}
//生成pdf
String basicPath="D:\\交易凭证0222";
String filePath =basicPath +"\\"+record.getBatchNo()+record.getUserName();
FileToZip.mkdir(filePath);
filePath = filePath+"\\"+record.getOrderNo()+".pdf";
generatePDF(transactionReceiptVOList.get(0),filePath);
//调用电子签章接口
//todo
//保存到文件服务器上
SFTPUtil sftpUtil = new SFTPUtil(username,password,host,port);
sftpUtil.login();
log.info("uploadFile | 成功连接ftp");
//sftpUtil.upload(basePath,directory,okFileName,new ByteArrayInputStream(okFileData));
sftpUtil.logout();
}
} catch (Exception e) {
log.error("[TransactionReceiptRecordServiceImpl][exportZipFile] 网络通讯异常,userId:{},ex:{}", ExceptionUtils.getStackTrace(e));
return JsonResult.buildErrorStateResult(e.getMessage());
}
}
return JsonResult.buildSuccessResult(null,null);
}
/**
* 校验是否可以导出
* @return
*/
@Override
public JsonResult checkCanExport() {
//查询初始状态的数据-如果存在则说明未全部更新状态
Long count = transactionReceiptRecordRepo.selectCountByImportStatus(0);
if(count != null && count > 0){
//异步多线程更新数据
return JsonResult.buildErrorStateResult("导入处理中,请稍后重试");
}else{
return JsonResult.buildSuccessResult("数据全部导入成功",null);
}
}
/**
* 更新交易凭证导入状态
* @return
*/
@Override
public JsonResult updateTransactionRecordsStatus() {
//查询所有初始化的数据
List<TransactionReceiptRecord> transactionReceiptRecordList
= transactionReceiptRecordRepo.selectRecordsByImportStatus(0);
//没有校验成功的放入一个list
List<TransactionReceiptRecord> failList = new ArrayList<>();
if(CollectionUtils.isNotEmpty(transactionReceiptRecordList)){
//创建线程池
//ThreadPoolExecutor threadPool = new ThreadPoolExecutor(20, 50,
// 4, TimeUnit.SECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.AbortPolicy());
// 记录单个任务的执行次数
//CountDownLatch countDownLatch = new CountDownLatch(splitNList.size());
// 对拆分的集合进行批量处理, 先拆分的集合, 再多线程执行
/*for (List<TransactionReceiptRecord> singleList : splitNList) {
// 线程池执行
threadPool.execute(new Thread(new Runnable(){
@Override
public void run() {
for (TransactionReceiptRecord record : singleList) {
// 将每一个对象进行数据封装, 并添加到一个用于存储更新数据的list
// ......
// 任务个数 - 1, 直至为0时唤醒await()
countDownLatch.countDown();
}
}
}));
}
try {
// 让当前线程处于阻塞状态,直到锁存器计数为零
countDownLatch.await();
} catch (InterruptedException e) {
throw new BusinessException("");
}*/
//为了性能每次最多传50个
List<List<TransactionReceiptRecord>> splitNList= splitList(transactionReceiptRecordList,50);
//分组校验
for(List<TransactionReceiptRecord> recordList : splitNList){
//调用金融用户中心校验userId是否一致
String userIds ="";
//循环获取userid进行拼接
for(int i= 0;i < recordList.size();i++){
TransactionReceiptRecord record =recordList.get(i);
if(i != recordList.size()-1){
userIds += record.getUserId()+",";
}else{
userIds += record.getUserId()+"";
}
}
Map<String, String> header = Maps.newHashMap();
header.put("Content-type", "application/x-www-form-urlencoded");
Map param = Maps.newHashMap();
param.put("userIds",userIds);
String userUrl = userSysUrl + "/api/sync/listByUserIds";
String userResult = httpService.get(userUrl, param);
if (StringUtils.isEmpty(userResult)) {
return JsonResult.buildErrorStateResult("批量查询userId报错");
}
//对比拿到的
JSONObject userJsonObject = JSONObject.parseObject(userResult);
String dataStr = userJsonObject.getString("data");
JSONArray userArray = JSONArray.parseArray(dataStr);
for(int i=0;i<userArray.size();i++){
JSONObject object= (JSONObject) userArray.get(i);
Integer userId =object.getInteger("userId");
String userName = object.getString("name");
TransactionReceiptRecord record =recordList.get(i);
if(record.getUserId().intValue() != userId.intValue() || userName.equals(record.getUserName())){
failList.add(record);
}
}
//调用kdsp接口校验userId和交易单号是否一致
String kUrl = kdspOperationUrl + "/api/kdsp/op/fa-cui/transaction-proof/check";
//得到json字符串
String kResult = httpService.post(kUrl, header, param);
JSONObject kJson =JSONObject.parseObject(kResult);
String kJsonResult = kJson.getString("data");
String businessCode = kJson.getString("businessCode");
if(!"0000".equals(businessCode)){
return JsonResult.buildErrorStateResult("订单信息查询报错");
}
JSONObject kJsonObject = JSONObject.parseObject(kJsonResult);
failList = (List<TransactionReceiptRecord>) kJsonObject.get("verifyErrorList");
}
//校验全部通过则更新状态
List<TransactionReceiptRecord> sucessList = listrem(transactionReceiptRecordList,failList);
for(TransactionReceiptRecord record :failList){
transactionReceiptRecordRepo.updateTransactionStatusByImportStatus(2,record.getOrderNo());
}
for(TransactionReceiptRecord record :sucessList){
transactionReceiptRecordRepo.updateTransactionStatusByImportStatus(2,record.getOrderNo());
}
}
return JsonResult.buildSuccessResult("数据全部导入成功",null);
}
@Override
public JsonResult updatePDFSignStatus(List<String> sucessList,List<String>failList) {
//pdf签章成功
if(!sucessList.isEmpty()){
for(String orderNo :sucessList){
transactionReceiptRecordRepo.updatePDFStatusByOrderNo(1,orderNo);
}
}
//pdf签章失败
if(!failList.isEmpty()){
for(String orderNo :failList){
transactionReceiptRecordRepo.updatePDFStatusByOrderNo(2,orderNo);
}
}
return JsonResult.buildSuccessResult("pdf签章状态更新失败",null);
}
public List<TransactionReceiptRecord> listrem(List<TransactionReceiptRecord> listA,List<TransactionReceiptRecord> listB){
HashSet hs1 = new HashSet(listA);
HashSet hs2 = new HashSet(listB);
hs1.removeAll(hs2);
List<TransactionReceiptRecord> listC = new ArrayList<>();
listC.addAll(hs1);
return listC;
}
/**
* 切分list
* @param records
* @param groupSize
* @return
*/
private List<List<TransactionReceiptRecord>> splitList(List<TransactionReceiptRecord> records,int groupSize){
int length = records.size();
//计算可以分为多少组
int num = (length+groupSize-1)/groupSize;
List<List<TransactionReceiptRecord>> newList = new ArrayList<>();
for(int i= 0;i < num; i++){
//开始位置
int fromIndex = i * groupSize;
//结束位置
int toIndex = (i+1) * groupSize < length ? (i+1) * groupSize : length;
newList.add(records.subList(fromIndex,toIndex));
}
return newList;
}
/**
* 生成PDF
* @param transactionReceiptVO
*/
public void generatePDF(TransactionReceiptVO transactionReceiptVO,String filePath){
final String LOG_PRE = "TransactionReceiptRecordServiceImpl.generatePDF";
log.info("{} 传入参数 transactionReceiptVO={}", LOG_PRE, transactionReceiptVO);
//订单信息
OrderVO orderVO = transactionReceiptVO.getOrder();
//商品信息
List<SkuVO> skuVOList = transactionReceiptVO.getSkuList();
//收货人信息
ReceiverVO receiverVO =transactionReceiptVO.getReceiver();
//物流信息
List<LogisticsVO> logisticsVOList = transactionReceiptVO.getLogisticsList();
//物流详情
//List<logisticsDetailVO> logisticsDetails = logisticsVO.getDetailList();
Document document = new Document(PageSize.A4);
try {
PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
document.addTitle("交易凭证");//标题
PdfPTable table = new PdfPTable(6);
Font font = ITextPDFUtil.getColorFont(BaseColor.BLACK,7,"微软雅黑");
table.setWidths(ITextPDFUtil.getColumnWiths(35,35,35,35,25,35));
//订单信息
//第一行合并单元格
PdfPCell cell;
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("订单信息"), font));
cell.setColspan(6);
cell.setMinimumHeight(18);
table.addCell(cell);
//第二行标题
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("订单ID"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("供应商订单ID"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("供应链订单号"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("商品渠道"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("下单平台"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("平台账号id"), font))).setMinimumHeight(18);
//第三行数据iTextITextPDFUtil.
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getOrderNo())?"/":orderVO.getOrderNo()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getMerchantOrderId()) ?"/":orderVO.getMerchantOrderId()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getKeyStoneOrderNo())?"":orderVO.getKeyStoneOrderNo()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getSkuSourceName())?"/":orderVO.getOrderNo()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getTenantName())?"/":orderVO.getTenantName()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(orderVO.getUserId() ==null ? "/":orderVO.getUserId().toString()), font))).setMinimumHeight(18);
//第4行标题iTextITextPDFUtil.
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("平台绑定手机号"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("订单创建时间"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("支付完成时间"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("订单金额"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("实付金额"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("支付方式"), font))).setMinimumHeight(18);
//查询手机号
UserSysResult<XUser> user = userSdk.getService().findUserByUserId(orderVO.getUserId());
//第5行数据iTextITextPDFUtil.
if(user !=null && user.getData() !=null){
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(user.getData().getPhoneNo()), font));
}else{
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("/"), font));
}
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getCreatedAt())?"/":orderVO.getCreatedAt()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getPayTime())?"/":orderVO.getPayTime()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getOrderAmount())?"":orderVO.getOrderAmount()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getPayAmount())?"/":orderVO.getPayAmount()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(orderVO.getPayTypeName())?"/":orderVO.getPayTypeName()), font))).setMinimumHeight(18);
//有多个物流信息,重复展示物流信息,商品信息,收货信息,物流详情
if(logisticsVOList.size() > 1){
//展示多个
for(int j= 0;j<logisticsVOList.size();j++){
table = generateMultiParagraph(cell,font,table,logisticsVOList,skuVOList,receiverVO,j);
}
}else{
//展示一个
table=generateMultiParagraph(cell,font,table,logisticsVOList,skuVOList,receiverVO,0);
}
document.add(table);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private PdfPTable generateMultiParagraph(PdfPCell cell,Font font,
PdfPTable table,List<LogisticsVO> logisticsVOList,List<SkuVO> skuVOList,ReceiverVO receiverVO,int count){
//物流信息
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("物流信息"), font));
cell.setColspan(6);
cell.setMinimumHeight(18);
table.addCell(cell);
if(logisticsVOList.size()>0){
//第一行标题
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("发货时间"), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("确认收货时间"), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("订单状态"), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("订单类型"), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("物流公司"), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("物流单号"), font));
//第二行数据
LogisticsVO logisticsVO=logisticsVOList.get(count);
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(logisticsVO.getPostTime())?"/":logisticsVO.getPostTime()), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(logisticsVO.getCompleteTime())?"/":logisticsVO.getCompleteTime()), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(logisticsVO.getStatusName())?"/":logisticsVO.getStatusName()), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(logisticsVO.getTypeName())?"/":logisticsVO.getTypeName()), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(logisticsVO.getExpressCompany())?"/":logisticsVO.getExpressCompany()), font));
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(logisticsVO.getDeliveryNo())?"/":logisticsVO.getDeliveryNo()), font));
}
//商品信息
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("商品信息"),font));
cell.setColspan(6);
cell.setMinimumHeight(18);
table.addCell(cell);
//商品信息标题
//合并3行
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("商品名称"), font));
cell.setColspan(3);
cell.setMinimumHeight(18);
table.addCell(cell);
//合并2行
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("商品属性"), font));
cell.setColspan(2);
cell.setMinimumHeight(18);
table.addCell(cell);
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("商品件数"), font));
//商品信息数据
for(SkuVO skuVO:skuVOList){
//商品名称取值
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(skuVO.getSkuName())?"/":skuVO.getSkuName()), font));
cell.setColspan(3);
cell.setMinimumHeight(18);
table.addCell(cell);
//商品属性取值
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(skuVO.getSkuAttr())?"/":skuVO.getSkuAttr()), font));
cell.setColspan(2);
cell.setMinimumHeight(18);
table.addCell(cell);
//商品件数取值
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(skuVO.getCount())?"/":skuVO.getCount()), font));
}
//收货人信息
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("收货人信息"), font));
cell.setMinimumHeight(18);
cell.setColspan(6);
table.addCell(cell);
//收货人信息标题
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("收货人手机"), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("收货人姓名"), font))).setMinimumHeight(18);
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("收货地址"), font));
cell.setMinimumHeight(18);
cell.setColspan(4);
table.addCell(cell);
//收货人信息数据
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(receiverVO.getReceiverMobile())?"/":receiverVO.getReceiverMobile()), font))).setMinimumHeight(18);
table.addCell(new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(receiverVO.getReceiverName())?"/":receiverVO.getReceiverName()), font))).setMinimumHeight(18);
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(receiverVO.getFullAddress())?"/":receiverVO.getFullAddress()), font));
cell.setMinimumHeight(18);
cell.setColspan(4);
table.addCell(cell);
//物流详情
if(logisticsVOList.size()>0){
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("物流详情"), font));
cell.setColspan(6);
cell.setMinimumHeight(18);
table.addCell(cell);
//物流详情标题
table.addCell(new Phrase(ITextPDFUtil.getUTF8String("时间"), font));
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String("状态"), font));
cell.setColspan(5);
cell.setMinimumHeight(18);
table.addCell(cell);
List<logisticsDetailVO> logisticsDetails =logisticsVOList.get(count).getDetailList();
//物流详情数据
for(logisticsDetailVO vo : logisticsDetails){
table.addCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(vo.getTime())?"/":vo.getTime()), font));
cell = new PdfPCell(new Phrase(ITextPDFUtil.getUTF8String(StringUtils.isEmpty(vo.getDesc())?"/":vo.getDesc()), font));
cell.setColspan(5);
cell.setMinimumHeight(18);
table.addCell(cell);
}
}
return table;
}
}
package cn.quantgroup.customer.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* @author :dongjianhua
* @date :Created in 2019/10/28 10:20
* @description:excel处理工具类
* @modified By:
* @version: 1.0
*/
@Component
public class ExcelUtil {
/**
* 总行数
*/
private int totalRows = 0;
/**
* 总列数
*/
private int totalCells = 0;
/**
* 错误信息
*/
private String errorInfo;
public boolean validateExcel(String filePath) {
/** 检查文件名是否为空或者是否是Excel格式的文件 */
if (filePath == null
|| !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorInfo = "文件名不是excel格式";
return false;
}
/** 检查文件是否存在 */
// File file = new File(filePath);
// if (file == null || !file.exists()) {
// errorInfo = "文件不存在";
// return false;
// }
return true;
}
public <T>List<T> read(String filename, InputStream is,Class<T> t) throws IOException {
/** 验证文件是否合法 */
if (!validateExcel(filename)) {
throw new RuntimeException("文件格式不合法 ");
}
/** 判断文件的类型,是2003还是2007 */
Workbook wb = null;
if (!isExcel2007(filename)) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
List<T> dataLst = new ArrayList<>();
/** 得到第一个shell */
Sheet sheet = wb.getSheetAt(0);
/** 得到Excel的行数 */
this.totalRows = sheet.getPhysicalNumberOfRows();
/** 得到Excel的列数 */
if (this.totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<String> fields = new ArrayList<>();
/** 循环Excel的行 */
for (int r = 0; r < this.totalRows; r++) {
if(r == 0){
continue;
}
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
T rowLst = null;
/** 循环Excel的列 */
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类型
switch (cell.getCellType()) {
case 0: // 数字
cellValue = cell.getNumericCellValue() + "";
break;
case 1: // 字符串
cellValue = cell.getStringCellValue();
break;
case 4: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case 2: // 公式
cellValue = cell.getCellFormula() + "";
break;
case 3: // 空值
cellValue = "";
break;
case 5: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
if(r == 1){
fields.add(cellValue);
continue;
}
if (StringUtils.isEmpty(cellValue)) {
continue;
}
if(rowLst == null){
try {
rowLst = t.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (c == 2||c == 5||c == 4) {
BigDecimal bd = new BigDecimal(cellValue);//要修改的值,需要string类型
cellValue = bd.setScale(0, BigDecimal.ROUND_HALF_UP).toPlainString();
}
setValue(fields.get(c),cellValue,rowLst);
}
/** 保存第r行的第c列 */
if(null != rowLst){
dataLst.add(rowLst);
}
}
return dataLst;
}
private void setValue(String field,String val, Object obj){
for (Method method : obj.getClass().getMethods()) {
if(method.getName().equalsIgnoreCase("set"+field.replace("_",""))){
try {
method.invoke(obj,val);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
}
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
package cn.quantgroup.customer.util;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 将文件夹下面的文件
* 打包成zip压缩文件
*
*
*/
public final class FileToZip {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 压缩成ZIP 单文件压缩
*
* @param srcDir
* 压缩文件夹路径
* @param out
* 压缩文件输出流
* @param KeepDirStructure
* 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException
* 压缩失败会抛出运行时异常 存在问题当源文件找不到的时候仍然压缩,
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 压缩成ZIP 多文件压缩
*
* @param srcFiles
* 需要压缩的文件列表
* @param out
* 压缩文件输出流
* @throws RuntimeException
* 压缩失败会抛出运行时异常 提前判断文件是否存在
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
*
* @param sourceFile
* 源文件
* @param zos
* zip输出流
* @param name
* 压缩后的名称
* @param KeepDirStructure
* 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();// listFiles是获取该目录下所有文件和目录的绝对路径
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (KeepDirStructure) {
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();//关闭当前zip条目读取下一条
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
/**
*
* @param src 被压缩的文件源路径
* @param newSrc 压缩后的新路径+名称
* @param zipName 压缩后内层文件的名称
* @param KeepDirStructure
* 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
public static void batchCompress(String src,String newSrc,String zipName,boolean KeepDirStructure) throws Exception{
FileOutputStream fos3 = new FileOutputStream(new File(newSrc));
File file = new File(src);
ZipOutputStream zos = new ZipOutputStream(fos3);
FileToZip.compress(file, zos, zipName, KeepDirStructure);
zos.close();//切记关闭资源否则zip包出错
}
public static void main(String[] args) throws Exception {
/** 测试压缩方法1 */
/* FileOutputStream fos1 = new FileOutputStream(new File("D:/交易凭证11.zip"));
FileToZip.toZip(
"D:/交易凭证",
fos1,true);*/
/** 测试压缩方法2 */
/* List<File> fileList = new ArrayList<File>();
fileList.add(new File("F:/笔记/截图/Html/合并单元格.png"));
fileList.add(new File("F:/photo/鸡哈线/质量管理/过程质量控制/钢筋工程/fds/3D120-2018-11-14-001X号塔+桩号(承台)+钢筋工程.jpeg"));
FileOutputStream fos2 = new FileOutputStream(new File("F:/mytest02.zip"));
FileToZip.toZip(fileList, fos2);*/
/** 测试递归压缩 必须关闭zip流 */
/*FileOutputStream fos3 = new FileOutputStream(new File("F:/mytest03.zip"));
File file = new File("F:/photo/鸡哈线");
ZipOutputStream zos = new ZipOutputStream(fos3);
ZipUtils.compress(file, zos, "鸡哈线", true);
zos.close();//这里必须切记关闭
*/
List<String>list =new ArrayList();
list.add("/1王五");
list.add("/1王二");
list.add("/2王三");
list.add("/2王四");
for(String str : list){
mkdir("D:/交易凭证00"+str);
System.out.println(str);
};
}
// 创建文件上传路径
public static void mkdir(String path) {
File fd = null;
try {
fd = new File(path);
if (!fd.exists()) {
fd.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fd = null;
}
}
}
package cn.quantgroup.customer.util;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.transaction.*;
import cn.quantgroup.customer.service.http.IHttpService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @Description iTextPDFUtil
* @className iTextPDFUtil
**/
@Slf4j
public class ITextPDFUtil {
public static final String FONT_FAMILY = "STSongStd-Light";
private static IHttpService httpService;
/**
* @param table 表格
* @param cell 列
* @param text 文本
* @return void
* @Description 蓝色背景色标题内容行添加
**/
public static void addTableGroupTitle(PdfPTable table, PdfPCell cell, String text) {
cell = new PdfPCell(new Phrase(getUTF8String(text), getColorFont(BaseColor.WHITE)));
table.addCell(addTitleCell(cell, 25, new BaseColor(69, 153, 241), 2, false));
}
/**
* @param table 表格
* @param cell 列
* @param text 文本
* @param colspan 需要合并的列
* @return void
* @Description 蓝色背景色标题内容行添加
**/
public static void addTableGroupTitle(PdfPTable table, PdfPCell cell, String text, int colspan) {
cell = new PdfPCell(new Phrase(getUTF8String(text), getColorFont(BaseColor.WHITE)));
table.addCell(addTitleCell(cell, 25, new BaseColor(69, 153, 241), colspan, false));
}
/**
* @param table 表格
* @param cell 列
* @param suggestText 核查建议内容
* @param fontColor 核查建议内容文字颜色
* @return com.itextpdf.text.Element
* @Description 核查建议
**/
public static void addSuggestLine(PdfPTable table, PdfPCell cell, String suggestText, BaseColor fontColor) throws Exception {
addSuggestLine(table, cell, suggestText, fontColor, 0, 10f, 30f);
}
/**
* @param table 表格
* @param cell 列
* @param suggestText 核查建议内容
* @param fontColor 核查建议内容文字颜色
* @param colspan 合并的列
* @param widths 列所占宽
* @return com.itextpdf.text.Element
* @Description 核查建议
**/
public static void addSuggestLine(PdfPTable table, PdfPCell cell, String suggestText, BaseColor fontColor, int colspan, float... widths) throws Exception {
cell = new PdfPCell(new Phrase(getUTF8String("核查建议:"), getColorFont()));
cell.setColspan(1);
table.addCell(addBaseCell(cell, 23, new BaseColor(238, 238, 238), false));
cell = new PdfPCell(new Phrase(getUTF8String(suggestText), getColorFont(fontColor)));
if (colspan > 0) {
cell.setColspan(colspan);
}
table.addCell(addBaseCell(cell, 23, new BaseColor(238, 238, 238), false));
table.setWidths(getColumnWiths(widths));
}
/**
* @param groupText 文本内容
* @return com.itextpdf.text.Element
* @Description 信息分组table
**/
public static Element addTableGroupLine(String groupText) {
PdfPTable tableBaseInfoIndex = new PdfPTable(1);
tableBaseInfoIndex.setWidthPercentage(20);
PdfPCell cellBaseInfo = new PdfPCell(new Phrase(getUTF8String(groupText), getColorFont(new BaseColor(0, 0, 0), 30, Font.BOLD)));
cellBaseInfo.setHorizontalAlignment(Element.ALIGN_CENTER);
tableBaseInfoIndex.addCell(addTitleCell(cellBaseInfo, 28, new BaseColor(255, 255, 255), 2, false));
tableBaseInfoIndex.addCell(addBlankLine(10, 1));
return tableBaseInfoIndex;
}
/**
* @param color 字体颜色
* @param fontSize 字体大小
* @param fontFamily 字体
* @return com.itextpdf.text.Font
* @Description 指定颜色字体 默认处理中文显示
**/
public static Font getColorFont(BaseColor color, int fontSize, String fontFamily) {
Font font = new Font(getFont());
font.setColor(color);
if (fontSize > 0 && (null != fontFamily || !"".equals(fontFamily))) {
font.setSize(fontSize);
font.setFamily(fontFamily);
}
return font;
}
/**
* @param color 字体颜色
* @param fontSize 字体大小
* @param fontBold 字体加粗
* @return com.itextpdf.text.Font
* @Description 指定颜色字体 默认处理中文显示
**/
public static Font getColorFont(BaseColor color, int fontSize, int fontBold) {
Font font = new Font(getFont());
font.setSize(fontSize);
font.setStyle(fontBold);
font.setColor(color);
return font;
}
/**
* @param color 字体颜色
* @return com.itextpdf.text.Font
* @Description 指定颜色字体 默认处理中文显示
**/
public static Font getColorFont(BaseColor color) {
return getColorFont(color, 0, null);
}
/**
* @return com.itextpdf.text.Font
* @Description 默认处理中文显示
**/
public static Font getColorFont() {
Font font = new Font(getFont());
return font;
}
/**
* @param widths 一个或多个
* @return float[]
* @Description 指定列宽度
**/
public static float[] getColumnWiths(float... widths) {
float[] columnWidths = new float[widths.length];
for (int i = 0; i < widths.length; i++) {
columnWidths[i] = widths[i];
}
return columnWidths;
}
/**
* @param titleCell 要操作的cell
* @param fixedHeight 行高度
* @param baseColor 背景色
* @param colspan 合并的列数
* @param isBottomBorder 是否有下边框 true 有 fasle 没有
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加表头cell
**/
public static PdfPCell addTitleCell(PdfPCell titleCell, int fixedHeight, BaseColor baseColor, int colspan, boolean isBottomBorder) {
titleCell.setColspan(colspan);
titleCell.setMinimumHeight(fixedHeight);
titleCell.setUseVariableBorders(true);
titleCell.setUseAscender(true);
titleCell.setUseDescender(true);
titleCell.setBackgroundColor(baseColor);
if (isBottomBorder) {
titleCell.setBorderColor(BaseColor.LIGHT_GRAY);
} else {
titleCell.setBorder(Rectangle.NO_BORDER);
}
titleCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
return titleCell;
}
/**
* @param fixedHeight 空行高度
* @param colspan 合并的列数
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加空行
**/
public static PdfPCell addBlankLine(int fixedHeight, int colspan) {
PdfPCell blankLine = new PdfPCell();
blankLine.setMinimumHeight(fixedHeight);
blankLine.setBorder(Rectangle.NO_BORDER);
blankLine.setColspan(colspan);
return blankLine;
}
/**
* @param baseCell 要操作的cell
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加默认cell
**/
public static PdfPCell addBaseCell(PdfPCell baseCell, BaseColor backGroundColor) {
baseCell.setMinimumHeight(23);
baseCell.setUseVariableBorders(true);
baseCell.setUseAscender(true);
baseCell.setUseDescender(true);
// baseCell.setBorder(Rectangle.);
baseCell.setBackgroundColor(backGroundColor);
baseCell.setBorderColor(BaseColor.LIGHT_GRAY);
baseCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
return baseCell;
}
/**
* @param baseCell 要操作的cell
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加默认cell
**/
public static PdfPCell addBaseCell(PdfPCell baseCell) {
baseCell.setMinimumHeight(23);
baseCell.setUseVariableBorders(true);
baseCell.setUseAscender(true);
baseCell.setUseDescender(true);
// baseCell.setBorder(Rectangle.);
baseCell.setBorderColor(BaseColor.LIGHT_GRAY);
baseCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
return baseCell;
}
/**
* @param baseCell 要操作的cell
* @param isBottomBorder 是否有下边框 true 有 fasle 没有
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加cell
**/
public static PdfPCell addBaseCell(PdfPCell baseCell, boolean isBottomBorder) {
baseCell.setMinimumHeight(23);
baseCell.setUseVariableBorders(true);
baseCell.setUseAscender(true);
baseCell.setUseDescender(true);
if (isBottomBorder) {
baseCell.setBorderColor(BaseColor.LIGHT_GRAY);
} else {
baseCell.setBorder(Rectangle.NO_BORDER);
}
baseCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
return baseCell;
}
/**
* @param baseCell 要操作的cell
* @param fixedHeight 行高
* @param color 背景色
* @param isBottomBorder 是否有下边框 true 有 fasle 没有
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加cell
**/
public static PdfPCell addBaseCell(PdfPCell baseCell, int fixedHeight, BaseColor color, boolean isBottomBorder) {
baseCell.setMinimumHeight(fixedHeight);
baseCell.setUseVariableBorders(true);
baseCell.setUseAscender(true);
baseCell.setUseDescender(true);
if (null != color) {
baseCell.setBackgroundColor(color);
}
if (isBottomBorder) {
baseCell.setBorderColor(BaseColor.LIGHT_GRAY);
} else {
baseCell.setBorder(Rectangle.NO_BORDER);
}
baseCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
return baseCell;
}
/**
* @param value 填充的值
* @param color 字体颜色
* @param color 背景颜色
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加数据、颜色
**/
public static PdfPCell initTitlePdfCell(String value, BaseColor color, BaseColor backGroundColor) {
Font font = getColorFont(color);
font.setStyle(Font.BOLD);
PdfPCell breakFithCell = new PdfPCell(new Phrase(getUTF8String(value), font));
breakFithCell.setBackgroundColor(backGroundColor);
return breakFithCell;
}
/**
* @param value 填充的值
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加数据、颜色
**/
public static PdfPCell initTitlePdfCell(String value) {
Font font = getColorFont(new BaseColor(0, 0, 0));
font.setStyle(Font.BOLD);
PdfPCell breakFithCell = new PdfPCell(new Phrase(getUTF8String(value), font));
breakFithCell.setBackgroundColor(new BaseColor(195, 195, 195));
return breakFithCell;
}
/**
* @param value 填充的值
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加数据、颜色
**/
public static PdfPCell initTitlePdfCell(String value, int fontSize) {
Font font = getColorFont(new BaseColor(0, 0, 0));
font.setSize(fontSize);
font.setStyle(Font.BOLD);
PdfPCell breakFithCell = new PdfPCell(new Phrase(getUTF8String(value), font));
breakFithCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
breakFithCell.setBackgroundColor(new BaseColor(195, 195, 195));
return breakFithCell;
}
/**
* @param value 填充的值
* @param color 填充颜色
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加数据、颜色
**/
public static PdfPCell initPhrasePdfCell(String value, BaseColor color) {
PdfPCell breakFithCell = new PdfPCell(new Phrase(getUTF8String(value), getColorFont(color)));
return breakFithCell;
}
/**
* @param value 填充的值
* @param color 填充颜色
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加数据、颜色
**/
public static PdfPCell initParagraphPdfCell(String value, BaseColor color) {
PdfPCell breakFithCell = new PdfPCell(new Paragraph(getUTF8String(value), getColorFont(color)));
return breakFithCell;
}
/**
* @param value 填充的值
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加数据、颜色
**/
public static PdfPCell initPhrasePdfCell(String value) {
PdfPCell breakFithCell = new PdfPCell(new Phrase(getUTF8String(value), getColorFont()));
return breakFithCell;
}
/**
* @param value 填充的值
* @param fontSize 字体大小
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加数据、颜色
**/
public static PdfPCell initPhrasePdfCell(String value, int fontSize) {
Font font = getColorFont();
font.setSize(fontSize);
PdfPCell breakFithCell = new PdfPCell(new Phrase(getUTF8String(value), font));
return breakFithCell;
}
/**
* @param value 填充的值
* @param fontSize 字体大小
* @return com.itextpdf.text.pdf.PdfPCell
* @Description 添加数据、颜色
**/
public static PdfPCell initPhrasePdfCell(String value, int fontSize, int align) {
Font font = getColorFont();
font.setSize(fontSize);
PdfPCell breakFithCell = new PdfPCell(new Phrase(getUTF8String(value), font));
breakFithCell.setHorizontalAlignment(align);
return breakFithCell;
}
/**
* @return com.itextpdf.text.pdf.BaseFont
* @Description 设置中文支持
* @Author 小帅丶
* @Date 2019/7/11 10:33
* @Param []
**/
static BaseFont bf = null;
public static BaseFont getFont() {
try {
if (bf == null) {
// 这个是xmlworker提供的获取字体方法,很方便,对中文支持很好
FontFactoryImp fp = new XMLWorkerFontProvider();
// 注册指定的字体目录,默认构造方法中会注册全部目录,我这里注册了src/font目录
fp.registerDirectory(ClassUtils.getDefaultClassLoader().getResource("").getPath().concat("fonts"), true);
// log.info("预加载路径:{}看一下字体列表:{}", ClassUtils.getDefaultClassLoader().getResource("").getPath().concat("fonts"), JSON.toJSONString(fp));
Font a = fp.getFont("宋体");
bf = a.getBaseFont();
}
} catch (Exception e) {
System.out.println("Exception = " + e.getMessage());
}
return bf;
}
/**
* 斜角排列、全屏多个重复的花式文字水印
*
* @param input 需要加水印的PDF读取输入流
* @param output 输出生成PDF的输出流
* @param waterMarkString 水印字符
* @param xAmout x轴重复数量
* @param yAmout y轴重复数量
* @param opacity 水印透明度
* @param rotation 水印文字旋转角度,一般为45度角
* @param waterMarkFontSize 水印字体大小
* @param color 水印字体颜色
*/
public static void stringWaterMark(InputStream input, OutputStream output, String waterMarkString, int xAmout, int yAmout, float opacity, float rotation, int waterMarkFontSize, BaseColor color) {
try {
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, output);
BaseFont baseFont = getFont();
int total = reader.getNumberOfPages() + 1;
PdfContentByte over;
// 给每一页加水印
for (int i = 1; i < total; i++) {
Rectangle pageRect = stamper.getReader().getPageSizeWithRotation(i);
// 计算水印每个单位步长X,Y
float x = pageRect.getWidth() / xAmout;
float y = pageRect.getHeight() / yAmout;
over = stamper.getOverContent(i);
PdfGState gs = new PdfGState();
// 设置透明度为
gs.setFillOpacity(opacity);
over.setGState(gs);
over.saveState();
over.beginText();
over.setColorFill(color);
over.setFontAndSize(baseFont, waterMarkFontSize);
for (int n = 0; n < xAmout + 1; n++) {
for (int m = 0; m < yAmout + 1; m++) {
over.showTextAligned(Element.ALIGN_CENTER, waterMarkString, x * n, y * m, rotation);
}
}
over.endText();
}
stamper.close();
} catch (Exception e) {
new Exception("NetAnd PDF add Text Watermark error" + e.getMessage());
}
}
/**
* 图片水印,整张页面平铺
*
* @param input 需要加水印的PDF读取输入流
* @param output 输出生成PDF的输出流
* @param imageFile 水印图片路径
*/
public static void imageWaterMark(InputStream input, OutputStream output, String imageFile, float opacity) {
try {
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, output);
Rectangle pageRect = stamper.getReader().getPageSize(1);
float w = pageRect.getWidth();
float h = pageRect.getHeight();
int total = reader.getNumberOfPages() + 1;
Image image = Image.getInstance(imageFile);
image.setAbsolutePosition(0, 0);// 坐标
image.scaleAbsolute(w, h);
PdfGState gs = new PdfGState();
gs.setFillOpacity(opacity);// 设置透明度
PdfContentByte over;
// 给每一页加水印
float x, y;
Rectangle pagesize;
for (int i = 1; i < total; i++) {
pagesize = reader.getPageSizeWithRotation(i);
x = (pagesize.getLeft() + pagesize.getRight()) / 2;
y = (pagesize.getTop() + pagesize.getBottom()) / 2;
over = stamper.getOverContent(i);
over.setGState(gs);
over.saveState();//没这个的话,图片透明度不起作用,必须在beginText之前,否则透明度不起作用,会被图片覆盖了内容而看不到文字了。
over.beginText();
// 添加水印图片
over.addImage(image);
}
stamper.close();
} catch (Exception e) {
new Exception("NetAnd PDF add image Watermark error" + e.getMessage());
}
}
/**
* @param tableMobileHeader 要操作的表格
* @param cellMobileHeader 要操作的单元格
* @param clospan 合并列 不需要合并填写0
* @param fixedHeight 行高
* @param padding 间距
* @param border 边框
* @param borderColor 边框颜色
* @param backgroundColor 背景色
* @param vertical 垂直对齐方式
* @param horizontal 水平对齐方式
* @return void
* @description 顶部表格卡片形式显示格式数据组装
**/
public static void addTableHeaderData(PdfPTable tableMobileHeader, PdfPCell cellMobileHeader, int clospan, float fixedHeight, int padding, int border, BaseColor borderColor, BaseColor backgroundColor, int vertical, int horizontal) {
cellMobileHeader.setUseBorderPadding(true);
cellMobileHeader.setUseAscender(true);
if (clospan > 0) {
cellMobileHeader.setColspan(clospan);
}
cellMobileHeader.setUseDescender(true);
cellMobileHeader.setMinimumHeight(fixedHeight);
cellMobileHeader.setPadding(padding);
cellMobileHeader.setVerticalAlignment(vertical);
cellMobileHeader.setHorizontalAlignment(horizontal);
if (null != backgroundColor) {
cellMobileHeader.setBackgroundColor(backgroundColor);
}
cellMobileHeader.setBorder(border);
cellMobileHeader.setBorderColor(borderColor);
tableMobileHeader.addCell(cellMobileHeader);
}
/**
* @param tableMobileHeader 要操作的表格
* @param cellMobileHeader 要操作的单元格
* @param clospan 合并列 不需要合并填写0
* @param backgroundColor 背景色
* @return void
* @description 顶部表格卡片形式显示格式数据组装
**/
public static void addTableHeaderData(PdfPTable tableMobileHeader, PdfPCell cellMobileHeader, int clospan, BaseColor backgroundColor) {
addTableHeaderData(tableMobileHeader, cellMobileHeader, clospan, 100, 10, 30, BaseColor.WHITE, backgroundColor, 0, 0);
}
public static String getUTF8String(String string) {
if (string != null) {
try {
return new String(string.getBytes(), "utf8");
} catch (Exception e) {
log.error("[getUTF8String]转换字符编码失败", e);
}
}
return string;
}
public static void main(String[] args) {
List<String>list =new ArrayList();
list.add("D:\\交易凭证0222\\1王五");
list.add("D:\\交易凭证0222\\1王二");
list.add("D:\\交易凭证0222\\2里三");
list.add("D:\\交易凭证0222\\2里斯");
list.add("D:\\交易凭证0222\\3吴就");
list.add("D:\\交易凭证0222\\3吴还");
for(String str : list){
FileToZip.mkdir(str);
generatePDF(str+"\\"+20220222+".pdf");
};
//String str = "D:\\交易凭证0219\\1王五\\11.pdf";
//generatePDF(str);
}
private static void generatePDF(String filePath){
Document document = new Document(PageSize.A4);
try {
//PdfWriter.getInstance(document, new FileOutputStream("D:\\createSamplePDF.pdf"));
PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
document.addTitle("交易凭证");//标题
PdfPTable table = new PdfPTable(6);
Font font = getColorFont(BaseColor.BLACK,7,"微软雅黑");
//订单信息
//第一行合并单元格
PdfPCell cell;
cell = new PdfPCell(new Phrase(getUTF8String("订单信息"), font));
cell.setColspan(6);
table.addCell(cell);
//第二行标题
table.addCell(new Phrase(getUTF8String("订单ID"), font));
table.addCell(new Phrase(getUTF8String("供应商订单ID"), font));
table.addCell(new Phrase(getUTF8String("供应链订单号"), font));
table.addCell(new Phrase(getUTF8String("商品渠道"), font));
table.addCell(new Phrase(getUTF8String("下单平台"), font));
table.addCell(new Phrase(getUTF8String("平台账号id"), font));
//第三行数据
table.addCell(new Phrase(getUTF8String("123"), font));
table.addCell(new Phrase(getUTF8String("456"), font));
table.addCell(new Phrase(getUTF8String("789"), font));
table.addCell(new Phrase(getUTF8String("000"), font));
table.addCell(new Phrase(getUTF8String("111"), font));
table.addCell(new Phrase(getUTF8String("222"), font));
//第4行标题
table.addCell(new Phrase(getUTF8String("平台绑定手机号"), font));
table.addCell(new Phrase(getUTF8String("订单创建时间"), font));
table.addCell(new Phrase(getUTF8String("支付完成时间"), font));
table.addCell(new Phrase(getUTF8String("订单金额"), font));
table.addCell(new Phrase(getUTF8String("实付金额"), font));
table.addCell(new Phrase(getUTF8String("支付方式"), font));
//第5行数据
table.addCell(new Phrase(getUTF8String("123"), font));
table.addCell(new Phrase(getUTF8String("456"), font));
table.addCell(new Phrase(getUTF8String("789"), font));
table.addCell(new Phrase(getUTF8String("000"), font));
table.addCell(new Phrase(getUTF8String("111"), font));
table.addCell(new Phrase(getUTF8String("222"), font));
//物流信息
cell = new PdfPCell(new Phrase(getUTF8String("物流信息"), font));
cell.setColspan(6);
table.addCell(cell);
//第一行标题
table.addCell(new Phrase(getUTF8String("发货时间"), font));
table.addCell(new Phrase(getUTF8String("确认收货时间"), font));
table.addCell(new Phrase(getUTF8String("订单状态"), font));
table.addCell(new Phrase(getUTF8String("订单类型"), font));
table.addCell(new Phrase(getUTF8String("物流公司"), font));
table.addCell(new Phrase(getUTF8String("物流单号"), font));
//第二行数据
table.addCell(new Phrase(getUTF8String("123"), font));
table.addCell(new Phrase(getUTF8String("456"), font));
table.addCell(new Phrase(getUTF8String("789"), font));
table.addCell(new Phrase(getUTF8String("000"), font));
table.addCell(new Phrase(getUTF8String("111"), font));
table.addCell(new Phrase(getUTF8String("222"), font));
//商品信息
cell = new PdfPCell(new Phrase(getUTF8String("商品信息"),font));
cell.setColspan(6);
table.addCell(cell);
//商品信息标题
//合并3行
cell = new PdfPCell(new Phrase(getUTF8String("商品名称"), font));
cell.setColspan(3);
table.addCell(cell);
//合并2行
cell = new PdfPCell(new Phrase(getUTF8String("商品属性"), font));
cell.setColspan(2);
table.addCell(cell);
table.addCell(new Phrase(getUTF8String("商品件数"), font));
//商品信息数据
cell = new PdfPCell(new Phrase(getUTF8String("元宵汤圆"), font));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(getUTF8String("黑芝麻"), font));
cell.setColspan(2);
table.addCell(cell);
table.addCell(new Phrase(getUTF8String("3"), font));
//收货人信息
cell = new PdfPCell(new Phrase(getUTF8String("收货人信息"), font));
cell.setColspan(6);
table.addCell(cell);
//收货人信息标题
table.addCell(new Phrase(getUTF8String("收货人手机"), font));
table.addCell(new Phrase(getUTF8String("收货人姓名"), font));
cell = new PdfPCell(new Phrase(getUTF8String("收货地址"), font));
cell.setColspan(4);
table.addCell(cell);
//收货人信息数据
table.addCell(new Phrase(getUTF8String("18732195428"), font));
table.addCell(new Phrase(getUTF8String("吴琼"), font));
cell = new PdfPCell(new Phrase(getUTF8String("河北省石家庄市元氏县南佐镇"), font));
cell.setColspan(4);
table.addCell(cell);
//物流详情
cell = new PdfPCell(new Phrase(getUTF8String("物流详情"), font));
cell.setColspan(6);
table.addCell(cell);
//物流详情标题
table.addCell(new Phrase(getUTF8String("时间"), font));
cell = new PdfPCell(new Phrase(getUTF8String("状态"), font));
cell.setColspan(5);
table.addCell(cell);
//物流详情数据
for(int i= 0;i <50;i++){
table.addCell(new Phrase(getUTF8String("2022/01/10 10:50"), font));
cell = new PdfPCell(new Phrase(getUTF8String("您的订单已由本人签收。如有疑问您可以联系配送员【陶威威,13157333133】确认。感谢您在京东购物,欢迎再次光临。"), font));
cell.setColspan(5);
table.addCell(cell);
}
document.add(table);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
package cn.quantgroup.customer.util;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.IOUtils;
public class SFTPUtil {
private final Logger logger = LoggerFactory.getLogger(SFTPUtil.class);
private ChannelSftp sftp;
private Session session;
private String username;
private String password;
private String privateKey;
private String host;
private int port;
public SFTPUtil(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
public SFTPUtil(String username, String host, int port, String privateKey) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}
public SFTPUtil() {
}
public void login() {
try {
JSch jsch = new JSch();
if (this.privateKey != null) {
jsch.addIdentity(this.privateKey);
}
this.session = jsch.getSession(this.username, this.host, this.port);
if (this.password != null) {
this.session.setPassword(this.password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
this.session.setConfig(config);
this.session.connect();
Channel channel = this.session.openChannel("sftp");
channel.connect();
this.sftp = (ChannelSftp)channel;
this.logger.info("pwd = [{}]", this.sftp.pwd());
} catch (JSchException var4) {
var4.printStackTrace();
} catch (SftpException var5) {
var5.printStackTrace();
}
}
public void logout() {
if (this.sftp != null && this.sftp.isConnected()) {
this.sftp.disconnect();
}
if (this.session != null && this.session.isConnected()) {
this.session.disconnect();
}
}
public void upload(String basePath, String directory, String sftpFileName, InputStream input) throws SftpException {
try {
this.sftp.cd(basePath);
this.sftp.cd(directory);
} catch (SftpException var14) {
String[] dirs = directory.split("/");
String tempPath = basePath;
String[] var8 = dirs;
int var9 = dirs.length;
for(int var10 = 0; var10 < var9; ++var10) {
String dir = var8[var10];
if (null != dir && !"".equals(dir)) {
tempPath = tempPath + "/" + dir;
try {
this.sftp.cd(tempPath);
} catch (SftpException var13) {
this.sftp.mkdir(tempPath);
this.sftp.cd(tempPath);
}
}
}
}
this.sftp.put(input, sftpFileName + ".tmp");
this.sftp.rename(sftpFileName + ".tmp", sftpFileName);
}
public void download(String directory, String downloadFile, String saveDirectory, String saveFile) throws SftpException, FileNotFoundException {
if (directory != null && !"".equals(directory)) {
this.sftp.cd(directory);
}
File file = new File(saveDirectory, saveFile);
this.sftp.get(downloadFile, new FileOutputStream(file));
}
public void download(String directory, String downloadFile, File file) throws SftpException, FileNotFoundException {
if (directory != null && !"".equals(directory)) {
this.sftp.cd(directory);
}
this.sftp.get(downloadFile, new FileOutputStream(file));
}
public byte[] download(String directory, String downloadFile) throws SftpException, IOException {
if (directory != null && !"".equals(directory)) {
this.sftp.cd(directory);
}
InputStream is = this.sftp.get(downloadFile);
byte[] fileData = IOUtils.readNBytes(is, is.available());
return fileData;
}
public void delete(String directory, String deleteFile) throws SftpException {
this.sftp.cd(directory);
this.sftp.rm(deleteFile);
}
public void createDir(String createPath) {
try {
if (this.isDirExist(createPath)) {
this.sftp.cd(createPath);
return;
}
String[] pathArry = createPath.split("/");
StringBuffer filePath = new StringBuffer("/");
String[] var4 = pathArry;
int var5 = pathArry.length;
for(int var6 = 0; var6 < var5; ++var6) {
String path = var4[var6];
if (!path.equals("")) {
filePath.append(path + "/");
if (this.isDirExist(filePath.toString())) {
this.sftp.cd(filePath.toString());
} else {
this.sftp.mkdir(filePath.toString());
this.sftp.cd(filePath.toString());
}
}
}
} catch (SftpException var8) {
var8.printStackTrace();
}
}
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = this.sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception var4) {
if (var4.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
return isDirExistFlag;
}
}
public Vector<?> listFiles(String directory) throws SftpException {
return this.sftp.ls(directory);
}
public static void main(String[] args) {
SFTPUtil sftp = new SFTPUtil("lhphy", "47.105.211.91", 22223, "MIIEpQIBAAKCAQEAzCJdHIHjBobXq8S+Vq6IoAY7y3u98KQ1dyA6Ixpa83bw0xZJ0yA/vrcNxueyUesdL7DaG/4kruAdiCeLukYqlmJR+SsFcBUxnB4zYSrWx106CoLjPujvv1DvFgPacDGyp4+e7ifGt/RQlAPONQ+XbaHDHjr6R/0i/93Gm+/yn+/wQvsGUVOqE4kSvpY+36mcVyAgXf2f7Q5YvGsuA7Y7wx0tqU/M/7RI2cRYa3/PumMtBAvx/3Ny17is4I+8RRCq5B/UjOiwsSd391QWMpT0B3T5tO9stpMXLL1Vfm/O4lBUIWkEJsGBqjtgLp7LUpCzDyOGW7+Bi+kDTo5Z1huvfwIDAQABAoIBAQDHcX+lnaXRN6e6NDR/fnEQYGbFjbXrSpTOOhdzOonIO9pZcvpYI7cEP9dfEfsgnGVcth6zoN/4WBGieHjFW066tX8/we/DLYHV9Y/fjLph+Mz/fhhG29F6C7o8uTEP0w6pNeJi70vxaOvdYcZ0AzLBM33uqFLmSQWMFgO5UXutFEDtgi6y6w067CFHq0LEn6PrHZqnevKsPCBMdEXQcTfDaL3JHQGGrIw7WGsi6c6uVk6EVSoSeag0mV6gLfQZzP7zf4oSTZb1Oxt10mk3hVrQV1FiNtHFQpfR9TBCrJBiRER0QQOh/PHet6lXzQ9SQbswLVsbL9asuAS7zOoFwWRBAoGBAPsjwf6waEB8YwPgL8MpD9cRd+VlwjJD9HQGSAr8IHgMNgrwhB2EZx+GOqSqI4FaXhQjb2Safs2POLZOArDmSDSajT7E6etue3c+P5MP/hprjNaSidaEcXsF/eCMjzntZT5HbHNCTHD0DoT5GkVj50UCfz3PHzQxTHV0pk4B2SufAoGBANAVuRIpwBOtF7RIDAeBi3OMdO6fTw3i3rZBco6qqGwyxt/d6BCvEGUuh3s3pcKcNfdRr6AeZRiwtgk8uu7dcwZBdF6TnCQqzJefReyVlVFDpyt44dKVDtOlckwc+BcaM56NHCWrGEJAwxAzl84rAywxktvT63x+LfY8w5KUyPAhAoGBAPM0G6fzWeIpExIrxtUuLKLPzdYfB0L6P/8kHhxVMXRQDv3lEWwsTlle+eeAxEV+J+FEt5krbGTQr9EMFtsNBxu6F9KTixxtr684XwSh1ifrw0YAPu+47tR+Zu9P71vfo83+CO5NZA12q6DmQySzrMFNu781lzhKDYspXevpKlBtAoGBALPZUrCELWPUQ5yqeNsz+JfSWm60etuBrwTP5HeywQdji8iKP73L0dviL28sVbSy12H/1FAMdUy1z2CEgP1bocNSZ4YnBtmrtFGIdCNb1kb6tk44mNYtxzbe1L88eqFdICh1xlI4YytAVlh2f0rOmltkLY6ax/o+BPPC6TaUKmiBAoGASC1VYOzpelcN0ne3RfOrTDzRH3lQzGTh7E+2UxsVpkdxJg0N4e47MGKpGyylxEiuqpcoc9w7ec+IqylcL5Hx2jzDLx4OJHagtZVv8Gx9tixG6+vAdjjl7E38HS5WQcFJzQRAyktCeeoiLYIA3UvSN0GOXqDPAkFzPtX853APRwQ=");
sftp.login();
try {
boolean has = sftp.isDirExist("./tst/20190819/account");
System.out.println(has);
if (!has) {
sftp.createDir("./tst/20190819/account");
}
} catch (Exception var3) {
var3.printStackTrace();
}
sftp.logout();
}
}
......@@ -31,7 +31,8 @@ public class WorkOrderTest {
@Autowired
private IWorkOrderService workOrderService;
@Autowired
private IHttpService httpService;
@Test
public void queryPage() {
......@@ -39,6 +40,14 @@ public class WorkOrderTest {
System.out.println(JSONTools.serialize(pageJsonResult));
}
@Test
public void testUser (){
String url ="https://passportapi-qa2.liangkebang.net/api/sync/listByUserIds?userIds=70356056,70356055";
String result = httpService.get(url);
JSONObject userJsonObject = JSONObject.parseObject(userResult);
JSONObject userData = userJsonObject.getJSONObject("data");
}
public static void main(String[] args) {
System.out.println(DesensitizeUtil.mobileDesensitization("13597778033"));
System.out.println(DesensitizeUtil.idcardDesensitization("422802199007261711"));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment