Skip to content
36 changes: 36 additions & 0 deletions Uses-Cases/Acroforms/acroforms_add.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import os
import logging
from pathlib import Path
from acroforms_helper import Config, PdfAcroformsHelper, logging
from asposepdfcloud import ApiClient, PdfApi, TextBoxField, Rectangle, Border, Dash

class PdfAcroformsAdd:
""" Class for adding form field to PDF document"""
def __init__(self, pdf_api: PdfApi, helper: PdfAcroformsHelper):
self.pdfApi = pdf_api
self.helper = helper

def addField(self, documentName: str, outputDocumentName: str, localFolder: Path, remoteFolder: str):
self.helper.uploadFile(documentName, localFolder, remoteFolder)

textBox = TextBoxField(
page_index=1,
partial_name= "EMail",
rect= Rectangle(llx=100, lly=100, urx=180, ury=120),
value= "[email protected]",
border= Border(
width=5,
dash=Dash(on=1, off=1)
)
)
try:
response = self.pdfApi.put_text_box_field(documentName, "EMail", textBox, folder=remoteFolder)
if response.code == 200:
logging.info("PdfAcroformsAdd(): Form filed 'Email' successfully added to the page #1.")
self.helper.downloadFile(documentName, outputDocumentName, localFolder, remoteFolder, "add_form_")
else:
logging.error(f"PdfAcroformsAdd(): Failed to add filed 'Email' to the page #1. Response code: {response.code}")
except Exception as e:

logging.error(f"PdfAcroformsAdd(): Error while adding form field: {e}")

26 changes: 26 additions & 0 deletions Uses-Cases/Acroforms/acroforms_get.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
import logging
from pathlib import Path
from acroforms_helper import Config, PdfAcroformsHelper, logging
from asposepdfcloud import ApiClient, PdfApi, FieldsResponse, Field

class PdfAcroformsGet:
""" Class for extracting form field from PDF document"""
def __init__(self, pdf_api: PdfApi, helper: PdfAcroformsHelper):
self.pdfApi = pdf_api
self.helper = helper

def getField(self, documentName: str, localFolder: Path, remoteFolder: str):
self.helper.uploadFile(documentName, localFolder, remoteFolder)

try:
response: FieldsResponse = self.pdfApi.get_fields(documentName, folder=remoteFolder)
if response.code == 200:
for field in response.fields.list:
logging.info(f"PdfAcroformsGet(): Form filed '{field}'.")
else:
logging.error(f"PdfAcroformsGet(): Failed to get form fileds from document. Response code: {response.code}")
except Exception as e:

logging.error(f"PdfAcroformsGet(): Error while extracting form field: {e}")

59 changes: 59 additions & 0 deletions Uses-Cases/Acroforms/acroforms_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import shutil
import json
import logging
import os
from pathlib import Path
from asposepdfcloud import ApiClient, PdfApi, HighlightAnnotation, Rectangle, Color, Point, AnnotationFlags, HorizontalAlignment, VerticalAlignment, AnnotationType

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")


class Config:
"""Configuration parameters."""
CREDENTIALS_FILE = Path(r"..\credentials.json") # Your Credentials path
LOCAL_FOLDER = Path(r"C:\Samples")
REMOTE_FOLDER = "Your_Temp_Pdf_Cloud"
PDF_DOCUMENT_NAME = "sample.pdf"
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
FIELD_NAME = "Signature_1"

class PdfAcroformsHelper:
def __init__(self, credentials_file: Path):
self.pdf_api = None
self._init_api(credentials_file)

def _init_api(self, credentials_file: Path):
"""Initialize the API client."""
try:
with credentials_file.open("r", encoding="utf-8") as file:
credentials = json.load(file)
api_key, app_id = credentials.get("key"), credentials.get("id")
if not api_key or not app_id:
raise ValueError("Error: Missing API keys in the credentials file.")
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
logging.error(f"Failed to load credentials: {e}")

def uploadFile(self, fileName: str, localFolder: Path, remoteFolder: str):
""" Upload a local fileName to the Aspose Cloud server. """
if self.pdf_api:
file_path = localFolder / fileName
try:
self.pdf_api.upload_file(os.path.join(remoteFolder, fileName), file_path)
logging.info(f"upload_file(): File '{fileName}' uploaded successfully.")
except Exception as e:
logging.error(f"upload_document(): Failed to upload file: {e}")


def downloadFile(self, document: str, outputDocument: str, localFolder: Path, remoteFolder: Path, output_prefix: str):
"""Download the processed PDF document from the Aspose Cloud server."""
if self.pdf_api:
try:
temp_file = self.pdf_api.download_file(str(remoteFolder) + '/' + document)
local_path = localFolder / ( output_prefix + outputDocument )
shutil.move(temp_file, str(local_path))
logging.info(f"download_result(): File successfully downloaded: {local_path}")
except Exception as e:

logging.error(f"download_result(): Failed to download file: {e}")
24 changes: 24 additions & 0 deletions Uses-Cases/Acroforms/acroforms_launch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from acroforms_helper import PdfAcroformsHelper, Config
from acroforms_add import PdfAcroformsAdd
from acroforms_get import PdfAcroformsGet
from acroforms_remove import PdfAcroformsDel
from acroforms_set import PdfAcroformsSetter
from acroforms_update import PdfAcroformsUpdate

if __name__ == "__main__":
helper = PdfAcroformsHelper(Config.CREDENTIALS_FILE)

