Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

La firma no se visualiza #425

Open
dperdomo3 opened this issue Jan 7, 2025 · 2 comments
Open

La firma no se visualiza #425

dperdomo3 opened this issue Jan 7, 2025 · 2 comments

Comments

@dperdomo3
Copy link

Al firmar, la firma aparece válida en el menú de firmas, pero no se ve "dibujada" en el pdf.

Les comparto mi código:
"

<title>Firma de PDF con AutoFirma</title> <script type="text/javascript" src="js/autoscript.js"></script> <script type="text/javascript"> window.onload = function () { AutoScript.cargarAppAfirma(); AutoScript.setServlets( window.location.origin + "/afirma-signature-storage/StorageService", Captura de pantalla 2025-01-07 231305 window.location.origin + "/afirma-signature-retriever/RetrieveService" ); };
    function showLog(message) {
        document.getElementById('console').value += message + '\n';
    }

    function showSignResultCallback(signatureB64, certificateB64, extraData) {
        showLog("Firma OK");
        if (extraData) {
            var extras = JSON.parse(extraData);
            showLog("Fichero cargado: " + extras.filename);
        }
        document.getElementById('resultField').value = signatureB64;
    }

    function showErrorCallback(errorType, errorMessage) {
        showLog("Type: " + errorType + "\nMessage: " + errorMessage);
    }

    function doSign() {
const extraParams = {
    "signaturePositionOnPageLowerLeftX": 100,
    "signaturePositionOnPageLowerLeftY": 100,
    "signaturePositionOnPageUpperRightX": 400,
    "signaturePositionOnPageUpperRightY": 200,
    "signaturePage": 1,  // Página donde aparecerá la firma (comienza desde 1)
    "signingReason": "Aprobación",
};

AutoScript.sign(
    data,
    "SHA512withRSA",
    "PAdES",
    JSON.stringify(extraParams),
    showSignResultCallback,
    showErrorCallback
);

}

    function saveSignature() {
        var signature = document.getElementById('resultField').value;
        if (!signature) {
            alert("No hay firma para guardar.");
            return;
        }

        AutoScript.saveDataToFile(
            signature,
            "Guardar firma electrónica",
            "firma.pdf",
            null,
            null,
            function () { showLog("Guardado OK"); },
            showErrorCallback
        );
    }
</script>

Firma de PDF con AutoFirma

<pre id="response">trayendo pdf …</pre>

<script>
    var data = null;
    window.addEventListener("load", function () {
        fetch("http://localhost:8080/certificados/generar/2/bs64")
            .then(response => {

                if (!response.ok) {
                    throw new Error("Error en la solicitud: " + response.status);
                }
                console.log(response)
                return response.text();
            })
            .then(base64Data => {
                data = base64Data;
                var binary = atob(base64Data.replace(/\s/g, ''));
                var len = binary.length;
                var buffer = new ArrayBuffer(len);
                var view = new Uint8Array(buffer);
                for (var i = 0; i < len; i++) {
                    view[i] = binary.charCodeAt(i);
                }
                const pdfBlob = new Blob([view], { type: "application/pdf" });
                const fileURL = URL.createObjectURL(pdfBlob);
                const iframe = document.getElementById("pdfIframe");
                iframe.src = fileURL;
                iframe.onload = () => URL.revokeObjectURL(fileURL);
                document.getElementById("response").innerText = "PDF cargado correctamente.";
            })
            .catch(error => {
                console.error("Error:", error.message);
                const iframe = document.getElementById("pdfIframe");
                iframe.contentDocument.body.innerHTML = "Error al cargar el PDF: " + error.message;

            });
    });
</script>
<iframe id="pdfIframe" width="600" height="800"></iframe>

<br><br>
<button type="button" onclick="doSign()">Firmar PDF</button>

<br><br>
<textarea id="console" cols="100" rows="10" readonly></textarea>
<br>

<input type="hidden" id="resultField" value="">
<br>
<button type="button" onclick="saveSignature()">Guardar Documento Firmado</button>
"
@mkager05
Copy link

mkager05 commented Jan 10, 2025

Buenos días.

Veo que indicas la posición de la firma pero no estás indicando lo que quieres mostrar en la firma, probablemente por eso no "dibuja" nada. Para mostrar un texto tendrías que añadir lo siguiente:

layer2Text=Firmado por $$SUBJECTCN$$ el día $$SIGNDATE=dd/MM/yyyy$$

Eso mostraría el campo Subject del certificado y la fecha en la que se realiza la firma.

Un saludo.

@Gamuci
Copy link
Contributor

Gamuci commented Jan 23, 2025

No se están pasando los extraParams en el formato que espera la aplicación, así que los está ignorando. La cadena debería ser:

signaturePositionOnPageLowerLeftX=100\nsignaturePositionOnPageLowerLeftY=100\nsignaturePositionOnPageUpperRightX=400\nsignaturePositionOnPageUpperRightY=200\nsignaturePage=1\nsigningReason=Aprobación

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants