diff options
Diffstat (limited to 'pdf-as-pdfbox-2/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox2/PADESPDFBOXSigner.java')
-rw-r--r-- | pdf-as-pdfbox-2/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox2/PADESPDFBOXSigner.java | 788 |
1 files changed, 330 insertions, 458 deletions
diff --git a/pdf-as-pdfbox-2/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox2/PADESPDFBOXSigner.java b/pdf-as-pdfbox-2/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox2/PADESPDFBOXSigner.java index 42f16598..36d7dade 100644 --- a/pdf-as-pdfbox-2/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox2/PADESPDFBOXSigner.java +++ b/pdf-as-pdfbox-2/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox2/PADESPDFBOXSigner.java @@ -70,8 +70,6 @@ import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.schema.PDFAIdentificationSchema; import org.apache.xmpbox.xml.DomXmpParser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import at.gv.egiz.pdfas.common.exceptions.PDFASError; import at.gv.egiz.pdfas.common.exceptions.PdfAsException; @@ -83,7 +81,6 @@ import at.gv.egiz.pdfas.lib.api.sign.IPlainSigner; import at.gv.egiz.pdfas.lib.api.sign.SignParameter; import at.gv.egiz.pdfas.lib.impl.ErrorExtractor; import at.gv.egiz.pdfas.lib.impl.SignaturePositionImpl; -import at.gv.egiz.pdfas.lib.impl.configuration.PlaceholderWebConfiguration; import at.gv.egiz.pdfas.lib.impl.configuration.SignatureProfileConfiguration; import at.gv.egiz.pdfas.lib.impl.pdfbox2.PDFBOXObject; import at.gv.egiz.pdfas.lib.impl.pdfbox2.positioning.Positioning; @@ -107,231 +104,123 @@ import at.knowcenter.wag.egov.egiz.pdf.PositioningInstruction; import at.knowcenter.wag.egov.egiz.pdf.TablePos; import at.knowcenter.wag.egov.egiz.table.Table; import iaik.x509.X509Certificate; +import lombok.extern.slf4j.Slf4j; +@Slf4j public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { - private static final Logger logger = LoggerFactory.getLogger(PADESPDFBOXSigner.class); - private boolean isAdobeSigForm = false; + @Override public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature, PDFASSignatureInterface genericSigner) throws PdfAsException { - PDFAsVisualSignatureProperties properties = null; - List<SignaturePlaceholderData> placeholders; - List<SignaturePlaceholderData> availablePlaceholders; - SignaturePlaceholderData signaturePlaceholderData = null; - - String placeholder_id = ""; - - if (PlaceholderWebConfiguration.getValue(PLACEHOLDER_WEB_ID) != null && !PlaceholderWebConfiguration - .getValue(PLACEHOLDER_WEB_ID).equalsIgnoreCase("")) { - placeholder_id = PlaceholderWebConfiguration.getValue(PLACEHOLDER_WEB_ID); - } - + + boolean isAdobeSigForm = false; + if (!(genericPdfObject instanceof PDFBOXObject)) { - // tODO: - throw new PdfAsException(); + throw new PdfAsException("PDF to signObject is of wrong type: " + genericPdfObject.getClass().getName()); + } - final PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject; - if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) { - // tODO: - throw new PdfAsException(); + throw new PdfAsException("PDF signerObject is of wrong type:" + genericSigner.getClass().getName()); + } - + + final PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject; final PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner; - String pdfaVersion = null; - PDDocument doc = null; SignatureOptions options = new SignatureOptions(); try { - doc = pdfObject.getDocument(); - // if signature already exists dont create new page - final List<PDSignatureField> pdSignatureFieldList = doc.getSignatureFields(); - PDSignature signature; + // sign a PDF with an existing empty signature, as created by the // CreateEmptySignatureForm example. - String sigFieldName = pdfObject.getStatus().getSettings().getValue(SIGNATURE_FIELD_NAME); - signature = findExistingSignature(doc, sigFieldName); + PDSignature signature = findExistingSignature(doc, getSignatureFieldNameConfig(pdfObject)); if (signature == null) { // create signature dictionary signature = new PDSignature(); + } else { isAdobeSigForm = true; + } + // set basic signature parameters signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter())); -// SignaturePlaceholderData signaturePlaceholderDataInit = - placeholders = PlaceholderFilter.checkPlaceholderSignatureLocationList(pdfObject.getStatus(), - pdfObject.getStatus().getSettings(), placeholder_id); - -// placeholders = SignaturePlaceholderExtractor.getPlaceholders(); - availablePlaceholders = listAvailablePlaceholders(placeholders, existingSignatureLocations(doc)); - - if (placeholder_id.equalsIgnoreCase("")) { - if (checkAvailablePlaceholders(placeholders, existingSignatureLocations(doc)) != null) { - placeholder_id = checkAvailablePlaceholders(placeholders, existingSignatureLocations(doc)).getId(); - } - } - - if (availablePlaceholders != null) { - signaturePlaceholderData = PlaceholderFilter - .checkPlaceholderSignatureLocation(pdfObject.getStatus(), pdfObject.getStatus().getSettings(), - placeholder_id); - } - - TablePos tablePos = null; - - if (signaturePlaceholderData != null) { - signature.setLocation(signaturePlaceholderData.getPlaceholderName()); - } - - if (signaturePlaceholderData != null) { - // Placeholder found! - placeholders.clear(); - logger.info("Placeholder data found."); - if (signaturePlaceholderData.getProfile() != null) { - logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile()); - requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile()); - } - - tablePos = signaturePlaceholderData.getTablePos(); - if (tablePos != null) { - - final SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() - .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); - - final float minWidth = signatureProfileConfiguration.getMinWidth(); - - if (minWidth > 0) { - if (tablePos.getWidth() < minWidth) { - tablePos.width = minWidth; - logger.debug("Correcting placeholder with to minimum width {}", minWidth); - } + signature.setSignDate(Calendar.getInstance()); + log.debug("Signing @ " + signature.getSignDate().getTime().toString()); + + // extract next QR-code placeholder, if exists + SignaturePlaceholderData nextPlaceholderData = PlaceholderFilter.checkPlaceholderSignatureLocation( + pdfObject.getStatus(), pdfObject.getStatus().getSettings(), + pdfObject.getStatus().getSignParamter().getPlaceHolderId()); + + if (nextPlaceholderData != null) { + log.info("Placeholder data found."); + signature.setLocation(nextPlaceholderData.getPlaceholderName()); + + if (nextPlaceholderData.getProfile() != null) { + if (pdfObject.getStatus().getSettings().isValue(IConfigurationConstants.PLACEHOLDER_PROFILE_OVERWRITE, true)) { + log.debug("Placeholder Profile set to: {}", nextPlaceholderData.getProfile()); + requestedSignature.setSignatureProfileID(nextPlaceholderData.getProfile()); + + } else { + log.debug("Placeholder profile over-write is disabled. Using profile from request ... "); + } - logger.debug("Placeholder Position set to: " + tablePos.toString()); - } - } - final SignatureProfileSettings signatureProfileSettings = TableFactory.createProfile( - requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings()); - - // Check if input document is PDF-A conform - if (signatureProfileSettings.isPDFA()) { - final DataSource origDoc = pdfObject.getOriginalDocument(); - final InputStream stream = origDoc.getInputStream(); - // Run PreflightParser for checking conformity// - // runPDFAPreflight(origDoc); + } } + + + final SignatureProfileSettings signatureProfileSettings = + TableFactory.createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings()); + + // set signature name final ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus()); - - final String signerName = resolver.resolve("SIG_SUBJECT", signatureProfileSettings.getValue( - "SIG_SUBJECT"), - signatureProfileSettings); - + final String signerName = resolver.resolve("SIG_SUBJECT", + signatureProfileSettings.getValue("SIG_SUBJECT"), signatureProfileSettings); signature.setName(signerName); - signature.setSignDate(Calendar.getInstance()); - String signerReason = signatureProfileSettings.getSigningReason(); - - if (signerReason == null) { - signerReason = "PAdES Signature"; - } + // set signature reason + String signerReason = signatureProfileSettings.getSigningReason() != null + ? signatureProfileSettings.getSigningReason() : "PAdES Signature"; signature.setReason(signerReason); - logger.debug("Signing reason: " + signerReason); - - logger.debug("Signing @ " + signer.getSigningDate().getTime().toString()); - // the signing date, needed for valid signature - // signature.setSignDate(signer.getSigningDate()); + log.debug("Signing reason: " + signerReason); signer.setPDSignature(signature); - int signatureSize = 0x1000; - try { - final String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE); - if (reservedSignatureSizeString != null) { - signatureSize = Integer.parseInt(reservedSignatureSizeString); - } - logger.debug("Reserving {} bytes for signature", signatureSize); - } catch (final NumberFormatException e) { - logger.warn("Invalid configuration value: {} should be a number using 0x1000", SIG_RESERVED_SIZE); - } - options.setPreferredSignatureSize(signatureSize); - + if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) { - pdfaVersion = getPDFAVersion(doc); - signatureProfileSettings.setPDFAVersion(pdfaVersion); + signatureProfileSettings.setPDFAVersion(getPDFAVersion(doc)); + } - // Is visible Signature - if (requestedSignature.isVisual()) { - logger.info("Creating visual siganture block"); - - final SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() - .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); - - if (tablePos == null) { - // ================================================================ - // PositioningStage (visual) -> find position or use - // fixed - // position - - final String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition(); - - TablePos signaturePos = null; - - final String signaturePosString = signatureProfileConfiguration.getDefaultPositioning(); - - if (signaturePosString != null) { - logger.debug("using signature Positioning: " + signaturePos); - signaturePos = new TablePos(signaturePosString); - } - - logger.debug("using Positioning: " + posString); - - if (posString != null) { - // Merge Signature Position - tablePos = new TablePos(posString, signaturePos); - } else { - // Fallback to signature Position! - tablePos = signaturePos; - } - - if (tablePos == null) { - // Last Fallback default position - tablePos = new TablePos(); - } - } - - // Legacy Modes not supported with pdfbox2 anymore -// boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning(); -// boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning(); - - // create Table describtion + // prepare basic signature options + options.setPreferredSignatureSize(calculateBlankAreaForSignature(signatureProfileSettings)); + + PDFAsVisualSignatureProperties properties = null; + if (requestedSignature.isVisual()) { + log.info("Creating visual siganture block"); + + final SignatureProfileConfiguration signatureProfileConfiguration = + pdfObject.getStatus().getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); + final TablePos tablePos = prepareTablePosition(nextPlaceholderData, signatureProfileConfiguration, + pdfObject.getStatus().getSignParamter().getSignaturePosition()); final Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(), requestedSignature); final IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings()); - final IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main); - /* - * PDDocument originalDocument = PDDocument .load(new - * ByteArrayInputStream(pdfObject.getStatus() - * .getPdfObject().getOriginalDocument())); - */ - final PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos, - "", - doc, visualObject, pdfObject.getStatus().getSettings()); - - logger.debug("Positioning: {}", positioningInstruction.toString()); + doc, visualObject, pdfObject.getStatus().getSettings(), signatureProfileSettings); + log.debug("Positioning: {}", positioningInstruction.toString()); if (!isAdobeSigForm) { if (positioningInstruction.isMakeNewPage()) { @@ -347,11 +236,11 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { // handle rotated page final int targetPageNumber = positioningInstruction.getPage(); - logger.debug("Target Page: " + targetPageNumber); + log.debug("Target Page: " + targetPageNumber); final PDPage targetPage = doc.getPages().get(targetPageNumber - 1); final int rot = targetPage.getRotation(); - logger.debug("Page rotation: " + rot); - logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation()); + log.debug("Page rotation: " + rot); + log.debug("resulting Sign rotation: " + positioningInstruction.getRotation()); final SignaturePositionImpl position = new SignaturePositionImpl(); position.setX(positioningInstruction.getX()); @@ -361,44 +250,11 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { position.setWidth(visualObject.getWidth()); requestedSignature.setSignaturePosition(position); } - + properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings, false); - properties.buildSignature(); - /* - * ByteArrayOutputStream sigbos = new ByteArrayOutputStream(); - * sigbos.write(StreamUtils.inputStreamToByteArray (properties - * .getVisibleSignature())); sigbos.close(); - */ - - /* - * if (signaturePlaceholderData != null) { - * - * InputStream fis = - * PADESPDFBOXSigner.class.getResourceAsStream("/placeholder/empty.jpg"); - * PDImageXObject img = JPEGFactory.createFromStream(doc, fis); - * - * img.getCOSObject().setNeedToBeUpdated(true); // PDDocumentCatalog root = - * doc.getDocumentCatalog(); // PDPageNode rootPages = root.getPages(); // - * List<PDPage> kids = new ArrayList<PDPage>(); // rootPages.getAllKids(kids); - * int pageNumber = positioningInstruction.getPage(); PDPage page = - * doc.getPages().get(pageNumber - 1); - * - * logger.info("Placeholder name: " + - * signaturePlaceholderData.getPlaceholderName()); COSDictionary - * xobjectsDictionary = (COSDictionary) page.getResources().getCOSObject() - * .getDictionaryObject(COSName.XOBJECT); - * - * - * xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), - * img); xobjectsDictionary.setNeedToBeUpdated(true); - * page.getResources().getCOSObject().setNeedToBeUpdated(true); - * logger.info("Placeholder name: " + - * signaturePlaceholderData.getPlaceholderName()); } - */ - if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) { final PDDocumentCatalog root = doc.getDocumentCatalog(); @@ -418,39 +274,30 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { root.setOutputIntents(oi); root.getCOSObject().setNeedToBeUpdated(true); - logger.info("added Output Intent"); + log.info("added Output Intent"); } catch (final Throwable e) { e.printStackTrace(); throw new PdfAsException("Failed to add Output Intent", e); + } finally { IOUtils.closeQuietly(colorProfile); + } } + options.setPage(positioningInstruction.getPage() - 1); options.setVisualSignature(properties.getVisibleSignature()); + } doc.addSignature(signature, signer, options); - - if (sigFieldName == null) { - sigFieldName = "PDF-AS Signatur"; - } - final int count = PdfBoxUtils.countSignatures(doc, sigFieldName); - - sigFieldName = sigFieldName + count; - - final PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm(); - - // PDStructureTreeRoot pdstRoot = - // doc.getDocumentCatalog().getStructureTreeRoot(); - // COSDictionary dic = - // doc.getDocumentCatalog().getCOSDictionary(); - // PDStructureElement el = new PDStructureElement("Widget", - // pdstRoot); - + + String sigFieldName = buildNextSignatureFieldName(doc, pdfObject); + // this is not used for Adobe signature fields if (!isAdobeSigForm) { PDSignatureField signatureField = null; + final PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm(); if (acroFormm != null) { @SuppressWarnings("unchecked") final List<PDField> fields = acroFormm.getFields(); @@ -473,7 +320,7 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { } } } else { - logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]"); + log.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]"); } if (signatureField != null) { @@ -485,7 +332,8 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { signatureField.setAlternateFieldName(sigFieldName); } } else { - logger.warn("Failed to name Signature Field! [Cannot find acroForm!]"); + log.warn("Failed to name Signature Field! [Cannot find acroForm!]"); + } } @@ -493,194 +341,284 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { final PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm(); if (acroForm != null) { signatureField = (PDSignatureField) acroForm.getField(sigFieldName); + } - // PDF-UA - logger.info("Adding pdf/ua content."); - try { - final PDDocumentCatalog root = doc.getDocumentCatalog(); - final PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot(); - if (structureTreeRoot != null) { - logger.info("Tree Root: {}", structureTreeRoot.toString()); - final List<Object> kids = structureTreeRoot.getKids(); - - if (kids == null) { - logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document"); - } - PDStructureElement docElement = null; - for (final Object k : kids) { - if (k instanceof PDStructureElement) { - docElement = (PDStructureElement) k; - break; + injectPdfUaContent(doc, signatureField, sigFieldName, signatureProfileSettings); + + performTechnicalSignature(doc, pdfObject, signatureProfileSettings); + - } + log.debug("Signature done!"); + + } catch (final IOException e) { + log.warn(MessageResolver.resolveMessage("error.pdf.sig.01"), e); + throw new PdfAsException("error.pdf.sig.01", e); + + } catch (PDFASError e2) { + log.warn(e2.getInfo()); + throw new PdfAsException("error.pdf.sig.01", e2); + + } finally { + if (options != null) { + if (options.getVisualSignature() != null) { + try { + options.getVisualSignature().close(); + options.close(); + } catch (IOException e) { + log.debug("Failed to close VisualSignature!", e); } + } + } + + if (doc != null) { + try { + doc.close(); + // SignaturePlaceholderExtractor.getPlaceholders().clear(); + } catch (final IOException e) { + log.debug("Failed to close COS Doc!", e); + // Ignore + } + } + } + } - final PDStructureElement sigBlock = new PDStructureElement("Form", docElement); + private void performTechnicalSignature(PDDocument doc, PDFBOXObject pdfObject, + SignatureProfileSettings signatureProfileSettings) throws PdfAsException { + try { + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + synchronized (doc) { + doc.saveIncremental(bos); + final byte[] outputDocument = bos.toByteArray(); + pdfObject.setSignedDocument(outputDocument); + } + /* Check if resulting pdf is PDF-A conform */ + if (signatureProfileSettings.isPDFA()) { + runPDFAPreflight(new ByteArrayDataSource(pdfObject.getSignedDocument())); + } - // create object dictionary and add as child element - final COSDictionary objectDic = new COSDictionary(); - objectDic.setName("Type", "OBJR"); + } catch (final IOException e1) { + log.error("Can not save incremental update", e1); - objectDic.setItem("Pg", signatureField.getWidget().getPage()); - objectDic.setItem("Obj", signatureField.getWidget()); + } + + System.gc(); + + } - final List<Object> l = new ArrayList<>(); - l.add(objectDic); - sigBlock.setKids(l); - sigBlock.setPage(signatureField.getWidget().getPage()); + private void injectPdfUaContent(PDDocument doc, PDSignatureField signatureField, String sigFieldName, + SignatureProfileSettings signatureProfileSettings) throws PdfAsException { + try { + log.info("Adding pdf/ua content .... "); + final PDDocumentCatalog root = doc.getDocumentCatalog(); + final PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot(); + if (structureTreeRoot != null) { + log.info("Tree Root: {}", structureTreeRoot.toString()); + final List<Object> kids = structureTreeRoot.getKids(); + + if (kids == null) { + log.info("No kid-elements in structure tree Root, maybe not PDF/UA document"); + } - sigBlock.setTitle("Signature Table"); - sigBlock.setParent(docElement); - docElement.appendKid(sigBlock); + PDStructureElement docElement = null; + for (final Object k : kids) { + if (k instanceof PDStructureElement) { + docElement = (PDStructureElement) k; + break; - // Create and add Attribute dictionary to mitigate PAC - // warning - final COSDictionary sigBlockDic = sigBlock.getCOSObject(); - final COSDictionary sub = new COSDictionary(); + } + } - sub.setName("O", "Layout"); - sub.setName("Placement", "Block"); - sigBlockDic.setItem(COSName.A, sub); - sigBlockDic.setNeedToBeUpdated(true); + final PDStructureElement sigBlock = new PDStructureElement("Form", docElement); - // Modify number tree - PDNumberTreeNode ntn = structureTreeRoot.getParentTree(); - if (ntn == null) { - ntn = new PDNumberTreeNode(objectDic, null); - logger.info("No number-tree-node found!"); - } + // create object dictionary and add as child element + final COSDictionary objectDic = new COSDictionary(); + objectDic.setName("Type", "OBJR"); - final COSArray ntnKids = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.KIDS); - final COSArray ntnNumbers = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.NUMS); + objectDic.setItem("Pg", signatureField.getWidget().getPage()); + objectDic.setItem("Obj", signatureField.getWidget()); - final int parentTreeNextKey = getParentTreeNextKey(structureTreeRoot); + final List<Object> l = new ArrayList<>(); + l.add(objectDic); + sigBlock.setKids(l); + sigBlock.setPage(signatureField.getWidget().getPage()); - if (ntnNumbers == null && ntnKids != null) {// no number array, so continue with the kids array - // create dictionary with limits and nums array - final COSDictionary pTreeEntry = new COSDictionary(); - final COSArray limitsArray = new COSArray(); - // limits for exact one entry - limitsArray.add(COSInteger.get(parentTreeNextKey)); - limitsArray.add(COSInteger.get(parentTreeNextKey)); + sigBlock.setTitle("Signature Table"); + sigBlock.setParent(docElement); + docElement.appendKid(sigBlock); - final COSArray numsArray = new COSArray(); - numsArray.add(COSInteger.get(parentTreeNextKey)); - numsArray.add(sigBlock); + // Create and add Attribute dictionary to mitigate PAC + // warning + final COSDictionary sigBlockDic = sigBlock.getCOSObject(); + final COSDictionary sub = new COSDictionary(); - pTreeEntry.setItem(COSName.NUMS, numsArray); - pTreeEntry.setItem(COSName.LIMITS, limitsArray); + sub.setName("O", "Layout"); + sub.setName("Placement", "Block"); + sigBlockDic.setItem(COSName.A, sub); + sigBlockDic.setNeedToBeUpdated(true); - final PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry, PDNumberTreeNode.class); + // Modify number tree + PDNumberTreeNode ntn = structureTreeRoot.getParentTree(); + if (ntn == null) { + ntn = new PDNumberTreeNode(objectDic, null); + log.info("No number-tree-node found!"); + } - ntnKids.add(newKidsElement); - ntnKids.setNeedToBeUpdated(true); + final COSArray ntnKids = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.KIDS); + final COSArray ntnNumbers = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.NUMS); - } else if (ntnNumbers != null && ntnKids == null) { + final int parentTreeNextKey = getParentTreeNextKey(structureTreeRoot); - final int arrindex = ntnNumbers.size(); + if (ntnNumbers == null && ntnKids != null) {// no number array, so continue with the kids array + // create dictionary with limits and nums array + final COSDictionary pTreeEntry = new COSDictionary(); + final COSArray limitsArray = new COSArray(); + // limits for exact one entry + limitsArray.add(COSInteger.get(parentTreeNextKey)); + limitsArray.add(COSInteger.get(parentTreeNextKey)); - ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey)); - ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject()); + final COSArray numsArray = new COSArray(); + numsArray.add(COSInteger.get(parentTreeNextKey)); + numsArray.add(sigBlock); - ntnNumbers.setNeedToBeUpdated(true); + pTreeEntry.setItem(COSName.NUMS, numsArray); + pTreeEntry.setItem(COSName.LIMITS, limitsArray); - structureTreeRoot.setParentTree(ntn); + final PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry, PDNumberTreeNode.class); - } else if (ntnNumbers == null && ntnKids == null) { - // document is not pdfua conform before signature creation - throw new PdfAsException("error.pdf.sig.pdfua.1"); - } else { - // this is not allowed - throw new PdfAsException("error.pdf.sig.pdfua.1"); - } + ntnKids.add(newKidsElement); + ntnKids.setNeedToBeUpdated(true); - // set StructureParent for signature field annotation - signatureField.getWidget().setStructParent(parentTreeNextKey); + } else if (ntnNumbers != null && ntnKids == null) { - // Increase the next Key value in the structure tree root - structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1); + final int arrindex = ntnNumbers.size(); - // add the Tabs /S Element for Tabbing through annots - final PDPage p = signatureField.getWidget().getPage(); - p.getCOSObject().setName("Tabs", "S"); - p.getCOSObject().setNeedToBeUpdated(true); + ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey)); + ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject()); - // check alternative signature field name - if (signatureField != null) { - if (signatureField.getAlternateFieldName().equals("")) { - signatureField.setAlternateFieldName(sigFieldName); - } - } + ntnNumbers.setNeedToBeUpdated(true); - ntn.getCOSObject().setNeedToBeUpdated(true); - sigBlock.getCOSObject().setNeedToBeUpdated(true); - structureTreeRoot.getCOSObject().setNeedToBeUpdated(true); - objectDic.setNeedToBeUpdated(true); - docElement.getCOSObject().setNeedToBeUpdated(true); - } - } catch (final Throwable e) { - if (signatureProfileSettings.isPDFUA() == true) { - logger.error("Could not create PDF-UA conform document!"); - throw new PdfAsException("error.pdf.sig.pdfua.1", e); + structureTreeRoot.setParentTree(ntn); + + } else if (ntnNumbers == null && ntnKids == null) { + // document is not pdfua conform before signature creation + throw new PdfAsException("error.pdf.sig.pdfua.1"); } else { - logger.info("Could not create PDF-UA conform signature"); + // this is not allowed + throw new PdfAsException("error.pdf.sig.pdfua.1"); } - } - try { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - synchronized (doc) { - doc.saveIncremental(bos); - final byte[] outputDocument = bos.toByteArray(); - pdfObject.setSignedDocument(outputDocument); - } - /* Check if resulting pdf is PDF-A conform */ - if (signatureProfileSettings.isPDFA()) { - runPDFAPreflight(new ByteArrayDataSource(pdfObject.getSignedDocument())); + // set StructureParent for signature field annotation + signatureField.getWidget().setStructParent(parentTreeNextKey); + + // Increase the next Key value in the structure tree root + structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1); + + // add the Tabs /S Element for Tabbing through annots + final PDPage p = signatureField.getWidget().getPage(); + p.getCOSObject().setName("Tabs", "S"); + p.getCOSObject().setNeedToBeUpdated(true); + + // check alternative signature field name + if (signatureField != null) { + if (signatureField.getAlternateFieldName().equals("")) { + signatureField.setAlternateFieldName(sigFieldName); + } } - } catch (final IOException e1) { - logger.error("Can not save incremental update", e1); + ntn.getCOSObject().setNeedToBeUpdated(true); + sigBlock.getCOSObject().setNeedToBeUpdated(true); + structureTreeRoot.getCOSObject().setNeedToBeUpdated(true); + objectDic.setNeedToBeUpdated(true); + docElement.getCOSObject().setNeedToBeUpdated(true); + } + } catch (final Throwable e) { + if (signatureProfileSettings.isPDFUA()) { + log.error("Could not create PDF-UA conform document!"); + throw new PdfAsException("error.pdf.sig.pdfua.1", e); + + } else { + log.info("Could not create PDF-UA conform signature"); + } + } + + } + private String buildNextSignatureFieldName(PDDocument doc, PDFBOXObject pdfObject) { + String sigFieldName = getSignatureFieldNameConfig(pdfObject); + if (sigFieldName == null) { + sigFieldName = "PDF-AS Signatur"; + + } + return sigFieldName + PdfBoxUtils.countSignatures(doc, sigFieldName); + + } + + private int calculateBlankAreaForSignature(SignatureProfileSettings signatureProfileSettings) { + int signatureSize = 0x1000; + try { + final String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE); + if (reservedSignatureSizeString != null) { + signatureSize = Integer.parseInt(reservedSignatureSizeString); } + log.debug("Reserving {} bytes for signature", signatureSize); - System.gc(); - logger.debug("Signature done!"); + } catch (final NumberFormatException e) { + log.warn("Invalid configuration value: {} should be a number using 0x1000", SIG_RESERVED_SIZE); - } catch (final IOException e) { - logger.warn(MessageResolver.resolveMessage("error.pdf.sig.01"), e); - throw new PdfAsException("error.pdf.sig.01", e); + } - } catch (PDFASError e2) { - logger.warn(e2.getInfo()); - throw new PdfAsException("error.pdf.sig.01", e2); - - } finally { - if (options != null) { - if (options.getVisualSignature() != null) { - try { - options.getVisualSignature().close(); - options.close(); - } catch (IOException e) { - logger.debug("Failed to close VisualSignature!", e); - } + return signatureSize; + } + + private TablePos prepareTablePosition(SignaturePlaceholderData nextPlaceholderData, + SignatureProfileConfiguration signatureProfileConfiguration, String profilePosParam) throws PdfAsException { + + + if (nextPlaceholderData != null && nextPlaceholderData.getTablePos() != null) { + final float minWidth = signatureProfileConfiguration.getMinWidth(); + TablePos tablePos = nextPlaceholderData.getTablePos(); + if (minWidth > 0) { + if (tablePos.getWidth() < minWidth) { + tablePos.width = minWidth; + log.debug("Correcting placeholder with to minimum width {}", minWidth); } } + log.debug("Placeholder Position set to: " + tablePos.toString()); + return tablePos; - if (doc != null) { - try { - doc.close(); - // SignaturePlaceholderExtractor.getPlaceholders().clear(); - } catch (final IOException e) { - logger.debug("Failed to close COS Doc!", e); - // Ignore - } + } else { + TablePos signaturePos = null; + final String signaturePosString = signatureProfileConfiguration.getDefaultPositioning(); + + if (signaturePosString != null) { + log.debug("using signature Positioning: " + signaturePosString); + signaturePos = new TablePos(signaturePosString); + + } + + log.debug("using Positioning: " + profilePosParam); + + if (profilePosParam != null) { + // Merge Signature Position + return new TablePos(profilePosParam, signaturePos); + + } else if (signaturePos != null){ + // Fallback to signature Position! + return signaturePos; + + } else { + return new TablePos(); + } } } + private String getSignatureFieldNameConfig(PDFBOXObject pdfObject) { + return pdfObject.getStatus().getSettings().getValue(SIGNATURE_FIELD_NAME); + } + private int getParentTreeNextKey(PDStructureTreeRoot structureTreeRoot) throws IOException { int nextKey = structureTreeRoot.getParentTreeNextKey(); if (nextKey < 0) { @@ -717,31 +655,31 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { document.close(); result = document.getResult(); - logger.info("PDF-A Validation Result: " + result.isValid()); + log.info("PDF-A Validation Result: " + result.isValid()); if (result.getErrorsList().size() > 0) { - logger.error("The following validation errors occured for PDF-A validation"); + log.error("The following validation errors occured for PDF-A validation"); } for (final ValidationResult.ValidationError ve : result.getErrorsList()) { - logger.error("\t" + ve.getErrorCode() + ": " + ve.getDetails()); + log.error("\t" + ve.getErrorCode() + ": " + ve.getDetails()); } if (!result.isValid()) { - logger.info("The file is not a valid PDF-A document"); + log.info("The file is not a valid PDF-A document"); } } catch (final SyntaxValidationException e) { - logger.error("The file is syntactically invalid.", e); + log.error("The file is syntactically invalid.", e); throw new PdfAsException("Resulting PDF Document is syntactically invalid."); } catch (final ValidationException e) { - logger.error("The file is not a valid PDF-A document.", e); + log.error("The file is not a valid PDF-A document.", e); } catch (final IOException e) { - logger.error("An IOException (" + e.getMessage() + log.error("An IOException (" + e.getMessage() + ") occurred, while validating the PDF-A conformance", e); throw new PdfAsException("Failed validating PDF Document IOException."); } catch (final RuntimeException e) { - logger.debug("An RuntimeException (" + e.getMessage() + log.debug("An RuntimeException (" + e.getMessage() + ") occurred, while validating the PDF-A conformance", e); throw new PdfAsException("Failed validating PDF Document RuntimeException."); } finally { @@ -819,11 +757,11 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { final String signaturePosString = signatureProfileConfiguration.getDefaultPositioning(); PositioningInstruction positioningInstruction; if (signaturePosString != null) { - positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "", - origDoc, visualObject, pdfObject.getStatus().getSettings()); + positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), + origDoc, visualObject, pdfObject.getStatus().getSettings(), signatureProfileSettings); } else { - positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc, - visualObject, pdfObject.getStatus().getSettings()); + positioningInstruction = Positioning.determineTablePositioning(new TablePos(), origDoc, + visualObject, pdfObject.getStatus().getSettings(), signatureProfileSettings); } origDoc.close(); @@ -877,10 +815,10 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { return cutOut; } catch (final PdfAsException e) { - logger.warn("PDF-AS Exception", e); + log.warn("PDF-AS Exception", e); throw ErrorExtractor.searchPdfAsError(e, status); } catch (final Throwable e) { - logger.warn("Unexpected Throwable Exception", e); + log.warn("Unexpected Throwable Exception", e); throw ErrorExtractor.searchPdfAsError(e, status); } } @@ -898,7 +836,7 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { if (pdfaIdentificationSchema != null) { final Integer pdfaversion = pdfaIdentificationSchema.getPart(); final String conformance = pdfaIdentificationSchema.getConformance(); - logger.info("Detected PDF/A Version: {} - {}", pdfaversion, conformance); + log.info("Detected PDF/A Version: {} - {}", pdfaversion, conformance); if (pdfaversion != null) { return String.valueOf(pdfaversion); @@ -907,7 +845,7 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { } } } catch (final Throwable e) { - logger.warn("Failed to determine PDF/A Version!", e); + log.warn("Failed to determine PDF/A Version!", e); } return null; } @@ -931,75 +869,9 @@ public class PADESPDFBOXSigner implements IPdfSigner, IConfigurationConstants { } } return signature; + } - - private List<String> existingSignatureLocations(PDDocument doc) { - final List<String> existingLocations = new ArrayList<>(); - try { - final List<PDSignature> pdSignatureList = doc.getSignatureDictionaries(); - if (pdSignatureList.size() != 0) { - for (final PDSignature sig : pdSignatureList) { - existingLocations.add(sig.getLocation()); - } - } - } catch (final IOException e) { - e.printStackTrace(); - } - return existingLocations; - } - - // find first placeholder_id - public SignaturePlaceholderData checkAvailablePlaceholders(List<SignaturePlaceholderData> placeholders, - List<String> existingPlaceholders) { - SignaturePlaceholderData result = null; - - if (placeholders != null) { - for (int i = 0; i < placeholders.size(); ++i) { - // take smallest id - if (!existingPlaceholders.contains(placeholders.get(i).getPlaceholderName())) { - final SignaturePlaceholderData spd = placeholders.get(i); - if (spd.getId() != null) { - if (result == null) { - result = spd; - } else { - try { - final int currentID = Integer.parseInt(result.getId()); - final int testID = Integer.parseInt(spd.getId()); - if (testID < currentID) { - result = spd; - } - } catch (final Exception e) { - // fallback to string compare - final String currentID = result.getId(); - final String testID = spd.getId(); - if (testID.compareToIgnoreCase(currentID) < 0) { - result = spd; - } - } - } - } - } - } - } - return result; - } - - // find first placeholder_id - public List<SignaturePlaceholderData> listAvailablePlaceholders(List<SignaturePlaceholderData> placeholders, - List<String> existingPlaceholders) { - final List<SignaturePlaceholderData> result = new ArrayList<>(); - - if (placeholders != null) { - for (int i = 0; i < placeholders.size(); ++i) { - // take smallest id - if (!existingPlaceholders.contains(placeholders.get(i).getPlaceholderName())) { - result.add(placeholders.get(i)); - } - } - } - return result; - } - + static Map<Integer, COSObjectable> getNumberTreeAsMap(PDNumberTreeNode tree) throws IOException { Map<Integer, COSObjectable> numbers = tree.getNumbers(); |