add_filed = PdfAcroformsAdd(helper.pdf_api, helper)
add_filed.addField(Config.PDF_DOCUMENT_NAME, Config.LOCAL_RESULT_DOCUMENT_NAME, Config.LOCAL_FOLDER, Config.REMOTE_FOLDER)

del_fild =PdfAcroformsDel(helper.pdf_api, helper)
del_fild.delField(Config.PDF_DOCUMENT_NAME, Config.LOCAL_RESULT_DOCUMENT_NAME, Config.FIELD_NAME, Config.LOCAL_FOLDER, Config.REMOTE_FOLDER)

get_filed = PdfAcroformsGet(helper.pdf_api, helper)
get_filed.getField(Config.PDF_DOCUMENT_NAME, Config.LOCAL_FOLDER, Config.REMOTE_FOLDER)

set_fild = PdfAcroformsSetter(helper.pdf_api, helper)
set_fild.setField(Config.PDF_DOCUMENT_NAME, Config.LOCAL_RESULT_DOCUMENT_NAME, Config.FIELD_NAME, Config.LOCAL_FOLDER, Config.REMOTE_FOLDER)

upd_fild = PdfAcroformsUpdate(helper.pdf_api, helper)
upd_fild.updField(Config.PDF_DOCUMENT_NAME, Config.LOCAL_RESULT_DOCUMENT_NAME, Config.FIELD_NAME, Config.LOCAL_FOLDER, Config.REMOTE_FOLDER)
26 changes: 26 additions & 0 deletions Uses-Cases/Acroforms/acroforms_remove.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
import logging
from pathlib import Path
from acroforms_helper import Config, PdfAcroformsHelper, logging
from asposepdfcloud import ApiClient, PdfApi, TextBoxField, Rectangle, Border, Dash

class PdfAcroformsDel:
""" Class for deleting form field from PDF document"""
def __init__(self, pdf_api: PdfApi, helper: PdfAcroformsHelper):
self.pdfApi = pdf_api
self.helper = helper

def delField(self, documentName: str, outputDocumentName: str, fieldName: str, localFolder: Path, remoteFolder: str):
self.helper.uploadFile(documentName, localFolder, remoteFolder)

try:
response = self.pdfApi.delete_field(documentName, fieldName, folder=remoteFolder)
if response.code == 200:
logging.info(f"PdfAcroformsDel(): Form filed '{fieldName}' successfully deleted from docuemnt.")
self.helper.downloadFile(documentName, outputDocumentName, localFolder, remoteFolder, "del_form_")
else:
logging.error(f"PdfAcroformsDel(): Failed to reomve filed '{fieldName}' from document. Response code: {response.code}")
except Exception as e:

logging.error(f"PdfAcroformsDel(): Error while deleting form field: {e}")

31 changes: 31 additions & 0 deletions Uses-Cases/Acroforms/acroforms_set.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import os
import logging
from pathlib import Path
from acroforms_helper import Config, PdfAcroformsHelper, logging
from asposepdfcloud import ApiClient, PdfApi, Field, FieldType

class PdfAcroformsSetter:
""" Class for writing new form field values to PDF document"""
def __init__(self, pdf_api: PdfApi, helper: PdfAcroformsHelper):
self.pdfApi = pdf_api
self.helper = helper

def setField(self, documentName: str, outputDocumentName: str, fieldName: str, localFolder: Path, remoteFolder: str):
self.helper.uploadFile(documentName, localFolder, remoteFolder)

field = Field(
name="EMail",
type=FieldType.TEXT,
values=["[email protected]"]
)
try:
response = self.pdfApi.put_update_field(documentName, fieldName, field, folder=remoteFolder)
if response.code == 200:
logging.info(f"PdfAcroformsReplace(): Form filed '{fieldName}' successfully updated in the document.")
self.helper.downloadFile(documentName, outputDocumentName, localFolder, remoteFolder, "set_form_")
else:
logging.error(f"PdfAcroformsReplace(): Failed to update filed 'Email' inn the document. Response code: {response.code}")
except Exception as e:

logging.error(f"PdfAcroformsReplace(): Error while updating form field: {e}")

34 changes: 34 additions & 0 deletions Uses-Cases/Acroforms/acroforms_update.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import os
import logging
from pathlib import Path
from acroforms_helper import Config, PdfAcroformsHelper, logging
from asposepdfcloud import ApiClient, PdfApi, Field, Fields, FieldType, Rectangle

class PdfAcroformsUpdate:
""" Class for updating form fields in PDF document"""
def __init__(self, pdf_api: PdfApi, helper: PdfAcroformsHelper):
self.pdfApi = pdf_api
self.helper = helper

def updField(self, documentName: str, outputDocumentName: str, fieldName: str, localFolder: Path, remoteFolder: str):
self.helper.uploadFile(documentName, localFolder, remoteFolder)

field = Field(
name=fieldName,
type=FieldType.TEXT,
values=["[email protected]"],
rect= Rectangle( llx=125, lly=735, urx=200, ury=752),
)

fields = Fields(list=[field])

try:
response = self.pdfApi.put_update_fields(documentName, fields, folder=remoteFolder)
if response.code == 200:
logging.info(f"PdfAcroformsUpdate(): Form filed '{fieldName}' successfully updated in the document.")
self.helper.downloadFile(documentName, outputDocumentName, localFolder, remoteFolder, "update_form_")
else:
logging.error(f"PdfAcroformsUpdate(): Failed to update fileds in the document. Response code: {response.code}")
except Exception as e:

logging.error(f"PdfAcroformsUpdate(): Error while updating form field: {e}")