Skip to content

Commit f46baf8

Browse files
PDFCLOUD-4801: added uses cases for Sign
1 parent f70472b commit f46baf8

File tree

4 files changed

+351
-0
lines changed

4 files changed

+351
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import credentials from "../../../Credentials/credentials.json" with { type: "json" };
2+
import fs from 'node:fs/promises';
3+
import path from 'node:path';
4+
import { PdfApi } from "../../src/api/api.js";
5+
import {Signature} from "../../src/models/signature.js";
6+
import {SignatureType} from "../../src/models/signatureType.js";
7+
import {SignatureField} from "../../src/models/signatureField.js";
8+
9+
const configParams = {
10+
LOCAL_FOLDER: "C:\\Samples\\",
11+
PDF_DOCUMENT_NAME: "sample.pdf",
12+
LOCAL_RESULT_DOCUMENT_NAME: "output_sample.pdf",
13+
LOCAL_SIGNATURE_PATH: "C:\\Samples\\Signatures\\3",
14+
SIGNATURE_PFX: "signature.pfx",
15+
SIGNATURE_FORM_FIELD: 'Signature_1',
16+
SIGNATURE_PASSWORD: 'Password',
17+
SIGNATURE_CONTACT: 'Contact',
18+
SIGNATURE_LOCATION: 'Location',
19+
SIGNATURE_AUTHORITY: 'Issuer',
20+
SIGNATURE_DATE: '04/19/2025 12:15:00.000 PM',
21+
SIGNATURE_RECT: { lLx: 100, lLy: 100, uRx: 500, uRy: 500 }
22+
};
23+
24+
const pdfApi = new PdfApi(credentials.id, credentials.key);
25+
26+
const pdfSignatures = {
27+
async uploadFile (folder, fileName) {
28+
const fileNamePath = path.join(folder, fileName);
29+
const pdfFileData = await fs.readFile(fileNamePath);
30+
await pdfApi.uploadFile(fileName, pdfFileData);
31+
console.log("File '" + fileName + "' successfully uploaded!");
32+
},
33+
34+
async uploadDocument () {
35+
await this.uploadFile(configParams.LOCAL_FOLDER, configParams.PDF_DOCUMENT_NAME);
36+
},
37+
38+
async downloadResult () {
39+
const changedPdfData = await pdfApi.downloadFile(configParams.PDF_DOCUMENT_NAME);
40+
const filePath = path.join(configParams.LOCAL_FOLDER, configParams.LOCAL_RESULT_DOCUMENT_NAME);
41+
await fs.writeFile(filePath, changedPdfData.body);
42+
console.log("Downloaded: " + filePath);
43+
},
44+
45+
async addSignature () {
46+
if (pdfApi)
47+
{
48+
49+
const signature = new Signature();
50+
signature.authority = configParams.SIGNATURE_AUTHORITY;
51+
signature.contact = configParams.SIGNATURE_CONTACT;
52+
signature.date = configParams.SIGNATURE_DATE;
53+
signature.formFieldName = configParams.SIGNATURE_FORM_FIELD;
54+
signature.location = configParams.SIGNATURE_LOCATION;
55+
signature.password = configParams.SIGNATURE_PASSWORD;
56+
signature.rectangle = configParams.SIGNATURE_RECT;
57+
signature.signaturePath = configParams.SIGNATURE_PFX;
58+
signature.signatureType = SignatureType.PKCS7;
59+
signature.visible = true;
60+
61+
const field = new SignatureField();
62+
field.pageIndex = 1;
63+
field.signature = signature;
64+
field.partialName = 'sign1';
65+
field.rect = configParams.SIGNATURE_RECT;
66+
67+
const response = await pdfApi.postSignatureField(configParams.PDF_DOCUMENT_NAME, field);
68+
69+
if (response.body.code == 200)
70+
console.log("addSignature(): Signature '" + configParams.SIGNATURE_CONTACT + "' successfully added to the document.");
71+
else
72+
console.error("addSignature(): Failed to add signature to the document. Response code: " + response.body.code);
73+
}
74+
},
75+
}
76+
77+
async function main() {
78+
try {
79+
await pdfSignatures.uploadFile(configParams.LOCAL_SIGNATURE_PATH, configParams.SIGNATURE_PFX);
80+
await pdfSignatures.uploadDocument();
81+
await pdfSignatures.addSignature();
82+
await pdfSignatures.downloadResult();
83+
} catch (error) {
84+
console.error("Error:", error.message);
85+
}
86+
}
87+
88+
main();
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import credentials from "../../../Credentials/credentials.json" with { type: "json" };
2+
import fs from 'node:fs/promises';
3+
import path from 'node:path';
4+
import { PdfApi } from "../../src/api/api.js";
5+
6+
7+
const configParams = {
8+
LOCAL_FOLDER: "C:\\Samples\\",
9+
PDF_DOCUMENT_NAME: "sample-signed.pdf",
10+
}
11+
12+
const pdfApi = new PdfApi(credentials.id, credentials.key);
13+
14+
const pdfSignatures = {
15+
async uploadDocument () {
16+
const fileNamePath = path.join(configParams.LOCAL_FOLDER, configParams.PDF_DOCUMENT_NAME);
17+
const pdfFileData = await fs.readFile(fileNamePath);
18+
await pdfApi.uploadFile(configParams.PDF_DOCUMENT_NAME, pdfFileData);
19+
console.log("File '" + configParams.PDF_DOCUMENT_NAME + "' successfully uploaded!");
20+
},
21+
22+
showSignatureFieldsArray(fields)
23+
{
24+
if (fields.list.length > 0)
25+
fields.list.forEach(function(item) {
26+
console.log("Signature => value: '" + item.signature.contact + "'");
27+
});
28+
else
29+
console.log("Signature fileds is empty!");
30+
},
31+
32+
async getSignatureFields () {
33+
if (pdfApi)
34+
{
35+
const response = await pdfApi.getDocumentSignatureFields(configParams.PDF_DOCUMENT_NAME);
36+
37+
if (response.body.code == 200 && response.body.fields) {
38+
console.log("getSignatureFields(): Signature fields successfully extracted in to the '" + configParams.PDF_DOCUMENT_NAME + "' documen:")
39+
this.showSignatureFieldsArray(response.body.fields);
40+
}
41+
else
42+
console.error("getSignatures(): Failed to extract signatures in the document. Response code: " + response.body.code);
43+
}
44+
},
45+
}
46+
47+
async function main() {
48+
try {
49+
await pdfSignatures.uploadDocument();
50+
await pdfSignatures.getSignatureFields();
51+
} catch (error) {
52+
console.error("Error:", error.message);
53+
}
54+
}
55+
56+
main();
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import credentials from "../../../Credentials/credentials.json" with { type: "json" };
2+
import fs from 'node:fs/promises';
3+
import path from 'node:path';
4+
import { PdfApi } from "../../src/api/api.js";
5+
import {Signature} from "../../src/models/signature.js";
6+
import {SignatureType} from "../../src/models/signatureType.js";
7+
import {SignatureField} from "../../src/models/signatureField.js";
8+
9+
const configParams = {
10+
LOCAL_FOLDER: "C:\\Samples\\",
11+
PDF_DOCUMENT_NAME: "sample.pdf",
12+
LOCAL_RESULT_DOCUMENT_NAME: "output_sample.pdf",
13+
LOCAL_SIGNATURE_PATH: "C:\\Samples\\Signatures\\3",
14+
SIGNATURE_PFX: "signature.pfx",
15+
SIGNATURE_FORM_FIELD: 'Signature_1',
16+
SIGNATURE_PASSWORD: 'Password',
17+
SIGNATURE_CONTACT: 'Contact',
18+
SIGNATURE_LOCATION: 'Location',
19+
SIGNATURE_AUTHORITY: 'Issuer',
20+
SIGNATURE_DATE: '04/19/2025 12:15:00.000 PM',
21+
SIGNATURE_RECT: { lLx: 100, lLy: 100, uRx: 500, uRy: 500 }
22+
};
23+
24+
const pdfApi = new PdfApi(credentials.id, credentials.key);
25+
26+
const pdfSignatures = {
27+
async uploadFile (folder, fileName) {
28+
const fileNamePath = path.join(folder, fileName);
29+
const pdfFileData = await fs.readFile(fileNamePath);
30+
await pdfApi.uploadFile(fileName, pdfFileData);
31+
console.log("File '" + fileName + "' successfully uploaded!");
32+
},
33+
34+
async uploadDocument () {
35+
await this.uploadFile(configParams.LOCAL_FOLDER, configParams.PDF_DOCUMENT_NAME);
36+
},
37+
38+
async downloadResult () {
39+
const changedPdfData = await pdfApi.downloadFile(configParams.PDF_DOCUMENT_NAME);
40+
const filePath = path.join(configParams.LOCAL_FOLDER, configParams.LOCAL_RESULT_DOCUMENT_NAME);
41+
await fs.writeFile(filePath, changedPdfData.body);
42+
console.log("Downloaded: " + filePath);
43+
},
44+
45+
async replaceSignature () {
46+
if (pdfApi)
47+
{
48+
49+
const signature = new Signature();
50+
signature.authority = configParams.SIGNATURE_AUTHORITY;
51+
signature.contact = configParams.SIGNATURE_CONTACT;
52+
signature.date = configParams.SIGNATURE_DATE;
53+
signature.formFieldName = configParams.SIGNATURE_FORM_FIELD;
54+
signature.location = configParams.SIGNATURE_LOCATION;
55+
signature.password = configParams.SIGNATURE_PASSWORD;
56+
signature.rectangle = configParams.SIGNATURE_RECT;
57+
signature.signaturePath = configParams.SIGNATURE_PFX;
58+
signature.signatureType = SignatureType.PKCS7;
59+
signature.visible = true;
60+
61+
const field = new SignatureField();
62+
field.pageIndex = 1;
63+
field.signature = signature;
64+
field.partialName = 'sign1';
65+
field.rect = configParams.SIGNATURE_RECT;
66+
67+
const response = await pdfApi.putSignatureField(configParams.PDF_DOCUMENT_NAME, configParams.SIGNATURE_FORM_FIELD, field);
68+
69+
if (response.body.code == 200)
70+
console.log("replaceSignature(): Signature '" + configParams.SIGNATURE_CONTACT + "' successfully replaced in the document.");
71+
else
72+
console.error("replaceSignature(): Failed to replace signature in the document. Response code: " + response.body.code);
73+
}
74+
},
75+
}
76+
77+
async function main() {
78+
try {
79+
await pdfSignatures.uploadFile(configParams.LOCAL_SIGNATURE_PATH, configParams.SIGNATURE_PFX);
80+
await pdfSignatures.uploadDocument();
81+
await pdfSignatures.replaceSignature();
82+
await pdfSignatures.downloadResult();
83+
} catch (error) {
84+
console.error("Error:", error.message);
85+
}
86+
}
87+
88+
main();
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import credentials from "../../../Credentials/credentials.json" with { type: "json" };
2+
import fs from 'node:fs/promises';
3+
import path from 'node:path';
4+
import { PdfApi } from "../../src/api/api.js";
5+
6+
7+
const configParams = {
8+
LOCAL_FOLDER: "C:\\Samples\\",
9+
PDF_DOCUMENT_NAME: "sample-signed.pdf",
10+
SIGNATURE_NAME: 'sign1',
11+
}
12+
13+
const pdfApi = new PdfApi(credentials.id, credentials.key);
14+
15+
const pdfSignatures = {
16+
async uploadDocument () {
17+
const fileNamePath = path.join(configParams.LOCAL_FOLDER, configParams.PDF_DOCUMENT_NAME);
18+
const pdfFileData = await fs.readFile(fileNamePath);
19+
await pdfApi.uploadFile(configParams.PDF_DOCUMENT_NAME, pdfFileData);
20+
console.log("File '" + configParams.PDF_DOCUMENT_NAME + "' successfully uploaded!");
21+
},
22+
23+
async verifySignature () {
24+
if (pdfApi)
25+
{
26+
const response = await pdfApi.getVerifySignature(configParams.PDF_DOCUMENT_NAME, configParams.SIGNATURE_NAME);
27+
28+
if (response.body.code == 200) {
29+
if (response.body.valid == true)
30+
console.log("verifySignature(): Signature is VALID for the '" + configParams.PDF_DOCUMENT_NAME + "' documen.");
31+
else
32+
console.log("verifySignature(): Signature is NOT VALID for the '" + configParams.PDF_DOCUMENT_NAME + "' documen.");
33+
}
34+
else
35+
console.error("verifySignature(): Failed to extract signatures in the document. Response code: " + response.body.code);
36+
}
37+
},
38+
}
39+
40+
async function main() {
41+
try {
42+
await pdfSignatures.uploadDocument();
43+
await pdfSignatures.verifySignature();
44+
} catch (error) {
45+
console.error("Error:", error.message);
46+
}
47+
}
48+
49+
main();
50+
51+
52+
/*
53+
import shutil
54+
import json
55+
import logging
56+
from pathlib import Path
57+
from asposepdfcloud import ApiClient, PdfApi, Signature, SignatureType, Rectangle
58+
59+
# Configure logging
60+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
61+
62+
63+
class Config:
64+
"""Configuration parameters."""
65+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
66+
LOCAL_FOLDER = Path(r"C:\Samples")
67+
PDF_DOCUMENT_NAME = "sample.pdf"
68+
SIGNATURE_FORM_FIELD = 'Signature_1'
69+
70+
71+
class PdfSignatures:
72+
"""Class for managing PDF signatures using Aspose PDF Cloud API."""
73+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
74+
self.pdf_api = None
75+
self._init_api(credentials_file)
76+
77+
def _init_api(self, credentials_file: Path):
78+
"""Initialize the API client."""
79+
try:
80+
with credentials_file.open("r", encoding="utf-8") as file:
81+
credentials = json.load(file)
82+
api_key, app_id = credentials.get("key"), credentials.get("id")
83+
if not api_key or not app_id:
84+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
85+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
86+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
87+
logging.error(f"init_api(): Failed to load credentials: {e}")
88+
89+
def upload_document(self):
90+
"""Upload a PDF document to the Aspose Cloud server."""
91+
if self.pdf_api:
92+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
93+
try:
94+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
95+
logging.info(f"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
96+
except Exception as e:
97+
logging.error(f"Failed to upload file: {e}")
98+
99+
def verify_signature(self):
100+
"""Verify signature fields in the PDF document."""
101+
if self.pdf_api:
102+
try:
103+
response = self.pdf_api.get_verify_signature(Config.PDF_DOCUMENT_NAME, Config.SIGNATURE_FORM_FIELD)
104+
if response.code == 200:
105+
if response.valid == True:
106+
logging.info(f"verify_signature(): Signature is valid for the '{Config.PDF_DOCUMENT_NAME}' documen.")
107+
else:
108+
logging.error(f"verify_signature(): Signature is not valid for the '{Config.PDF_DOCUMENT_NAME}' documen.")
109+
else:
110+
logging.error(f"verify_signature(): Failed to verify signature for the document. Response code: {response.code}")
111+
except Exception as e:
112+
logging.error(f"verify_signature(): Error while verified signature: {e}")
113+
114+
115+
if __name__ == "__main__":
116+
pdf_sign = PdfSignatures()
117+
pdf_sign.upload_document()
118+
pdf_sign.verify_signature()
119+
*/

0 commit comments

Comments
 (0)