使用pdfbox 2.0.12 java的多重设计?
我试图在stamper上的单个pdf中添加多个签名。我可以添加多个母版。在我的一个例子中,我得到了错误 至少有一个签名无效 我想在一个PDF中添加多个有效符号。请帮帮我。 在图中,只有一个符号是有效的,其他符号是无效的,所以让我看看我做错了什么 下面是我的代码快照使用pdfbox 2.0.12 java的多重设计?,java,pdf,pdfbox,Java,Pdf,Pdfbox,我试图在stamper上的单个pdf中添加多个签名。我可以添加多个母版。在我的一个例子中,我得到了错误 至少有一个签名无效 我想在一个PDF中添加多个有效符号。请帮帮我。 在图中,只有一个符号是有效的,其他符号是无效的,所以让我看看我做错了什么 下面是我的代码快照 public void getSignOnPdf(Map<Integer, byte[]> PdfSigneture1, List<Long> documentIds, List<String> c
public void getSignOnPdf(Map<Integer, byte[]> PdfSigneture1, List<Long> documentIds, List<String> calTimeStamp,
String originalPdfReadServerPath, String tickImagePath, int serverTime, int pageNumberToInsertStamp,
String name, String location, String reasonForSign, int xCo_ordinates, int yCo_ordinates,
int signatureWidth, int signatureHeight, String pdfPassword, String internal_outputFinalPdfPath)
throws Exception {
String pdfReadServerPath = null;
String l_slash = new String();
String originalPDFPath = new String(originalPdfReadServerPath.trim());
boolean isCorrectPDFOutputPath = false;
String aspOutputPdfServerPath = null;
synchronized (this) {
if ((internal_outputFinalPdfPath != null) && (!internal_outputFinalPdfPath.trim().isEmpty())) {
System.out.println("[" + EsignCommonFuntion.generateTimeStampForLog()
+ "] :1--> outputFinalPdfPath is: " + internal_outputFinalPdfPath);
if (!(new File(internal_outputFinalPdfPath)).isFile()) {
isCorrectPDFOutputPath = true;
aspOutputPdfServerPath = internal_outputFinalPdfPath;
} else {
System.out.println("1--> Please provide directory path for outputFinalPdfPath: "
.concat(String.valueOf(internal_outputFinalPdfPath)));
}
} else {
System.out.println(" 1--> outputFinalPdfPath is empty or null: "
.concat(String.valueOf(internal_outputFinalPdfPath)));
}
}
boolean isPasswordPresent = false;
String pdfPasswordForEncryption;
synchronized (this) {
if ((pdfPassword != null) && (!pdfPassword.trim().isEmpty())) {
pdfPasswordForEncryption = pdfPassword.trim();
isPasswordPresent = true;
} else {
pdfPasswordForEncryption = null;
}
String pdfOriginalName = (new File(originalPDFPath)).getName();
String pdfAbsolutePath = originalPDFPath.substring(0, originalPDFPath.lastIndexOf(l_slash));
if (isPasswordPresent) {
pdfAbsolutePath = getEncryptedPdfName(originalPDFPath, pdfAbsolutePath + l_slash,
pdfPasswordForEncryption, pdfOriginalName);
pdfReadServerPath = new String(pdfAbsolutePath);
} else {
pdfReadServerPath = originalPDFPath;
}
}
ArrayList<String> unSignedFilesList = new ArrayList<String>();
Map<Integer, byte[]> l_PdfSigneture = PdfSigneture1;
int actual_pageNumForStamp = 1;
String pdfFileName = (new File(pdfReadServerPath)).getName();
FileOutputStream fos = null;
String nameToShowInSignature = name;
String locationToShowInSignature = location;
String reasonForSignatureSign = reasonForSign;
PDDocument documentFinal = null;
try {
pdfReadServerPath = pdfReadServerPath.substring(0, pdfReadServerPath.lastIndexOf(l_slash));
System.out.println("inside getSignOnMethod pdfAbsolutePath:".concat(String.valueOf(pdfReadServerPath)));
unSignedFilesList.add(pdfFileName);
System.out.println("inside getSignOnMethod pdfFileName:".concat(String.valueOf(pdfFileName)));
String PDFpath = pdfReadServerPath + l_slash + (String) (unSignedFilesList).get(0);
System.out.println("Inside for PDFpath: ".concat(String.valueOf(PDFpath)));
String finalOutputPdfName = ((String) (unSignedFilesList).get(0)).substring(0,
((String) (unSignedFilesList).get(0)).lastIndexOf(".")) + "_signedFinal.pdf";
File outFile2 = null;
if (isCorrectPDFOutputPath) {
System.out.println("if condition Final signed PDF ouptut Path: " + aspOutputPdfServerPath + l_slash
+ finalOutputPdfName);
outFile2 = new File(aspOutputPdfServerPath + l_slash + finalOutputPdfName);
fos = new FileOutputStream(outFile2);
} else {
outFile2 = new File(pdfReadServerPath + l_slash + outFile2);
fos = new FileOutputStream(outFile2);
}
documentFinal = PDDocument.load(new File(PDFpath));
for (int i = 1; i < 4; i++) {
FileInputStream image2 = new FileInputStream(tickImagePath);
PDSignature pdsignature = new PDSignature();
pdsignature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
pdsignature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
Calendar cal = GregorianCalendar.getInstance();
SimpleDateFormat l_simpleDateFormater = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timeStamp = (String) calTimeStamp.get(i - 1);
try {
cal.setTime(l_simpleDateFormater.parse(timeStamp));
} catch (ParseException ex) {
ex.printStackTrace();
}
cal.add(12, serverTime);
pdsignature.setSignDate(cal);
documentFinal.setDocumentId((Long) documentIds.get(i - 1));
String dateToShowInSignature = cal.getTime().toString();
Float saveIncrementalObj1 = null;
saveIncrementalObj1 = new Float((float) xCo_ordinates, (float) yCo_ordinates, (float) signatureWidth,
(float) signatureHeight);
PDRectangle rect = getPDRectangle(documentFinal, saveIncrementalObj1, i);
PDVisibleSignDesigner visibleSig;
(visibleSig = new PDVisibleSignDesigner(documentFinal, image2, i)).xAxis(xCo_ordinates)
.yAxis(yCo_ordinates).zoom(-95.0F).signatureFieldName("signature");
PDVisibleSigProperties visibleSignatureProp = new PDVisibleSigProperties();
visibleSignatureProp.signerName("name").signerLocation("location").signatureReason("Security")
.preferredSize(0).page(i - 1).visualSignEnabled(true).setPdVisibleSignature(visibleSig)
.buildSignature();
try {
PdfSigneture = new TreeMap<>();
// PdfSigneture.clear();
PdfSigneture = l_PdfSigneture;
if (visibleSignatureProp.isVisualSignEnabled()) {
this.options = new SignatureOptions();
this.options.setVisualSignature(visibleSignatureProp);
this.options.setPage(visibleSignatureProp.getPage());
this.options.setVisualSignature(
getInputStream(documentFinal, i, rect, tickImagePath, nameToShowInSignature,
locationToShowInSignature, dateToShowInSignature, reasonForSignatureSign));
documentFinal.addSignature(pdsignature, this, this.options);
} else {
documentFinal.addSignature(pdsignature, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
synchronized (this) {
SaveIncrementalSignObject saveIncrementalSignObject;
(saveIncrementalSignObject = new SaveIncrementalSignObject()).setFos(fos);
saveIncrementalSignObject.setPDDocumentFromFile(documentFinal);
saveIncrementalForSign(saveIncrementalSignObject);
}
} catch (Exception localException2) {
System.out.println("Insidemethod -- Exception block" + localException2.getMessage());
return;
} finally {
fos.flush();
if (fos != null) {
fos.close();
}
documentFinal.close();
}
}
public static synchronized void saveIncrementalForSign(SaveIncrementalSignObject p_SaveIncrementalObj) {
PDDocument documentFinal = null;
try {
(documentFinal = p_SaveIncrementalObj.getPDDocumentFromFile())
.saveIncremental(p_SaveIncrementalObj.getFos());
} catch (Exception e) {
e.printStackTrace();
try {
// documentFinal.close();
return;
} catch (Exception eX) {
eX.printStackTrace();
return;
}
}
}
public void getSignOnPdf(映射PdfSigneture1,列表DocumentID,列表calTimeStamp,
字符串originalPdfReadServerPath、字符串tickImagePath、int serverTime、int pageNumberToInsertStamp、,
字符串名称、字符串位置、字符串原因符号、int xCo坐标、int yCo坐标、,
int signatureWidth、int signatureHeight、字符串pdfPassword、字符串内部\u outputFinalPdfPath)
抛出异常{
字符串pdfReadServerPath=null;
字符串l_斜杠=新字符串();
String originalPDFPath=新字符串(originalpdfreaserverpath.trim());
布尔值IsCorrectPdfoutPath=false;
字符串aspOutputPdfServerPath=null;
已同步(此){
if((internal_outputFinalPdfPath!=null)&(!internal_outputFinalPdfPath.trim().isEmpty()){
System.out.println(“[”+esignCommonFunction.generateTimeStampForLog()
+“]:1-->OutputFinalPDPath为:“+内部\u OutputFinalPDPath”;
如果(!(新文件(内部_outputFinalPdfPath)).isFile()){
iscorrectpdfoutpath=true;
aspOutputPdfServerPath=内部\u outputFinalPdfPath;
}否则{
System.out.println(“1-->请为OutputFinalPDPath提供目录路径:”
.concat(String.valueOf(internal_outputFinalPdfPath));
}
}否则{
System.out.println(“1-->OutputFinalPDPath为空或空:”
.concat(String.valueOf(internal_outputFinalPdfPath));
}
}
布尔值isPasswordPresent=false;
字符串pdfPasswordForEncryption;
已同步(此){
如果((pdfPassword!=null)&(!pdfPassword.trim().isEmpty()){
pdfPasswordForEncryption=pdfPassword.trim();
isPasswordPresent=true;
}否则{
pdfPasswordForEncryption=null;
}
字符串pdfOriginalName=(新文件(originalPDFPath)).getName();
字符串pdfAbsolutePath=originalPDFPath.substring(0,originalPDFPath.lastIndexOf(l_斜杠));
如果(isPasswordPresent){
pdfAbsolutePath=getEncryptedPdfName(原始数据路径,pdfAbsolutePath+l_斜杠,
PDFPassword表示加密,PDFPassword表示原始名称);
pdfReadServerPath=新字符串(pdfAbsolutePath);
}否则{
pdfReadServerPath=originalPDFPath;
}
}
ArrayList unsignedFileList=新建ArrayList();
映射l_PdfSigneture=PdfSigneture1;
int-actual_pageNumForStamp=1;
字符串pdfFileName=(新文件(pdfReadServerPath)).getName();
FileOutputStream=null;
字符串名称ToShowInSignature=名称;
字符串位置ToShowInSignature=位置;
字符串reasonForSignatureSign=reasonForSign;
PDDocument documentFinal=null;
试一试{
pdfReadServerPath=pdfReadServerPath.substring(0,pdfReadServerPath.lastIndexOf(l_斜杠));
System.out.println(“内部getSignOnMethod pdfAbsolutePath:”.concat(String.valueOf(pdfReadServerPath));
unSignedFilesList.add(pdfFileName);
System.out.println(“内部GetSignonMethodPdfileName:.concat(String.valueOf(PdfileName));
字符串PDFpath=pdfReadServerPath+l_斜杠+(字符串)(unSignedFilesList).get(0);
System.out.println(“PDFpath的内部:”.concat(String.valueOf(PDFpath));
字符串finalOutputPdfName=((字符串)(unSignedFilesList).get(0)).substring(0,
((字符串)(unSignedFilesList.get(0)).lastIndexOf(“.”)+“_signedFinal.pdf”;
文件outFile2=null;
if(iscorrectpdfoutpath){
System.out.println(“如果条件最终签名PDF输出路径:”+aspOutputPdfServerPath+l_斜杠
+FinalOutpDfName);
outFile2=新文件(aspOutputPdfServerPath+l_斜杠+finalOutputPdfName);
fos=新文件输出流(输出流2);
}否则{
outFile2=新文件(pdfReadServerPath+l_斜杠+outFile2);
fos=新文件输出流(输出流2);
}
documentFinal=PDDocument.load(新文件(PDFpath));
对于(int i=1;i<4;i++){
FileInputStream image2=新的FileInputStream(tickImagePath);
PDSignature PDSignature=新的PDSignature();
pdsignature.setFilter(pdsignature.FILTER\u ADOBE\u PPKLITE);
pdsignature.setSubFilter(pdsignature.SUBFILTER_ADBE_PKCS7_分离);
Calendar cal=GregorianCalendar.getInstance();
SimpleDataFormat l_SimpleDataFormat=新的SimpleDataFormat(“yyyyMMdd_HHmmss”);
String timeStamp=(String)calTimeStamp.get(i-1);
试一试{
cal.setTime(l_SimpleDataFormat.parse(时间戳));
}捕获(解析异常){
例如printStackTrace();
}
计算添加(12,服务器时间);
pdsignature.setSignDate(标定);
setDocumentId((长)documentId.get(i-1));
字符串dateToShowInSignature=cal.getTime().toString();
Float saveIncrementalObj1=null;
saveIncrementalObj1=新浮点((浮点)xCo_坐标,(浮点)yCo_坐标,(浮点)符号宽度,
(浮动)签名权);
PDRectangle rect=getPDRectangle(documentFinal,saveIncrementalObj1,i);
PDVisibleSignDesigner VisibleSign;
(visibleSig=新PDVisibleSignDesigner(documentFinal,image2,i)).xAxis(xCo_坐标)
.yAxis(yCo_坐标)。缩放(-95.0F)。签名场名称(“签名”);
if (isPasswordPresent) {
documentFinal = PDDocument.load(new File(PDFpath), pdfPasswordForEncryption);
} else {
documentFinal = PDDocument.load(new File(PDFpath));
}
for (int i = 1; i < 4; i++) {
FileInputStream image2 = new FileInputStream(tickImagePath);
PDSignature pdsignature = new PDSignature();
[...]
try {
[...]
if (visibleSignatureProp.isVisualSignEnabled()) {
[...]
documentFinal.addSignature(pdsignature, this, this.options);
} else {
documentFinal.addSignature(pdsignature, this);
}
} catch (Exception e) {
System.out.println("Inside getSignOnPdf sub exception block at addSignature:" + e + "error :" + e.getMessage());
e.printStackTrace();
}
}
synchronized (this) {
[...]
saveIncrementalForSign(saveIncrementalSignObject);
}
for (int i = 1; i < 4; i++) {
load current version of the PDF;
apply the i'th signature;
save and sign as new current version of the PDF;
}
void addSignatureField(PDDocument pdDocument, PDPage pdPage, PDRectangle rectangle, PDSignature signature) throws IOException {
PDAcroForm acroForm = pdDocument.getDocumentCatalog().getAcroForm();
List<PDField> acroFormFields = acroForm.getFields();
PDSignatureField signatureField = new PDSignatureField(acroForm);
signatureField.setSignature(signature);
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
acroFormFields.add(signatureField);
widget.setRectangle(rectangle);
widget.setPage(pdPage);
// from PDVisualSigBuilder.createHolderForm()
PDStream stream = new PDStream(pdDocument);
PDFormXObject form = new PDFormXObject(stream);
PDResources res = new PDResources();
form.setResources(res);
form.setFormType(1);
PDRectangle bbox = new PDRectangle(rectangle.getWidth(), rectangle.getHeight());
float height = bbox.getHeight();
form.setBBox(bbox);
PDFont font = PDType1Font.HELVETICA_BOLD;
// from PDVisualSigBuilder.createAppearanceDictionary()
PDAppearanceDictionary appearance = new PDAppearanceDictionary();
appearance.getCOSObject().setDirect(true);
PDAppearanceStream appearanceStream = new PDAppearanceStream(form.getCOSObject());
appearance.setNormalAppearance(appearanceStream);
widget.setAppearance(appearance);
try (PDPageContentStream cs = new PDPageContentStream(pdDocument, appearanceStream))
{
// show background (just for debugging, to see the rect size + position)
cs.setNonStrokingColor(Color.yellow);
cs.addRect(-5000, -5000, 10000, 10000);
cs.fill();
float fontSize = 10;
float leading = fontSize * 1.5f;
cs.beginText();
cs.setFont(font, fontSize);
cs.setNonStrokingColor(Color.black);
cs.newLineAtOffset(fontSize, height - leading);
cs.setLeading(leading);
cs.showText("Signature text");
cs.newLine();
cs.showText("some additional Information");
cs.newLine();
cs.showText("let's keep talking");
cs.endText();
}
pdPage.getAnnotations().add(widget);
COSDictionary pageTreeObject = pdPage.getCOSObject();
while (pageTreeObject != null) {
pageTreeObject.setNeedToBeUpdated(true);
pageTreeObject = (COSDictionary) pageTreeObject.getDictionaryObject(COSName.PARENT);
}
}
try ( InputStream resource = PDF_SOURCE_STREAM;
OutputStream result = PDF_TARGET_STREAM;
PDDocument pdDocument = PDDocument.load(resource) )
{
PDAcroForm acroForm = pdDocument.getDocumentCatalog().getAcroForm();
if (acroForm == null) {
pdDocument.getDocumentCatalog().setAcroForm(acroForm = new PDAcroForm(pdDocument));
}
acroForm.setSignaturesExist(true);
acroForm.setAppendOnly(true);
acroForm.getCOSObject().setDirect(true);
PDRectangle rectangle = new PDRectangle(100, 600, 300, 100);
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setName("Example User");
signature.setLocation("Los Angeles, CA");
signature.setReason("Testing");
signature.setSignDate(Calendar.getInstance());
pdDocument.addSignature(signature, this);
for (PDPage pdPage : pdDocument.getPages()) {
addSignatureField(pdDocument, pdPage, rectangle, signature);
}
pdDocument.saveIncremental(result);
}