Skip to content

Commit 135b6a5

Browse files
authored
Merge pull request #106 from aspose-pdf-cloud/develop
update to 25.5
2 parents 53322ff + e3e04bd commit 135b6a5

File tree

14 files changed

+799
-9
lines changed

14 files changed

+799
-9
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ XLS, XLSX, PPTX, DOC, DOCX, MobiXML, JPEG, EMF, PNG, BMP, GIF, TIFF, Text
3030
## Read PDF Formats
3131
MHT, PCL, PS, XSLFO, MD
3232

33-
## Enhancements in Version 25.4
34-
- Add method for adding Stamp per page in batch.
33+
## Enhancements in Version 25.5
34+
- Add a method for comparing pdf files.
3535
- A new version of Aspose.PDF Cloud was prepared using the latest version of Aspose.PDF for .NET.
3636

3737
## Requirements.
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, OptimizeOptions
6+
7+
# Configure logging
8+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
9+
10+
11+
class Config:
12+
"""Configuration parameters."""
13+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
14+
LOCAL_FOLDER = Path(r"C:\Samples")
15+
TEMP_FOLDER = 'TempPdfCloud'
16+
PDF_DOCUMENT_NAME = "sample.pdf"
17+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
18+
19+
class PdfCompress:
20+
"""Class for compress PDF links using Aspose PDF Cloud API."""
21+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
22+
self.pdf_api = None
23+
self._init_api(credentials_file)
24+
25+
def _init_api(self, credentials_file: Path):
26+
"""Initialize the API client."""
27+
try:
28+
with credentials_file.open("r", encoding="utf-8") as file:
29+
credentials = json.load(file)
30+
api_key, app_id = credentials.get("key"), credentials.get("id")
31+
if not api_key or not app_id:
32+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
33+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
34+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
35+
logging.error(f"init_api(): Failed to load credentials: {e}")
36+
37+
def upload_document(self):
38+
"""Upload a PDF document to the Aspose Cloud server."""
39+
if self.pdf_api:
40+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
41+
stotage_path = Config.TEMP_FOLDER + '/' + Config.PDF_DOCUMENT_NAME
42+
try:
43+
self.pdf_api.upload_file(stotage_path, str(file_path))
44+
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
45+
except Exception as e:
46+
logging.error(f"upload_document(): Failed to upload file: {e}")
47+
48+
def download_result(self):
49+
"""Download the processed PDF document from the Aspose Cloud server."""
50+
if self.pdf_api:
51+
try:
52+
temp_file = self.pdf_api.download_file(Config.TEMP_FOLDER + '/' + Config.PDF_DOCUMENT_NAME)
53+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
54+
shutil.move(temp_file, str(local_path))
55+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
56+
except Exception as e:
57+
logging.error(f"download_result(): Failed to download file: {e}")
58+
59+
def compress_pdf_document(self):
60+
"""Compress the PDF document."""
61+
if self.pdf_api:
62+
optimize_options = OptimizeOptions(
63+
allow_reuse_page_content=False,
64+
compress_images=True,
65+
image_quality=100,
66+
link_duplcate_streams=True,
67+
remove_unused_objects=True,
68+
remove_unused_streams=True,
69+
unembed_fonts=True
70+
)
71+
opts = {
72+
"options" : optimize_options,
73+
"folder" : Config.TEMP_FOLDER
74+
}
75+
try:
76+
response = self.pdf_api.post_optimize_document(Config.PDF_DOCUMENT_NAME, **opts)
77+
78+
if response.code == 200:
79+
logging.info(f"compress_pdf_document(): PDF document '{Config.PDF_DOCUMENT_NAME}' successfully compressed.")
80+
else:
81+
logging.error(f"compress_pdf_document(): Failed to compress document. Response code: {response.code}")
82+
except Exception as e:
83+
logging.error(f"compress_pdf_document(): Error while compress document: {e}")
84+
85+
86+
if __name__ == "__main__":
87+
pdf_compress = PdfCompress()
88+
pdf_compress.upload_document()
89+
pdf_compress.compress_pdf_document()
90+
pdf_compress.download_result()
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import shutil
2+
import json
3+
import logging
4+
import pathlib
5+
import math
6+
from asposepdfcloud import ApiClient, PdfApi, Direction, PageMode, PageLayout, DocumentConfig, DocumentProperties, DocumentProperty, DisplayProperties, DefaultPageConfig
7+
8+
# Configure logging
9+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
10+
11+
class Config:
12+
"""Configuration parameters."""
13+
CREDENTIALS_FILE = pathlib.Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
14+
LOCAL_FOLDER = pathlib.Path(r"C:\Samples")
15+
TEMP_FOLDER = 'TempPdfCloud'
16+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
17+
PAGE_WIDTH = 590
18+
PAGE_HEIGHT = 894
19+
PAGES_COUNT = 5
20+
21+
class PdfPageChanges:
22+
""" Class for managing PDF page changes using Aspose PDF Cloud API. """
23+
def __init__(self, credentials_file: pathlib.Path = Config.CREDENTIALS_FILE):
24+
self.pdf_api = None
25+
self._init_api(credentials_file)
26+
27+
def _init_api(self, credentials_file: pathlib.Path):
28+
""" Initialize the API client. """
29+
try:
30+
with credentials_file.open("r", encoding="utf-8") as file:
31+
credentials = json.load(file)
32+
api_key, app_id = credentials.get("key"), credentials.get("id")
33+
if not api_key or not app_id:
34+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
35+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
36+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
37+
logging.error(f"init_api(): Failed to load credentials: {e}")
38+
39+
def download_result(self):
40+
""" Download the processed PDF document from the Aspose Cloud server. """
41+
if self.pdf_api:
42+
try:
43+
temp_file = self.pdf_api.download_file(Config.TEMP_FOLDER + '/' + Config.LOCAL_RESULT_DOCUMENT_NAME)
44+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
45+
shutil.move(temp_file, str(local_path))
46+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
47+
except Exception as e:
48+
logging.error(f"download_result(): Failed to download file: {e}")
49+
50+
51+
def create_document(self):
52+
""" Create PDF document with required properties. """
53+
opts = {
54+
"folder" : Config.TEMP_FOLDER
55+
}
56+
57+
document_config = DocumentConfig(
58+
document_properties=DocumentProperties(
59+
list=[
60+
DocumentProperty(
61+
built_in=False,
62+
name='prop1',
63+
value='Val1',
64+
)
65+
]),
66+
display_properties=DisplayProperties(
67+
center_window = True,
68+
hide_menu_bar = True,
69+
direction = Direction.L2R,
70+
display_doc_title = True,
71+
hide_tool_bar = True,
72+
hide_window_ui = True,
73+
non_full_screen_page_mode = PageMode.USETHUMBS,
74+
page_layout = PageLayout.TWOPAGELEFT,
75+
page_mode = PageMode.USETHUMBS
76+
),
77+
default_page_config=DefaultPageConfig(
78+
height=Config.PAGE_HEIGHT,
79+
width=Config.PAGE_WIDTH
80+
),
81+
pages_count=Config.PAGES_COUNT
82+
)
83+
response = self.pdf_api.post_create_document(Config.LOCAL_RESULT_DOCUMENT_NAME, document_config, **opts)
84+
logging.info(f"Document #{Config.LOCAL_RESULT_DOCUMENT_NAME} created.")
85+
return response
86+
87+
if __name__ == "__main__":
88+
pdf_pages = PdfPageChanges()
89+
pdf_pages.create_document()
90+
pdf_pages.download_result()
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import shutil
2+
import json
3+
import logging
4+
import os
5+
from pathlib import Path
6+
from asposepdfcloud import ApiClient, PdfApi
7+
8+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
9+
10+
credentials_file = Path( os.path.join(os.path.dirname(os.path.realpath('__file__')), "..\Credentials\credentials.json"))
11+
local_folder = Path(r"C:\Samples")
12+
pdf_document = "output_sample.pdf"
13+
14+
pdf_api = None
15+
16+
try:
17+
""" Load credentials and create PDF Rest API object """
18+
with credentials_file.open("r", encoding="utf-8") as file:
19+
credentials = json.load(file)
20+
api_key, app_id = credentials.get("key"), credentials.get("id")
21+
if not api_key or not app_id:
22+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
23+
pdf_api = PdfApi(ApiClient(api_key, app_id))
24+
25+
if pdf_api:
26+
""" Create empty PDF document """
27+
pdf_response = pdf_api.put_create_document(pdf_document)
28+
if pdf_response.code == 200:
29+
logging.info(f"Document #{pdf_document} created.")
30+
31+
""" Download empty PDF document to local folder """
32+
temp_file = pdf_api.download_file(pdf_document)
33+
local_path = local_folder / pdf_document
34+
shutil.move(temp_file, str(local_path))
35+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
36+
except Exception as err:
37+
38+
logging.error(f"Failed to create empty Pdfdocument '{pdf_document}'!.")
39+
logging.error(f"Unexpected {err=}, {type(err)=}")
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Signature, SignatureType, SignatureField, Rectangle
6+
7+
# Configure logging
8+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
9+
10+
11+
class Config:
12+
"""Configuration parameters."""
13+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
14+
LOCAL_FOLDER = Path(r"C:\Samples")
15+
PDF_DOCUMENT_NAME = "sample.pdf"
16+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
17+
LOCAL_SIGNATURE_PATH = Path(r"C:\Samples\Signatures\3")
18+
SIGNATURE_PFX = "signature.pfx"
19+
SIGNATURE_FORM_FIELD = 'Signature_1'
20+
SIGNATURE_PASSWORD='Password'
21+
SIGNATURE_CONTACT='Contact'
22+
SIGNATURE_LOCATION='Location'
23+
SIGNATURE_AUTHORITY='Issuer'
24+
SIGNATURE_DATE='04/19/2025 12:15:00.000 PM'
25+
SIGNATURE_RECT = Rectangle(100, 100, 500, 500)
26+
27+
28+
class PdfSignatures:
29+
"""Class for managing PDF signatures using Aspose PDF Cloud API."""
30+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
31+
self.pdf_api = None
32+
self._init_api(credentials_file)
33+
34+
def _init_api(self, credentials_file: Path):
35+
"""Initialize the API client."""
36+
try:
37+
with credentials_file.open("r", encoding="utf-8") as file:
38+
credentials = json.load(file)
39+
api_key, app_id = credentials.get("key"), credentials.get("id")
40+
if not api_key or not app_id:
41+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
42+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
43+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
44+
logging.error(f"init_api(): Failed to load credentials: {e}")
45+
46+
def upload_file(self, local_path: Path, fileName: str):
47+
""" Upload a local fileName to the Aspose Cloud server. """
48+
if self.pdf_api:
49+
file_path = local_path / fileName
50+
try:
51+
self.pdf_api.upload_file(fileName, str(file_path))
52+
logging.info(f"upload_file(): File '{fileName}' uploaded successfully.")
53+
except Exception as e:
54+
logging.error(f"upload_document(): Failed to upload file: {e}")
55+
56+
def upload_document(self):
57+
""" Upload a PDF document to the Aspose Cloud server. """
58+
self.upload_file(Config.LOCAL_FOLDER, Config.PDF_DOCUMENT_NAME)
59+
60+
61+
def download_result(self):
62+
"""Download the processed PDF document from the Aspose Cloud server."""
63+
if self.pdf_api:
64+
try:
65+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
66+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
67+
shutil.move(temp_file, str(local_path))
68+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
69+
except Exception as e:
70+
logging.error(f"download_result(): Failed to download file: {e}")
71+
72+
def append_signature(self):
73+
"""Append a new signature to the PDF document."""
74+
if self.pdf_api:
75+
76+
signature = Signature(
77+
signature_path=Config.SIGNATURE_PFX,
78+
signature_type=SignatureType.PKCS7,
79+
password=Config.SIGNATURE_PASSWORD,
80+
contact=Config.SIGNATURE_CONTACT,
81+
location=Config.SIGNATURE_LOCATION,
82+
visible=True,
83+
rectangle=Config.SIGNATURE_RECT,
84+
form_field_name=Config.SIGNATURE_FORM_FIELD,
85+
authority=Config.SIGNATURE_AUTHORITY,
86+
date=Config.SIGNATURE_DATE,
87+
show_properties=False)
88+
89+
field = SignatureField(page_index=1)
90+
field.signature = signature
91+
field.partial_name = 'sign1'
92+
field.rect = Config.SIGNATURE_RECT
93+
94+
try:
95+
response = self.pdf_api.post_signature_field(Config.PDF_DOCUMENT_NAME, field)
96+
if response.code == 200:
97+
logging.info(f"append_signature(): Signature '{Config.SIGNATURE_CONTACT}' successfully added to the document.")
98+
else:
99+
logging.error(f"append_signature(): Failed to add signature to the document. Response code: {response.code}")
100+
except Exception as e:
101+
logging.error(f"append_signature(): Error while adding signature: {e}")
102+
103+
104+
if __name__ == "__main__":
105+
pdf_sign = PdfSignatures()
106+
pdf_sign.upload_document()
107+
pdf_sign.upload_file(Config.LOCAL_SIGNATURE_PATH, Config.SIGNATURE_PFX)
108+
pdf_sign.append_signature()
109+
pdf_sign.download_result()

0 commit comments

Comments
 (0)