Example usage for com.itextpdf.text.pdf PdfSignatureAppearance setSignatureGraphic

List of usage examples for com.itextpdf.text.pdf PdfSignatureAppearance setSignatureGraphic

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfSignatureAppearance setSignatureGraphic.

Prototype

public void setSignatureGraphic(Image signatureGraphic) 

Source Link

Document

Sets the Image object to render when Render is set to RenderingMode.GRAPHIC or RenderingMode.GRAPHIC_AND_DESCRIPTION.

Usage

From source file:com.isa.firma.FirmaPDFController.java

public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException {

    try {//from  w w w .  j  a  va 2s  .c  om
        System.out.println("Firma Controller::firmar");

        PdfReader reader = new PdfReader(pdfbase64);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        System.out.println("Pre definir apariencia...");
        if (infoFirma.isApariencia()) {
            System.out.println("Insertando apriencia en documento...");
            appearance.setSignatureGraphic(Image.getInstance(new URL(infoFirma.getRutaImagen())));
            appearance.setRenderingMode(Utiles.getModoApariencia());

            int numeroPagFirma = infoFirma.getHoja() == -1 ? reader.getNumberOfPages() : infoFirma.getHoja();
            int cantidadFirmaActuales = reader.getAcroFields().getSignatureNames().size();
            int[] coords = infoFirma.calcularCorrdenadasFirma(cantidadFirmaActuales, infoFirma.getAncho(),
                    infoFirma.getLargo());

            //llx, lly, urx, ury
            String v = Utiles.encodingString(infoFirma.getFirmante());
            System.out.println("Post encoding: " + v);
            appearance.setLayer2Text(v);
            //appearance.setLayer2Text(  infoFirma.getFirmante() );
            appearance.setVisibleSignature(new Rectangle(coords[0], coords[1], coords[2], coords[3]),
                    numeroPagFirma, "Id: " + IdGenerator.generate());
        }

        ExternalSignature es = new PrivateKeySignature(infoFirma.getPk(), "SHA-256",
                infoFirma.getProvidername());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, es, infoFirma.getChainCert(), null, null, null, 0,
                CryptoStandard.CMS);

        System.out.println("PDF Firmado correctamente.");

        return os;

    } catch (IOException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (DocumentException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (KeyStoreException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    }
}

From source file:com.isa.firma.pades.FirmaPDFController.java

public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException {

    try {//from   ww  w  . j  av  a2s  .c o  m
        PdfReader reader = new PdfReader(pdfbase64);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();

        if (infoFirma.isApariencia()) {
            System.out.println("Definiendo apariencia...");
            appearance.setRenderingMode(Utiles.getModoApariencia());

            if (!Utiles.getModoApariencia().equals(PdfSignatureAppearance.RenderingMode.DESCRIPTION)) {
                appearance.setSignatureGraphic(Image.getInstance(new URL(infoFirma.getRutaImagen())));
            }

            int numeroPagFirma = infoFirma.getHoja() == -1 ? reader.getNumberOfPages() : infoFirma.getHoja();
            int cantidadFirmaActuales = reader.getAcroFields().getSignatureNames().size();
            int[] coords = infoFirma.calcularCorrdenadasFirma(cantidadFirmaActuales, infoFirma.getAncho(),
                    infoFirma.getLargo());

            System.out.println("firmante: " + infoFirma.getFirmante());
            System.out.println("serie: " + infoFirma.getNroSerie());
            //llx, lly, urx, ury
            appearance.setLayer2Text(infoFirma.generarTextoEnFirma());
            appearance.setVisibleSignature(new Rectangle(coords[0], coords[1], coords[2], coords[3]),
                    numeroPagFirma, "Id: " + IdGenerator.generate());
        }

        ExternalSignature es = new PrivateKeySignature(infoFirma.getPk(), "SHA-256",
                infoFirma.getProvidername());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, es, infoFirma.getChainCert(), null, null, null, 0,
                CryptoStandard.CMS);

        System.out.println("PDF Firmado correctamente.");

        return os;

    } catch (IOException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (DocumentException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (KeyStoreException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    }
}

From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java

License:Open Source License

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef,
 * org.alfresco.service.cmr.repository.NodeRef)
 *//*w w w  .j ava  2s.  c  o m*/
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {

    if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == false) {
        // node doesn't exist - can't do anything
        return;
    }

    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON);
    Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE);
    Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC);

    boolean useSignatureField = false;
    String user = AuthenticationUtil.getRunAsUser();
    String positionType = "predefined";
    String positionLoc = "center";
    JSONObject box;
    int page = -1;

    // parse out the position JSON
    JSONObject positionObj = null;

    try {
        positionObj = (JSONObject) parser.parse(position);
    } catch (ParseException e) {
        logger.error("Could not parse position JSON from Share");
        throw new AlfrescoRuntimeException("Could not parse position JSON from Share");
    }

    // get the page
    page = Integer.parseInt(String.valueOf(positionObj.get("page")));

    // get the positioning type
    positionType = String.valueOf(positionObj.get("type"));

    // get the position (field or predefined)
    positionLoc = String.valueOf(positionObj.get("position"));

    // get the box (if required)
    box = (JSONObject) positionObj.get("box");

    int width = 350;
    int height = 75;

    File tempDir = null;

    // current date, used for both signing the PDF and creating the
    // associated signature object
    Calendar now = Calendar.getInstance();

    try {
        // get the keystore, pk and cert chain
        SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user);
        KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword);
        PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = keystore.getCertificateChain(alias);

        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());
        OutputStream cos = serviceRegistry.getContentService()
                .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream();

        PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true);
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);

        // set reason for signature, location of signer, and date
        sap.setReason(reason);
        sap.setLocation(location);
        sap.setSignDate(now);

        // get the image for the signature
        BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height);
        // save the signature image back to the signatureProvider
        signatureProvider.saveSignatureImage(sigImage, signatureJson);

        if (visible) {
            //if this is a graphic sig, set the graphic here
            if (graphic) {
                sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
                sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE));
            } else {
                sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);
            }

            // either insert the sig at a defined field or at a defined position / drawn loc
            if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) {
                Rectangle pageRect = reader.getPageSizeWithRotation(page);
                sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null);
            } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) {
                Rectangle pageRect = reader.getPageSizeWithRotation(page);
                sap.setVisibleSignature(positionBlock(pageRect, box), page, null);
            } else {
                sap.setVisibleSignature(positionLoc);
                useSignatureField = true;
            }
        }

        // close the stamp, applying the changes to the PDF
        stamp.close();
        reader.close();
        cos.close();

        //delete the temp file
        file.delete();

        // apply the "signed" aspect
        serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED,
                new HashMap<QName, Serializable>());

        // create a "signature" node and associate it with the signed doc
        addSignatureNodeAssociation(actionedUponNodeRef, location, reason,
                useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc);

    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.opencps.pki.PdfSigner.java

