You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
754 lines
27 KiB
754 lines
27 KiB
package com.fr.plugin.third.party.jsdbacfj; |
|
|
|
import com.fanruan.api.log.LogKit; |
|
import com.fanruan.api.util.StringKit; |
|
import com.fr.base.Base64; |
|
import com.fr.data.NetworkHelper; |
|
import com.fr.file.CacheManager; |
|
import com.fr.general.ReportDeclareRecordType; |
|
import com.fr.io.exporter.PDFEmbExporter; |
|
import com.fr.io.exporter.PDFExporterForPrint; |
|
import com.fr.json.JSONArray; |
|
import com.fr.json.JSONObject; |
|
import com.fr.log.LogUtils; |
|
import com.fr.page.PageSetProvider; |
|
import com.fr.plugin.context.PluginContexts; |
|
import com.fr.plugin.third.party.jsdbacfj.config.CustomDataConfig; |
|
import com.fr.report.ReportContext; |
|
import com.fr.report.controller.PrintOffsetController; |
|
import com.fr.report.entity.PrintOffsetEntity; |
|
import com.fr.report.print.PrintOffsetSign; |
|
import com.fr.report.print.TypeIP; |
|
import com.fr.stable.StringUtils; |
|
import com.fr.stable.web.SessionProvider; |
|
import com.fr.third.org.apache.commons.io.FileUtils; |
|
import com.fr.third.org.apache.commons.lang3.time.DateFormatUtils; |
|
import com.fr.third.org.apache.http.impl.client.CloseableHttpClient; |
|
import com.fr.web.core.ReportRepositoryDeal; |
|
import com.fr.web.core.ReportSessionIDInfor; |
|
import com.fr.web.core.SessionPoolManager; |
|
import com.fr.web.utils.WebUtils; |
|
import org.apache.pdfbox.cos.COSName; |
|
import org.apache.pdfbox.pdmodel.PDDocument; |
|
import org.apache.pdfbox.pdmodel.PDPage; |
|
import org.apache.pdfbox.pdmodel.PDPageContentStream; |
|
import org.apache.pdfbox.pdmodel.common.PDRectangle; |
|
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; |
|
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; |
|
|
|
import javax.servlet.FilterChain; |
|
import javax.servlet.ServletOutputStream; |
|
import javax.servlet.http.HttpServletRequest; |
|
import javax.servlet.http.HttpServletResponse; |
|
import java.io.*; |
|
import java.math.BigDecimal; |
|
import java.nio.ByteBuffer; |
|
import java.nio.channels.Channels; |
|
import java.nio.channels.ReadableByteChannel; |
|
import java.nio.channels.WritableByteChannel; |
|
import java.nio.file.Files; |
|
import java.nio.file.Path; |
|
import java.nio.file.Paths; |
|
import java.util.Collection; |
|
import java.util.HashSet; |
|
import java.util.Set; |
|
import java.util.UUID; |
|
|
|
public class StampUtils { |
|
public static String getImgBase64() { |
|
String stampBase64 = getStampBase64(); |
|
if (StringKit.isEmpty(stampBase64)) { |
|
return ""; |
|
} |
|
String dataBase64 = "data:image/png;base64," + stampBase64; |
|
return dataBase64; |
|
} |
|
|
|
public static String getStampBase64() { |
|
return getStampBase64("012101"); |
|
} |
|
|
|
public static String getStampBase64(String orgId) { |
|
try { |
|
|
|
String temp = ""; |
|
if (StringKit.isNotEmpty(temp)) { |
|
return temp; |
|
} |
|
|
|
String url = CustomDataConfig.getInstance().getStampEsbUrl(); |
|
if (StringKit.isEmpty(url)) { |
|
return ""; |
|
} |
|
|
|
if (StringKit.isEmpty(orgId)) { |
|
orgId = "012101"; |
|
} |
|
|
|
String bodyContent = "{\"sysHead\":\n" + |
|
"{\"userLang\":\"CHINESE\",\n" + |
|
"\"svcCd\":\"xx\",\n" + |
|
"\"scnCd\":\"xx\",\n" + |
|
"\"cnsmSysId\":\"xx\",\n" + |
|
"\"subSeqNo\":\"" + getId() + "\",\n" + |
|
"\"seqNo\":\"" + getId() + "\",\n" + |
|
"\"tranMode\":\"xx\",\n" + |
|
"\"systemId\":\"xx\",\n" + |
|
"\"tranDate\":\"" + getcurrentDate() + "\",\n" + |
|
"\"tranTimestamp\":\"" + getcurrentTimeStamp() + "\",\n" + |
|
"\"fileFlg\":\"0\",\n" + |
|
"\"userId\":\"\",\n" + |
|
"\"branchId\":\"\",\n" + |
|
"\"company\":\"\",\n" + |
|
"\"sourceBranchNo\":\"\",\n" + |
|
"\"apprUserId\":\"\",\n" + |
|
"\"macValue\":\"\",\n" + |
|
"\"srcSysTmnlNo\":\"\",\n" + |
|
"\"srcSysSvrId\":\"\",\n" + |
|
"\"filePath\":\"\",\n" + |
|
"\"authFlag\":\"\",\n" + |
|
"\"apprFlag\":\"\",\n" + |
|
"\"cnsmSysSvrId\":\"\",\n" + |
|
"\"destBranchNo\":\"\",\n" + |
|
"\"tmnIdNo\":\"\",\n" + |
|
"\"sourceType\":\"\",\n" + |
|
"\"authUserId\":\"\",\n" + |
|
"\"programId\":\"\"\n" + |
|
"},\n" + |
|
"\"appHead\": {},\n" + |
|
"\"body\": {\n" + |
|
"\"tranCd\": \"xx\",\n" + |
|
"\"chnlNo\": \"xxx\",\n" + |
|
"\"subBnkNo\": \"xxx\",\n" + |
|
"\"brNo\": \"xxx." + orgId + "\",\n" + |
|
"\"tlrNo\": \"xxx\",\n" + |
|
"\"bsnDt\": \"" + getcurrentDate() + "\",\n" + |
|
"\"bsnTm\": \"" + getcurrentTime() + "\",\n" + |
|
"\"chnlSeqNo\": \"" + getId() + "\",\n" + |
|
"\"mvmtBsnData\": \"\",\n" + |
|
"\"stmpId\": \"xx\"\n" + |
|
"}\n" + |
|
"}"; |
|
|
|
LogKit.info("印章集成,请求链接:" + url); |
|
LogKit.info("印章集成,请求内容:\n" + bodyContent); |
|
|
|
|
|
CloseableHttpClient httpClient = Utils.createHttpClient(url); |
|
String resBodyContent = Utils.createHttpPostContent(httpClient, url, bodyContent, "", "application/json;charset=UTF-8"); |
|
httpClient.close(); |
|
if (StringKit.isEmpty(resBodyContent)) { |
|
return ""; |
|
} |
|
LogKit.info("印章集成,响应内容:\n" + resBodyContent); |
|
|
|
|
|
JSONObject jsonObject = new JSONObject(resBodyContent); |
|
if (!jsonObject.containsKey("body")) { |
|
return ""; |
|
} |
|
JSONObject bodyJson = jsonObject.getJSONObject("body"); |
|
if (!bodyJson.containsKey("stmpImgCntnt")) { |
|
return ""; |
|
} |
|
String base64Content = bodyJson.getString("stmpImgCntnt"); |
|
if (StringKit.isEmpty(base64Content)) { |
|
return ""; |
|
} |
|
return base64Content; |
|
} catch (Exception e) { |
|
LogKit.info("印章集成,获取印章出错," + e.getMessage(), e); |
|
} |
|
return ""; |
|
} |
|
|
|
private static String getId() { |
|
String value = "ORSJ" + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmssSSS"); |
|
return value; |
|
} |
|
|
|
private static String getcurrentDate() { |
|
String value = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd"); |
|
return value; |
|
} |
|
|
|
private static String getcurrentTime() { |
|
String value = DateFormatUtils.format(System.currentTimeMillis(), "HHmmss"); |
|
return value; |
|
} |
|
|
|
private static String getcurrentTimeStamp() { |
|
String value = DateFormatUtils.format(System.currentTimeMillis(), "HHmmssSSS"); |
|
return value; |
|
} |
|
|
|
|
|
public static Set<String> getStampReportNames() { |
|
Set<String> names = new HashSet<>(); |
|
String content = StringKit.trim(CustomDataConfig.getInstance().getStampReportName()); |
|
if (StringKit.isEmpty(content)) { |
|
return names; |
|
} |
|
String[] tempNames = content.split(","); |
|
if ((tempNames == null) || (tempNames.length <= 0)) { |
|
return names; |
|
} |
|
|
|
String tempName; |
|
for (int i = 0, max = tempNames.length - 1; i <= max; i++) { |
|
tempName = StringKit.trim(tempNames[i]); |
|
if (StringKit.isEmpty(content)) { |
|
continue; |
|
} |
|
names.add(tempName); |
|
} |
|
return names; |
|
} |
|
|
|
public static boolean isStampReport(String path) { |
|
if (StringKit.isEmpty(path)) { |
|
return false; |
|
} |
|
Set<String> tempNames = getStampReportNames(); |
|
if (tempNames.size() <= 0) { |
|
return false; |
|
} |
|
if (tempNames.contains(path)) { |
|
return true; |
|
} |
|
return false; |
|
} |
|
|
|
public static boolean isNotStampReport(String path) { |
|
return !isStampReport(path); |
|
} |
|
|
|
//[{reportlet: '印章测试/垫款-保证.cpt', orgId:123456}] |
|
//FR.doURLPDFPrint |
|
public static boolean isDoURLPDFPrint(String path) { |
|
if (StringKit.isEmpty(path)) { |
|
return false; |
|
} |
|
try { |
|
JSONArray jsons = new JSONArray(path); |
|
if ((jsons == null) || (jsons.size() <= 0)) { |
|
return false; |
|
} |
|
JSONObject json = jsons.getJSONObject(0); |
|
if (!json.containsKey("reportlet")) { |
|
return false; |
|
} |
|
} catch (Exception e) { |
|
return false; |
|
} |
|
return true; |
|
} |
|
|
|
public static boolean isNotDoURLPDFPrint(String path) { |
|
return !isDoURLPDFPrint(path); |
|
} |
|
|
|
public static String getOrgIdByDoURLPDFPrint(String path) { |
|
if (isNotDoURLPDFPrint(path)) { |
|
return ""; |
|
} |
|
JSONArray jsons = new JSONArray(path); |
|
if ((jsons == null) || (jsons.size() <= 0)) { |
|
return ""; |
|
} |
|
JSONObject json = jsons.getJSONObject(0); |
|
String orgId = json.getString("orgId", ""); |
|
return orgId; |
|
} |
|
|
|
public static final String TEMP_DIRECTORY_NAME = "jsdbacfj-export-temp"; |
|
|
|
|
|
/** |
|
* 获取临时目录 |
|
* |
|
* @return |
|
*/ |
|
public static String getTempDirectory() { |
|
File file = new File(CacheManager.getProviderInstance().getCacheDirectory(), TEMP_DIRECTORY_NAME); |
|
return file.getAbsolutePath(); |
|
} |
|
|
|
|
|
/** |
|
* 获取临时导出目录 |
|
* |
|
* @return |
|
*/ |
|
public static String getTempExportPath() { |
|
String path = UUID.randomUUID().toString(); |
|
File file = new File(getTempDirectory(), path); |
|
return file.getAbsolutePath(); |
|
} |
|
|
|
/** |
|
* 删除临时目录 |
|
*/ |
|
public static void deleteTempDirectory() throws IOException { |
|
deleteFile(getTempDirectory()); |
|
} |
|
|
|
/** |
|
* jvm退出时删除临时目录 |
|
*/ |
|
public static void deleteTempDirectoryByShutdownHook() { |
|
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { |
|
@Override |
|
public void run() { |
|
try { |
|
LogKit.info("Delete temporary directory on Shutdown"); |
|
deleteTempDirectory(); |
|
} catch (IOException e) { |
|
LogKit.error("Delete temporary directory on Shutdown," + e.getMessage()); |
|
} |
|
} |
|
}) { |
|
}); |
|
} |
|
|
|
|
|
/** |
|
* 删除文件 |
|
* |
|
* @param target |
|
* @throws IOException |
|
*/ |
|
public static void deleteFile(String target) throws IOException { |
|
deleteFile(Paths.get(target)); |
|
} |
|
|
|
/** |
|
* 删除文件 |
|
* |
|
* @param target |
|
* @throws IOException |
|
*/ |
|
public static void deleteFile(Path target) throws IOException { |
|
if (Files.isDirectory(target)) { |
|
FileUtils.deleteDirectory(target.toFile()); |
|
return; |
|
} |
|
Files.deleteIfExists(target); |
|
} |
|
|
|
/** |
|
* 复制流 |
|
* |
|
* @param inputStream |
|
* @param outputStream |
|
* @throws IOException |
|
*/ |
|
public static void copyStreamByNio(InputStream inputStream, OutputStream outputStream) throws IOException { |
|
int bufferSize = 10485760;//1024 * 1024 * 10; |
|
ReadableByteChannel input = Channels.newChannel(inputStream); |
|
WritableByteChannel output = Channels.newChannel(outputStream); |
|
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize); |
|
while ((input.read(byteBuffer)) != -1) { |
|
//切换读取模式 |
|
byteBuffer.flip(); |
|
output.write(byteBuffer); |
|
byteBuffer.clear(); |
|
} |
|
input.close(); |
|
outputStream.flush(); |
|
outputStream.close(); |
|
} |
|
|
|
|
|
/** |
|
* 判断是否是打印请求,需要加上印章 |
|
* |
|
* @param req |
|
* @return |
|
*/ |
|
public static boolean isAddStamp(HttpServletRequest req) { |
|
if (req == null) { |
|
return false; |
|
} |
|
String method = req.getMethod(); |
|
if (!"GET".equalsIgnoreCase(method)) { |
|
return false; |
|
} |
|
|
|
String reqUrl = req.getRequestURL().toString(); |
|
if (!reqUrl.endsWith("/decision/view/report")) { |
|
return false; |
|
} |
|
String op = WebUtils.getHTTPRequestParameter(req, "op"); |
|
if (!"fr_pdfprint".equals(op)) { |
|
return false; |
|
} |
|
|
|
String cmd = WebUtils.getHTTPRequestParameter(req, "cmd"); |
|
if (!"native".equals(cmd)) { |
|
return false; |
|
} |
|
|
|
String sessionID = WebUtils.getHTTPRequestParameter(req, "sessionID"); |
|
if (StringKit.isEmpty(sessionID)) { |
|
return false; |
|
} |
|
|
|
ReportSessionIDInfor reportSessionIDInfor = SessionPoolManager.getSessionIDInfor(sessionID, ReportSessionIDInfor.class); |
|
if (reportSessionIDInfor == null) { |
|
return false; |
|
} |
|
|
|
String relativePath = reportSessionIDInfor.getRelativePath(); |
|
if (isStampFlag(reportSessionIDInfor) || StampUtils.isStampReport(relativePath) || StampUtils.isDoURLPDFPrint(relativePath)) { |
|
return true; |
|
} |
|
return false; |
|
} |
|
|
|
public static boolean isStampFlag(ReportSessionIDInfor reportSessionIDInfor) { |
|
if (reportSessionIDInfor == null) { |
|
return false; |
|
} |
|
Object value = reportSessionIDInfor.getParameterValue("STAMP"); |
|
if (value == null) { |
|
return false; |
|
} |
|
if ("1".equals(value)) { |
|
return true; |
|
} |
|
return false; |
|
} |
|
|
|
public static String getOrgIdByReportSessionIDInfor(ReportSessionIDInfor reportSessionIDInfor) { |
|
if (!isStampFlag(reportSessionIDInfor)) { |
|
return ""; |
|
} |
|
Object value = reportSessionIDInfor.getParameterValue("ORGID"); |
|
if (value == null) { |
|
return ""; |
|
} |
|
String orgId = String.valueOf(value); |
|
return orgId; |
|
} |
|
|
|
public static void addStamp(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws Exception { |
|
if (!PluginContexts.currentContext().isAvailable()) { |
|
LogKit.error("印章集成插件试用过期, 请添加许可证"); |
|
filterChain.doFilter(req, res); |
|
return; |
|
} |
|
|
|
|
|
String sessionID = WebUtils.getHTTPRequestParameter(req, "sessionID"); |
|
ReportSessionIDInfor reportSessionIDInfor = SessionPoolManager.getSessionIDInfor(sessionID, ReportSessionIDInfor.class); |
|
if (reportSessionIDInfor == null) { |
|
filterChain.doFilter(req, res); |
|
return; |
|
} |
|
String relativePath = reportSessionIDInfor.getRelativePath(); |
|
String orgId = StampUtils.getOrgIdByDoURLPDFPrint(relativePath); |
|
if (StringKit.isEmpty(orgId)) { |
|
orgId = StampUtils.getOrgIdByReportSessionIDInfor(reportSessionIDInfor); |
|
} |
|
String stampBase64 = StampUtils.getStampBase64(orgId); |
|
if (StringKit.isEmpty(stampBase64)) { |
|
filterChain.doFilter(req, res); |
|
return; |
|
} |
|
|
|
String dirPath = StampUtils.getTempExportPath(); |
|
Path path = Paths.get(dirPath); |
|
Files.createDirectories(path); |
|
String filePath = dirPath + "/a.pdf"; |
|
String filePath1 = dirPath + "/b.pdf"; |
|
createPrintPdf(req, filePath, reportSessionIDInfor, sessionID); |
|
addStampWithPdf(stampBase64, filePath, filePath1); |
|
writePdfToResponse(req, res, reportSessionIDInfor, filePath1); |
|
deleteFile(path); |
|
} |
|
|
|
private static void writePdfToResponse(HttpServletRequest req, HttpServletResponse res, ReportSessionIDInfor reportSessionIDInfor, String pdfPath) throws IOException { |
|
addFrameOptions(req, res); |
|
boolean previewOption = Boolean.parseBoolean(WebUtils.getHTTPRequestParameter(req, "preview")); |
|
if (!previewOption) { |
|
LogUtils.recordPrintInformation(reportSessionIDInfor.getRelativePath(), reportSessionIDInfor.getParameterMap4Execute4Consisent(), ReportDeclareRecordType.PRINT_TYPE_NO_CLIENT, reportSessionIDInfor); |
|
} |
|
writePdfToResponse(res, pdfPath); |
|
} |
|
|
|
public static void writePdfToResponse(HttpServletResponse res, String pdfPath) throws IOException { |
|
res.setContentType("application/pdf"); |
|
ServletOutputStream servletOutputStream = res.getOutputStream(); |
|
FileInputStream fileInputStream = new FileInputStream(pdfPath); |
|
copyStreamByNio(fileInputStream, servletOutputStream); |
|
} |
|
|
|
public static void addFrameOptions(HttpServletRequest req, HttpServletResponse res) { |
|
String referer = req.getHeader("Referer"); |
|
if (StringUtils.isEmpty(referer)) { |
|
return; |
|
} |
|
String host = getHost(referer); |
|
Collection headerNames = res.getHeaderNames(); |
|
if (headerNames.contains("X-Frame-Options")) { |
|
res.setHeader("X-Frame-Options", "ALLOW-FROM " + host); |
|
} |
|
} |
|
|
|
private static String getHost(String value) { |
|
int index = value.indexOf("/", value.indexOf("//") + 2); |
|
return index == -1 ? value : value.substring(0, index); |
|
} |
|
|
|
private static void createPrintPdf(HttpServletRequest req, String filePath, ReportSessionIDInfor reportSessionIDInfor, String sessionID) throws Exception { |
|
float[] offset = getOffset(reportSessionIDInfor); |
|
reportSessionIDInfor.getPrintContext().setOffset(offset); |
|
PageSetProvider pageSet = reportSessionIDInfor.getPrintPreviewPageSet4Traversing(); |
|
FileOutputStream fileOutputStream = new FileOutputStream(filePath); |
|
PDFExporterForPrint pdfExporter = new PDFExporterForPrint(); |
|
pdfExporter.export(fileOutputStream, pageSet); |
|
fileOutputStream.flush(); |
|
fileOutputStream.close(); |
|
LogUtils.recordPrintInformation(reportSessionIDInfor.getRelativePath(), reportSessionIDInfor.getParameterMap4Execute4Consisent(), ReportDeclareRecordType.PRINT_TYPE_PDF, reportSessionIDInfor); |
|
boolean needKeepSession = NetworkHelper.getHTTPRequestBoolParameter(req, "needKeepSession"); |
|
if (!needKeepSession) { |
|
SessionPoolManager.closeSession(sessionID); |
|
} |
|
} |
|
|
|
|
|
public static float[] getOffset(SessionProvider sessionIDInfor) { |
|
return getOffset(sessionIDInfor.getWebContext().getAddress(), sessionIDInfor.getWebTitle(), new TypeIP()); |
|
} |
|
|
|
|
|
public static float[] getOffset(String remote_IP, String cptName, TypeIP type) { |
|
try { |
|
float[] offset = getRemoteOffset(remote_IP, type); |
|
type.setType(PrintOffsetSign.SIGN_ALL); |
|
PrintOffsetController controller = ReportContext.getInstance().getPrintOffsetController(); |
|
if (controller.findOne(remote_IP, cptName, PrintOffsetSign.SIGN_SINGLE.getSign()) != null) { |
|
type.setIP(""); |
|
offset = getRemoteOffset(remote_IP, cptName, type); |
|
type.setType(PrintOffsetSign.SIGN_SINGLE); |
|
} |
|
|
|
return offset; |
|
} catch (Exception e) { |
|
LogKit.error(e.getMessage(), e); |
|
} |
|
type.setType(PrintOffsetSign.SIGN_NONE); |
|
return new float[2]; |
|
} |
|
|
|
|
|
private static float[] getRemoteOffset(String remote_IP, TypeIP type) { |
|
return getRemoteOffset(remote_IP, "", PrintOffsetSign.SIGN_ALL.getSign(), type); |
|
} |
|
|
|
private static float[] getRemoteOffset(String remote_IP, String cptName, TypeIP type) { |
|
return getRemoteOffset(remote_IP, cptName, PrintOffsetSign.SIGN_SINGLE.getSign(), type); |
|
} |
|
|
|
private static float[] getRemoteOffset(String remote_IP, String cptName, String sign, TypeIP type) { |
|
float[] offset = new float[]{0.0F, 0.0F}; |
|
PrintOffsetController controller = ReportContext.getInstance().getPrintOffsetController(); |
|
PrintOffsetEntity entity = controller.findOne(remote_IP, cptName, sign); |
|
if (entity != null) { |
|
type.setIP(entity.getIp()); |
|
offset[0] = Float.parseFloat(entity.getOffsetX()); |
|
offset[1] = Float.parseFloat(entity.getOffsetY()); |
|
} |
|
return offset; |
|
} |
|
|
|
public static void addStampWithPdf111(String stampBase64, String srcFilePath, String targetFilePath) throws Exception { |
|
PDDocument doc = PDDocument.load(new File(srcFilePath)); |
|
|
|
float width = getZoomValue(609f); |
|
float height = getZoomValue(397f); |
|
width = 182.7f; |
|
height = 119.1f; |
|
|
|
byte[] stampBytes = Base64.decode(stampBase64); |
|
PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, stampBytes, "stamp.png"); |
|
PDExtendedGraphicsState pdExtGfxState = new PDExtendedGraphicsState(); |
|
// 设置透明度 |
|
pdExtGfxState.setNonStrokingAlphaConstant(getStampOpacity()); |
|
pdExtGfxState.setAlphaSourceFlag(true); |
|
pdExtGfxState.getCOSObject().setItem(COSName.BM, COSName.MULTIPLY); |
|
|
|
float configX = CustomDataConfig.getInstance().getStampPositionX(); |
|
float configY = CustomDataConfig.getInstance().getStampPositionY(); |
|
float x = 0; |
|
float y = 0; |
|
PDPage page; |
|
PDPageContentStream contentStream; |
|
PDRectangle rectangle; |
|
for (int i = 0, max = doc.getNumberOfPages() - 1; i <= max; i++) { |
|
page = doc.getPage(i); |
|
if (i == 0) { |
|
rectangle = page.getMediaBox(); |
|
x = getFitValue(configX, rectangle.getWidth(), width); |
|
y = getFitValue(configY, rectangle.getHeight(), height); |
|
x = 300; |
|
y = 100; |
|
} |
|
contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true); |
|
contentStream.setGraphicsStateParameters(pdExtGfxState); |
|
contentStream.drawImage(pdImage, x, y, width, height); |
|
contentStream.close(); |
|
} |
|
doc.save(targetFilePath); |
|
doc.close(); |
|
} |
|
|
|
public static void addStampWithPdf(String stampBase64, String srcFilePath, String targetFilePath) throws Exception { |
|
addStampWithPdf(stampBase64, srcFilePath, targetFilePath, -1, -1, -1, -1, -1); |
|
} |
|
|
|
/** |
|
* 在pdf上面添加印章 |
|
* |
|
* @param stampBase64 图片base64 |
|
* @param srcFilePath pdf源位置 |
|
* @param targetFilePath pdf目标位置 |
|
* @param stampXThousandths 印章横向位置 按1000来 |
|
* @param stampYThousandths 印章纵向位置 按1000来 |
|
* @param stampIntervalThousandths 印章间隔 按1000来 |
|
* @param stampWidthThousandths 印章宽 按1000来 |
|
* @param stampHeightThousandths 印章高 按1000来 |
|
* @throws Exception |
|
*/ |
|
public static void addStampWithPdf(String stampBase64, String srcFilePath, String targetFilePath, int stampXThousandths, int stampYThousandths, int stampIntervalThousandths, int stampWidthThousandths, int stampHeightThousandths) throws Exception { |
|
float defaultX = 300; |
|
float defaultY = 100; |
|
float defaultWidth = 182.7f; |
|
float defaultHeight = 119.1f; |
|
|
|
if (StringKit.isEmpty(stampBase64)) { |
|
return; |
|
} |
|
|
|
PDDocument doc = PDDocument.load(new File(srcFilePath)); |
|
byte[] stampBytes = Base64.decode(stampBase64); |
|
PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, stampBytes, "stamp.png"); |
|
PDExtendedGraphicsState pdExtGfxState = new PDExtendedGraphicsState(); |
|
|
|
// 设置透明度 |
|
pdExtGfxState.setNonStrokingAlphaConstant(getStampOpacity()); |
|
pdExtGfxState.setAlphaSourceFlag(true); |
|
pdExtGfxState.getCOSObject().setItem(COSName.BM, COSName.MULTIPLY); |
|
|
|
PDPage page; |
|
PDPageContentStream contentStream; |
|
PDRectangle rectangle; |
|
|
|
|
|
float stampX = 0, stampY = 0, stampInterval = 0; |
|
float stampWidth = 0, stampHeight = 0; |
|
|
|
float pageWidth = 0; |
|
float pageHeight = 0; |
|
for (int i = 0, max = doc.getNumberOfPages() - 1; i <= max; i++) { |
|
page = doc.getPage(i); |
|
rectangle = page.getMediaBox(); |
|
pageWidth = rectangle.getWidth(); |
|
pageHeight = rectangle.getHeight(); |
|
stampX = defaultX; |
|
stampY = defaultY; |
|
stampInterval = 0; |
|
stampWidth = defaultWidth; |
|
stampHeight = defaultHeight; |
|
if (stampXThousandths >= 0) { |
|
stampX = getRealValue(stampXThousandths, pageWidth); |
|
} |
|
if (stampYThousandths >= 0) { |
|
stampY = getRealValue(stampYThousandths, pageHeight); |
|
} |
|
if (stampIntervalThousandths > 0) { |
|
stampInterval = getRealValue(stampIntervalThousandths, pageHeight); |
|
} |
|
|
|
if (stampWidthThousandths > 0) { |
|
stampWidth = getRealValue(stampWidthThousandths, pageWidth); |
|
} |
|
if (stampHeightThousandths > 0) { |
|
stampHeight = getRealValue(stampHeightThousandths, pageHeight); |
|
} |
|
|
|
contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true); |
|
contentStream.setGraphicsStateParameters(pdExtGfxState); |
|
contentStream.drawImage(pdImage, stampX, stampY, stampWidth, stampHeight); |
|
if (stampInterval > 0) { |
|
stampY = stampY + stampInterval; |
|
while (stampY < pageHeight) { |
|
contentStream.drawImage(pdImage, stampX, stampY, stampWidth, stampHeight); |
|
stampY = stampY + stampInterval; |
|
} |
|
} |
|
contentStream.close(); |
|
} |
|
doc.save(targetFilePath); |
|
doc.close(); |
|
|
|
|
|
} |
|
|
|
private static float getRealValue(int thousandths, float baseValue) { |
|
if ((thousandths <= 0) || (baseValue <= 0)) { |
|
return 0f; |
|
} |
|
if (thousandths >= 1000) { |
|
return baseValue; |
|
} |
|
|
|
float value = thousandths * 0.001f * baseValue; |
|
return value; |
|
} |
|
|
|
|
|
private static float getFitValue(float configValue, float maxValue, float blankValue) { |
|
if (configValue <= 0) { |
|
return 0; |
|
} |
|
float tempValue; |
|
if ((configValue + blankValue) >= maxValue) { |
|
tempValue = maxValue - blankValue; |
|
if (tempValue <= 0) { |
|
tempValue = 0; |
|
} |
|
return tempValue; |
|
} |
|
return configValue; |
|
} |
|
|
|
private static float getZoomValue(float value) { |
|
int zoom = CustomDataConfig.getInstance().getStampScaling(); |
|
if (zoom <= 0) { |
|
zoom = 20; |
|
} |
|
BigDecimal b = new BigDecimal(String.valueOf(value)); |
|
b = b.multiply(new BigDecimal(String.valueOf(zoom))); |
|
b = b.multiply(new BigDecimal("0.01")); |
|
b = b.setScale(1, BigDecimal.ROUND_HALF_UP); |
|
return b.floatValue(); |
|
} |
|
|
|
public static float getStampOpacity() { |
|
int value = CustomDataConfig.getInstance().getStampTransparent(); |
|
if (value <= 0) { |
|
value = 0; |
|
} |
|
if (value >= 100) { |
|
value = 100; |
|
} |
|
int tempValue = 100 - value; |
|
BigDecimal b0 = new BigDecimal(String.valueOf(tempValue)); |
|
BigDecimal b1 = new BigDecimal("100"); |
|
BigDecimal b2 = b0.divide(b1, 2, BigDecimal.ROUND_HALF_UP); |
|
float opacityValue = b2.floatValue(); |
|
return opacityValue; |
|
} |
|
}
|
|
|