License:Open Source License

/**
 * Compute digest hash/*from  w  w w  .  ja  v a2 s .  c  om*/
 */
protected byte[] computeDigest(float llx, float lly, float urx, float ury) throws SignatureException {
    byte digestHash[] = null;
    int contentEstimated = 8192;
    try {
        PdfReader reader = new PdfReader(getOriginFilePath());
        FileOutputStream os = new FileOutputStream(getTempFilePath());
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        signatureFieldName = appearance.getNewSigName();
        TSAClient tsaClient = null;
        appearance.setCertificate(getCertificate());
        String tsaUrl = CertificateUtil.getTSAURL(getCertificate());
        if (tsaUrl != null) {
            tsaClient = new TSAClientBouncyCastle(tsaUrl);
        }
        if (tsaClient != null) {
            LtvTimestamp.timestamp(appearance, tsaClient, signatureFieldName);
            contentEstimated += 4096;
        }

        appearance.setSignDate(signDate);
        CertificateInfo certInfo = new CertificateInfo(getCertificate());
        appearance.setLocation(certInfo.getOrganizationUnit());
        appearance.setReason("Document is signed by " + certInfo.getCommonName());
        appearance.setContact(certInfo.getCommonName());
        if (!isVisible) {
            appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureFieldName);
        } else {
            if (signatureImage != null) {
                appearance.setSignatureGraphic(signatureImage.getImage());
                appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
            } else {
                appearance.setLayer2Text(certInfo.getCommonName());
            }
            appearance.setVisibleSignature(new Rectangle(llx, lly, urx, ury), 1, signatureFieldName);
        }

        ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE,
                PdfName.ADBE_PKCS7_DETACHED);
        MakeSignature.signExternalContainer(appearance, external, contentEstimated);

        digestHash = DigestAlgorithms.digest(appearance.getRangeStream(),
                digest.getMessageDigest(getHashAlgorithm().toString()));

        reader.close();
        os.close();
    } catch (Exception e) {
        throw new SignatureException(e.getMessage(), e);
    }
    return digestHash;
}