diff --git a/.gitignore b/.gitignore index dc345d3..c6a95a2 100644 --- a/.gitignore +++ b/.gitignore @@ -250,3 +250,4 @@ BundleArtifacts/ .cake/* .nugetapikey +.vscode diff --git a/README.md b/README.md index e12a1bd..5ce42ff 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,13 @@ Directory | Description -

+

## General PDF Features - Supports most established PDF standards and PDF specifications. -- Ability to read & export PDFs in multiple image formats including BMP, GIF, JPEG & PNG. +- Ability to read & export PDFs in multiple image formats including BMP, GIF, JPEG & PNG. - Set basic information (e.g. author, creator) of the PDF document. - Configure PDF Page properties (e.g. width, height, cropbox, bleedbox etc.). - Set page numbering, bookmark level, page sizes etc. @@ -75,7 +75,7 @@ Below code snippet follows these steps: 1. Create an instance of the HtmlLoadOptions object. 1. Initialize Document object. -1. Save output PDF document by calling Document.Save() method. +1. Save output PDF document by calling Document.save() method. ```python import aspose.pdf as ap diff --git a/examples/facades_form/exporting_pdf_form_data.py b/examples/facades_form/exporting_pdf_form_data.py new file mode 100644 index 0000000..134d904 --- /dev/null +++ b/examples/facades_form/exporting_pdf_form_data.py @@ -0,0 +1,118 @@ +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Export Data to XML +def export_pdf_form_data_to_xml(infile, datafile): + """Export PDF form data to XML file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XML file as stream + with FileIO(datafile, 'w') as xml_output_stream: + # Export data from PDF form fields to XML + pdf_form.export_xml(xml_output_stream) + +# Export Data to FDF +def export_form_data_to_fdf(infile, outfile): + """Export PDF form data to FDF file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Create FDF file stream + with open(outfile, 'wb') as fdf_output_stream: + # Export form data to FDF file + pdf_form.export_fdf(fdf_output_stream) + +# Export Data to XFDF +def export_pdf_form_to_xfdf(infile, outfile): + """Export PDF form data to XFDF file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Create XFDF file stream + with open(outfile, "wb") as xfdf_output_stream: + # Export form data to XFDF file + pdf_form.export_xfdf(xfdf_output_stream) + +# Export Data to JSON +def export_form_to_json(infile, outfile): + """Export PDF form field values to JSON file.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Create JSON file stream + with FileIO(outfile, 'w') as json_stream: + # Export form field values to JSON + form.export_json(json_stream, indented=True) + +# Extract XFA Data +def export_xfa_data(infile, outfile): + """Export XFA form data.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + with FileIO(outfile, 'w') as stream: + # Export form field values to JSON + form.extract_xfa_data(stream) + +def run_all_examples(data_dir=None, license_path=None): + """Run all import/export form data examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Export Data to XML", export_pdf_form_data_to_xml, "sample_form.xml"), + ("Export Data to FDF", export_form_data_to_fdf, "sample_form.fdf"), + ("Export Data to XFDF", export_pdf_form_to_xfdf, "sample_form.xfdf"), + ("Export Values to JSON", export_form_to_json, "sample_form.json"), + ("Export XFA Data", export_xfa_data, "sample_form_xfa.xml"), + ] + + for name, func, data_file_name in examples: + try: + if (func.__name__ == "export_xfa_data"): + input_file_name = path.join(input_dir, "sample_xfa_form.pdf") + else: + input_file_name = path.join(input_dir, "sample_form.pdf") + output_file_name = path.join(output_dir, data_file_name) + func(input_file_name, output_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll Export Form Data examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_form/filling_form_fields.py b/examples/facades_form/filling_form_fields.py new file mode 100644 index 0000000..b78968c --- /dev/null +++ b/examples/facades_form/filling_form_fields.py @@ -0,0 +1,151 @@ +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Fill Text Fields +def fill_text_fields(infile, outfile): + """Fill text fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill text fields by name + pdf_form.fill_field("name", "John Doe") + pdf_form.fill_field("address", "123 Main St, Anytown, USA") + pdf_form.fill_field("email", "john.doe@example.com") + + # Save updated PDF + pdf_form.save(outfile) + +# Fill Check Box Fields +def fill_check_box_fields(infile, outfile): + """Fill check box fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill check box fields by name + pdf_form.fill_field("subscribe_newsletter", "Yes") + pdf_form.fill_field("accept_terms", "Yes") + + # Save updated PDF + pdf_form.save(outfile) + +# Fill Radio Button Fields +def fill_radio_button_fields(infile, outfile): + """Fill radio button fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill radio button fields by name + pdf_form.fill_field("gender", 0) # Select male option (index 0) + #pdf_form.fill_field("gender", 1) # Select female option (index 1) + + # Save updated PDF + pdf_form.save(outfile) + +# Fill List Box / Multi-Select Fields +def fill_list_box_fields(infile, outfile): + """Fill list box and multi-select fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill list box / multi-select fields by name + pdf_form.fill_field("favorite_colors", "Red") + + # Save updated PDF + pdf_form.save(outfile) + +# Fill Barcode Fields +def fill_barcode_fields(infile, outfile): + """Fill barcode fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill barcode fields by name + pdf_form.fill_field("product_barcode", "123456789012") + + # Save updated PDF + pdf_form.save(outfile) + +# Fill Fields by Name and Value +def fill_fields_by_name_and_value(infile, outfile): + """Fill PDF form fields by name and value.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill fields by name and value + fields = { + "name": "Jane Smith", + "address": "456 Elm St, Othertown, USA", + "email": "jane.smith@example.com" + } + + names = list(fields.keys()) + values = list(fields.values()) + output = [] + pdf_form.fill_fields(names, values, output) + stream = output[0] # Get filled PDF as stream + stream.seek(0) # Reset stream position to beginning + with open(outfile, 'wb') as f: + f.write(stream.read()) + +def run_all_examples(data_dir=None, license_path=None): + """Run all import form data examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Fill Text Fields", fill_text_fields), + ("Fill Check Box Fields", fill_check_box_fields), + ("Fill Radio Button Fields", fill_radio_button_fields), + ("Fill List Box / Multi-Select Fields", fill_list_box_fields), + ("Fill Barcode Fields", fill_barcode_fields), + ("Fill Fields by Name and Value", fill_fields_by_name_and_value) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, f"{func.__name__}_in.pdf") + output_file_name = path.join(output_dir, f"{func.__name__}_out.pdf") + func(input_file_name, output_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll Fill Form Fields examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_form/importing_pdf_form_data.py b/examples/facades_form/importing_pdf_form_data.py new file mode 100644 index 0000000..c760cb7 --- /dev/null +++ b/examples/facades_form/importing_pdf_form_data.py @@ -0,0 +1,136 @@ +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Import data from XML +def import_xml_to_pdf_fields(infile, datafile, outfile): + """Import form data from XML file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XML file as stream + with FileIO(datafile, 'r') as xml_input_stream: + # Import data from XML into PDF form fields + pdf_form.import_xml(xml_input_stream) + + # Save updated PDF + pdf_form.save(outfile) + +# Import Data from FDF +def import_fdf_to_pdf_form(infile, datafile, outfile): + """Import form data from FDF file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open FDF file as stream + with open(datafile, 'rb') as fdf_input_stream: + pdf_form.import_fdf(fdf_input_stream) + + # Save updated PDF + pdf_form.save(outfile) + +# Import Data from XFDF +def import_data_from_xfdf(infile, datafile, outfile): + """Import form data from XFDF file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XFDF file as stream + with open(datafile, 'rb') as xfdf_input_stream: + # Import data from XFDF into PDF form fields + pdf_form.import_xfdf(xfdf_input_stream) + + # Save updated PDF + pdf_form.save(outfile) + +# Import from JSON +def import_json_to_pdf_form(infile, datafile, outfile): + """Import form data from JSON file into PDF form fields.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Open JSON file as stream + with FileIO(datafile, 'r') as json_stream: + # Import data from JSON into PDF form fields + form.import_json(json_stream) + + # Save updated PDF + form.save(outfile) + +# Replace from XFA data +def replace_xfa_data(infile, datafile, outfile): + """Import form data from XFA file into PDF form fields.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Open XFA file as stream + with FileIO(datafile, 'r') as xfa_stream: + # Import data from XFA into PDF form fields + form.set_xfa_data(xfa_stream) + + # Save updated PDF + form.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all import form data examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Import Data from XML", import_xml_to_pdf_fields, "sample_form.xml"), + ("Import Data from FDF", import_fdf_to_pdf_form, "sample_form.fdf"), + ("Import Data from XFDF", import_data_from_xfdf, "sample_form.xfdf"), + ("Import Values from JSON", import_json_to_pdf_form, "sample_form.json"), + ("Replace XFA Data", replace_xfa_data, "sample_form_xfa.xml"), + ] + + for name, func, data_file_name in examples: + try: + if (func.__name__ == "replace_xfa_data"): + input_file_name = path.join(input_dir, "sample_xfa_form.pdf") + else: + input_file_name = path.join(input_dir, "sample_form_new.pdf") + form_data_file_name = path.join(input_dir, data_file_name) + output_file_name = path.join(output_dir, f"{func.__name__}_out.pdf") + func(input_file_name, form_data_file_name, output_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll Import Form Data examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_form/managing-pdf-form-fields.py b/examples/facades_form/managing-pdf-form-fields.py new file mode 100644 index 0000000..7824c87 --- /dev/null +++ b/examples/facades_form/managing-pdf-form-fields.py @@ -0,0 +1,100 @@ +# Flatten Specific Fields +# ├── Flatten All Fields +# └── Rename Form Fields + +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Flatten specific fields +def flatten_specific_fields(infile, outfile): + """Flatten specific fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Flatten specific fields by their names + fields_to_flatten = ["First Name", "Last Name"] + for field_name in fields_to_flatten: + pdf_form.flatten_field(field_name) + + # Save updated PDF + pdf_form.save(outfile) + +# Flatten all fields +def flatten_all_fields(infile, outfile): + """Flatten all fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Flatten all fields in the PDF document + pdf_form.flatten_all_fields() + + # Save updated PDF + pdf_form.save(outfile) + +# Rename form fields +def rename_form_fields(infile, outfile): + """Rename form fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Rename form fields by providing a mapping of old names to new names + field_renaming_map = [ + ("First Name", "NewFirstName"), + ("Last Name", "NewLastName") + ] + for old_name, new_name in field_renaming_map: + pdf_form.rename_field(old_name, new_name) + + # Save updated PDF + pdf_form.save(outfile) + +def run_all_examples(data_dir=None, license_path=None): + """Run all import form data examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Flatten Specific Fields", flatten_specific_fields), + ("Flatten All Fields", flatten_all_fields), + ("Rename Form Fields", rename_form_fields) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, "sample_form.pdf") + output_file_name = path.join(output_dir, f"{func.__name__}_out.pdf") + func(input_file_name, output_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll managing PDF form fields examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_form/reading-and-inspecting-form-data.py b/examples/facades_form/reading-and-inspecting-form-data.py new file mode 100644 index 0000000..f4dd4d2 --- /dev/null +++ b/examples/facades_form/reading-and-inspecting-form-data.py @@ -0,0 +1,145 @@ +# ├── Get Field Values +# ├── Get Rich Text Values +# ├── Get Radio Button Options +# └── Resolve Full Field Names + +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Get field values +def get_field_values(infile): + """Get field values from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get field values by their names + field_names = ["First Name", "Last Name"] + for field_name in field_names: + value = pdf_form.get_field(field_name) + print(f"Value of '{field_name}': {value}") + + +# Get rich text values +def get_rich_text_values(infile): + """Get rich text values from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get rich text values by their names + field_names = ["Summary"] + for field_name in field_names: + rich_text_value = pdf_form.get_rich_text(field_name) + print(f"Rich text value of '{field_name}': {rich_text_value}") + + +# Get radio button options +def get_radio_button_options(infile): + """Get radio button options from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get radio button options by their names + field_names = ["WorkType"] + for field_name in field_names: + options = pdf_form.get_button_option_current_value(field_name) + print(f"Options for '{field_name}': {options}") + + +# Resolve full field names +def resolve_full_field_names(infile): + """Resolve full field names in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Resolve full field names + for field in pdf_form.field_names: + name= pdf_form.get_full_field_name(field) + print(f"Full field name: {name}") + +# Get required field names +def get_required_field_names(infile): + """Get required field names from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get required field names + for field in pdf_form.field_names: + if pdf_form.is_required_field(field): + print(f"Required field: {field}") + +#get field facades +def get_field_facades(infile): + """Get field facades from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get field facades + for field in pdf_form.field_names: + facade = pdf_form.get_field_facade(field) + print(f"Field facade for '{field}': {facade.box.location}, {facade.box.size}") + print(f"Field facade for '{field}': {facade.font.name}, {facade.font_size}") + + + +def run_all_examples(data_dir=None, license_path=None): + """Run all import form data examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + set_license(license_path) + input_dir, _ = initialize_data_dir(data_dir) + + examples = [ + ("Get Field Values", get_field_values), + ("Get Rich Text Values", get_rich_text_values), + ("Get Radio Button Options", get_radio_button_options), + ("Resolve Full Field Names", resolve_full_field_names), + ("Get Required Field Names", get_required_field_names), + ("Get Field Facades", get_field_facades) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, f"{func.__name__}_in.pdf") + func(input_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll managing PDF form fields examples finished.") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_form/working_with_button_fields.py b/examples/facades_form/working_with_button_fields.py new file mode 100644 index 0000000..015168b --- /dev/null +++ b/examples/facades_form/working_with_button_fields.py @@ -0,0 +1,73 @@ +# Working with Button Fields and Images +# └── Add Image Appearance to Button Fields + +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Add image appearance to button fields +def add_image_appearance_to_button_fields(infile, outfile): + """Add image appearance to button fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Add image appearance to button fields by providing the field name and image stream + image_path = infile.replace(".pdf", ".jpg") + with open(image_path, "rb") as image_stream: + pdf_form.fill_image_field("Image1_af_image", image_stream) + + # Save updated PDF + pdf_form.save(outfile) + +def get_submit_flags(infile, outfile): + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + flags=pdf_form.get_submit_flags("Submit1_af_submit") + + print(f"Submit flags: {flags}") + +def run_all_examples(data_dir=None, license_path=None): + """Run all import form data examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Image Appearance to Button Fields", add_image_appearance_to_button_fields), + ("Get Submit Flags", get_submit_flags) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, "sample_form_image.pdf") + output_file_name = path.join(output_dir, f"{func.__name__}_out.pdf") + func(input_file_name, output_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll managing PDF form fields examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_formeditor/adding_scripts_and_submit_actions.py b/examples/facades_formeditor/adding_scripts_and_submit_actions.py new file mode 100644 index 0000000..7a2cb4e --- /dev/null +++ b/examples/facades_formeditor/adding_scripts_and_submit_actions.py @@ -0,0 +1,123 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +def add_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set JavaScript action for the field + form_editor.set_field_script("Script_Demo_Button", "app.alert('Script 1 has been executed');") + + # Add JavaScript action to the field + form_editor.add_field_script("Script_Demo_Button", "app.alert('Script 2 has been executed');") + + # Save output PDF file + form_editor.save(output_file_name) + +def set_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Add JavaScript action to the field + form_editor.add_field_script("Script_Demo_Button", "app.alert('Script 1 has been executed');") + + # Set JavaScript action for the field + form_editor.set_field_script("Script_Demo_Button", "app.alert('Script 2 has been executed');") + + # Save output PDF file + form_editor.save(output_file_name) + +def remove_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Remove JavaScript action from the field + form_editor.remove_field_action("Script_Demo_Button") + + # Save output PDF file + form_editor.save(output_file_name) + +def set_submit_flag(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set submit flag for the form + form_editor.set_submit_flag("Script_Demo_Button", ap.facades.SubmitFormFlag.XFDF) + + # Save output PDF file + form_editor.save(output_file_name) + +def set_submit_url(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Set license + set_license() + + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set submit URL for the button + if not form_editor.set_submit_url("Script_Demo_Button", "http://www.example.com/submit"): + raise Exception("Failed to set submit URL") + + # Save output PDF file + form_editor.save(output_file_name) + +def run_all_examples(data_dir=None, license_path=None): + """Run all examples for adding scripts and submit actions with status reporting. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Field Script", add_field_script), + ("Set Field Script", set_field_script), + ("Remove Field Script", remove_field_script), + ("Set Submit Flag", set_submit_flag), + ("Set Submit URL", set_submit_url), + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, func.__name__ + ".pdf") + output_file_name = path.join(output_dir, func.__name__ + ".pdf") + func(input_file_name, output_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll Modifying Form Fields examples finished.") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_formeditor/creating-form-field.py b/examples/facades_formeditor/creating-form-field.py new file mode 100644 index 0000000..bfbb9a0 --- /dev/null +++ b/examples/facades_formeditor/creating-form-field.py @@ -0,0 +1,106 @@ +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +def create_checkbox_field(infile, outfile): + """Create CheckBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add CheckBox field to PDF form + pdf_form_editor.add_field(pdf_facades.FieldType.CHECK_BOX, "checkbox1", "Check Box 1", 1, 240, 498, 256, 514) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) + +def create_combobox_field(infile, outfile): + """Create ComboBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add ComboBox field to PDF form + pdf_form_editor.add_field(pdf_facades.FieldType.COMBO_BOX, "combobox1", "Australia", 1, 230, 498, 350, 514) + pdf_form_editor.add_list_item("combobox1", ["Australia","Australia"]) + pdf_form_editor.add_list_item("combobox1", ["New Zealand","New Zealand"]) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) + +def create_textbox_field(infile, outfile): + """Create TextBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add TextBox field to PDF form + pdf_form_editor.add_field(pdf_facades.FieldType.TEXT, "first_name", "Alexander", 1, 50, 570, 150, 590) + pdf_form_editor.add_field(pdf_facades.FieldType.TEXT, "last_name", "Smith", 1, 235, 570, 330, 590) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) + +def create_radiobutton_field(infile, outfile): + """Create RadioButton field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add RadioButton field to PDF form + pdf_form_editor.items = ["Australia", "New Zealand", "Malaysia"]; + pdf_form_editor.add_field(pdf_facades.FieldType.RADIO, "radiobutton1", "Malaysia", 1, 240, 498, 256, 514) + + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) + +def create_listbox_field(infile, outfile): + """Create ListBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add ListBox field to PDF form + pdf_form_editor.items = ["Australia", "New Zealand", "Malaysia"]; + pdf_form_editor.add_field(pdf_facades.FieldType.LIST_BOX, "listbox1", "Australia", 1, 230, 398, 350, 514) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) + +def create_submit_button(infile, outfile): + """Create Submit Button in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add Submit Button to PDF form + pdf_form_editor.add_submit_btn("submitbtn1", 1, "Submit Button", "http://example.com/submit", 100, 450, 200, 470) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) + +def run_all_examples(data_dir=None, license_path=None): + """Run all TextBox field examples with status reporting.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Create TextBox Field", create_textbox_field), + ("Create CheckBox Field", create_checkbox_field), + ("Create ComboBox Field", create_combobox_field), + ("Create RadioButton Field", create_radiobutton_field), + ("Create ListBox Field", create_listbox_field), + ("Create Submit Button", create_submit_button), + ] + + for name, func in examples: + try: + infile = path.join(input_dir, "sample_empty.pdf") + outfile = path.join(output_dir, func.__name__ + ".pdf") + func(infile, outfile) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_formeditor/customizing-field-appearance.py b/examples/facades_formeditor/customizing-field-appearance.py new file mode 100644 index 0000000..d6d910d --- /dev/null +++ b/examples/facades_formeditor/customizing-field-appearance.py @@ -0,0 +1,173 @@ +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def decorate_field(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + form_editor.facade = pdf_facades.FormFieldFacade() + form_editor.facade.background_color = ap_pydrawing.Color.red + form_editor.facade.text_color = ap_pydrawing.Color.blue + form_editor.facade.border_color = ap_pydrawing.Color.green + form_editor.facade.alignment = pdf_facades.FormFieldFacade.ALIGN_CENTER + form_editor.decorate_field("First Name") + + # Save updated document + form_editor.save(outfile) + + +def set_field_alignment(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field alignment to center + if (form_editor.set_field_alignment( + "First Name", pdf_facades.FormFieldFacade.ALIGN_CENTER + )): + # Save updated document + form_editor.save(outfile) + else: + raise Exception("Failed to set field alignment. Field may not support alignment.") + + +def set_field_alignment_vertical(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field vertical alignment to top + if form_editor.set_field_alignment_v( + "First Name", pdf_facades.FormFieldFacade.ALIGN_BOTTOM + ): + # Save updated document + form_editor.save(outfile) + else: + raise Exception("Failed to set field vertical alignment. Field may not support vertical alignment.") + +def set_field_appearance(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field appearance to invisible + if not form_editor.set_field_appearance("First Name", ap.annotations.AnnotationFlags.INVISIBLE): + raise Exception("Failed to set field appearance. Field may not support appearance flags.") + + # Save updated document + form_editor.save(outfile) + + +def set_field_attribute(infile, outfile): + # # Open document + # doc = ap.Document(infile) + + # # Create FormEditor object + # form_editor = pdf_facades.FormEditor(doc) + + # # Set field attribute to "ReadOnly" + # if not form_editor.set_field_attribute("Country", pdf_facades.PropertyFlags.READ_ONLY): + # raise Exception("Failed to set field attribute. Field may not support specified attribute.") + + # Save updated document + # form_editor.save(outfile) + pass + + +def set_field_comb_number(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field comb number to 5 + form_editor.set_field_comb_number("PIN", 5) + + # Save updated document + form_editor.save(outfile) + + +def set_field_limit(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field limit to 10 + if not form_editor.set_field_limit("Last Name", 10): + raise Exception("Failed to set field limit. Field may not support specified limit.") + + # Save updated document + form_editor.save(outfile) + + +def get_field_appearance(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Get field appearance + appearance = form_editor.get_field_appearance("Last Name") + print("Field Appearance: " + str(appearance)) + + +def run_all_examples(data_dir=None, license_path=None): + """ + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Decorate Field", decorate_field), + ("Set Field Alignment", set_field_alignment), + ("Set Field Alignment Vertical", set_field_alignment_vertical), + ("Set Field Appearance", set_field_appearance), + ("Set Field Attribute", set_field_attribute), + ("Set Field Comb Number", set_field_comb_number), + ("Set Field Limit", set_field_limit), + ("Get Field Appearance", get_field_appearance), + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, f"{func.__name__}.pdf") + output_file_name = path.join(output_dir, f"{func.__name__}.pdf") + func(input_file_name, output_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll Modifying Form Fields examples finished.") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_formeditor/modifying-form-fields.py b/examples/facades_formeditor/modifying-form-fields.py new file mode 100644 index 0000000..d51fc24 --- /dev/null +++ b/examples/facades_formeditor/modifying-form-fields.py @@ -0,0 +1,131 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_list_item(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Add list item to list box field + form_editor.add_list_item("Country", ["New Zealand","New Zealand"]) + # Save updated document + form_editor.save(outfile) + + +def del_list_item(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Delete list item from list box field + form_editor.del_list_item("Country", "UK") + # Save updated document + form_editor.save(outfile) + + +def move_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Move field to new page + form_editor.move_field("Country", 200, 600, 280, 620) + # Save updated document + form_editor.save(outfile) + + +def remove_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Remove field from document + form_editor.remove_field("Country") + # Save updated document + form_editor.save(outfile) + + +def rename_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Rename field in document + form_editor.rename_field("City", "Town") + # Save updated document + form_editor.save(outfile) + + +def single2multiple(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Change a single-lined text field to a multiple-lined one + form_editor.single_2_multiple("City") + # Save updated document + form_editor.save(outfile) + + +def copy_inner_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Copies an existing field to a new position specified by both page number and ordinates. + # A new document will be produced, which contains everything the source document has except for the newly copied field. + form_editor.copy_inner_field("First Name", "First Name Copy", 2, 200, 600) + # Save updated document + form_editor.save(outfile) + +def copy_outer_field(infile, outfile): + # Since copy_outer_field() method needs to copy field from source document to target document, we need to create a new document as target document first. + doc = ap.Document() + doc.pages.add() + doc.save(outfile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(outfile) + # Copies an existing field to a new position specified by both page number and ordinates. + # A new document will be produced, which contains everything the source document has except for the newly copied field. + form_editor.copy_outer_field(infile, "First Name", 1, 200, 600) + # Save updated document + form_editor.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all form field modification examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add List Item", add_list_item), + ("Delete List Item", del_list_item), + ("Move Field", move_field), + ("Remove Field", remove_field), + ("Rename Field", rename_field), + ("Single to Multiple", single2multiple), + ("Copy Inner Field", copy_inner_field), + ("Copy Outer Field", copy_outer_field), + ] + + for name, func in examples: + try: + func(path.join(input_dir, f"{func.__name__}.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_content_editor/annotations.py b/examples/facades_pdf_content_editor/annotations.py new file mode 100644 index 0000000..0e556fe --- /dev/null +++ b/examples/facades_pdf_content_editor/annotations.py @@ -0,0 +1,98 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +def add_text_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add text annotation to page 1 + content_editor.create_text(apd.Rectangle(100, 400, 50, 50), "Text Annotation", "This is a text annotation", True, "Insert", 1) + # Save updated document + content_editor.save(outfile) + +def add_free_text_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add free text annotation to page 1 + content_editor.create_free_text(apd.Rectangle(200, 480, 150, 25), "This is a free text annotation", 1) + # Save updated document + content_editor.save(outfile) + +def add_caret_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add caret annotation to page 1 + content_editor.create_caret(1, + apd.Rectangle(350, 400, 10, 10), + apd.Rectangle(300, 380, 115, 15), + "P", "This is a caret annotation", + apd.Color.red) + # Save updated document + content_editor.save(outfile) + +def add_markup_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add markup annotation to page 1 + content_editor.create_markup(apd.Rectangle(120, 440, 200, 20), "This is a highlight annotation", 0, 1, apd.Color.yellow) + content_editor.create_markup(apd.Rectangle(110, 542, 200, 20), "This is a underline annotation", 1, 1, apd.Color.yellow) + content_editor.create_markup(apd.Rectangle(120, 568, 200, 20), "This is a strikeout annotation", 2, 1, apd.Color.orange_red) + content_editor.create_markup(apd.Rectangle(110, 598, 200, 20), "This is a squiggly annotation", 3, 1, apd.Color.dark_blue) + # Save updated document + content_editor.save(outfile) + + +def add_popup_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add popup annotation to page 1 + content_editor.create_popup( + apd.Rectangle(220, 520, 180, 80), + "This is a popup annotation", + True, + 1, + ) + # Save updated document + content_editor.save(outfile) + +def run_all_examples(data_dir=None, license_path=None): + """Run all form field modification examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Text Annotation", add_text_annotation), + ("Add Free Text Annotation", add_free_text_annotation), + ("Add Caret Annotation", add_caret_annotation), + ("Add Markup Annotation", add_markup_annotation), + ("Add Popup Annotation", add_popup_annotation), + ] + + for name, func in examples: + try: + func(path.join(input_dir, "sample.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() + diff --git a/examples/facades_pdf_content_editor/attachments.py b/examples/facades_pdf_content_editor/attachments.py new file mode 100644 index 0000000..0dafc84 --- /dev/null +++ b/examples/facades_pdf_content_editor/attachments.py @@ -0,0 +1,125 @@ +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +def add_attachment(infile, attachment_file ,outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add attachment to page 1 + with open(attachment_file, "rb") as attachment_stream: + content_editor.add_document_attachment( + attachment_stream, + path.basename(attachment_file), + "This is a sample attachment for demonstration purposes.", + ) + # Save updated document + content_editor.save(outfile) + + +def add_attachment_from_path(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add attachment using file-path overload + content_editor.add_document_attachment( + attachment_file, + "Attachment added using file path overload.", + ) + # Save updated document + content_editor.save(outfile) + + +def add_file_attachment_annotation(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Create file attachment annotation on page 1 + content_editor.create_file_attachment( + apd.Rectangle(100, 520, 20, 20), + "Attachment annotation contents", + attachment_file, + 1, + "PushPin", + ) + # Save updated document + content_editor.save(outfile) + + +def add_file_attachment_annotation_from_stream(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + with open(attachment_file, "rb") as source_stream: + attachment_stream = BytesIO(source_stream.read()) + + # Create file attachment annotation using stream+opacity overload + content_editor.create_file_attachment( + apd.Rectangle(130, 520, 20, 20), + "Attachment annotation from stream", + attachment_stream, + path.basename(attachment_file), + 1, + "Tag", + 0.75, + ) + # Save updated document + content_editor.save(outfile) + +def remove_attachments(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Remove all attachments from document + content_editor.delete_attachments() + # Save updated document + content_editor.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all form field modification examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Attachment", add_attachment, True), + ("Add Attachment From Path", add_attachment_from_path, True), + ("Add File Attachment Annotation", add_file_attachment_annotation, True), + ( + "Add File Attachment Annotation From Stream", + add_file_attachment_annotation_from_stream, + True, + ), + ("Remove Attachments", remove_attachments, False), + ] + + input_pdf = path.join(input_dir, "sample.pdf") + attachment_file = path.join(input_dir, "SampleAttachment.txt") + + for name, func, needs_attachment in examples: + try: + if needs_attachment: + func(input_pdf, + attachment_file, + path.join(output_dir, f"{func.__name__}.pdf")) + else: + func(input_pdf, + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_content_editor/binding-and-streams.py b/examples/facades_pdf_content_editor/binding-and-streams.py new file mode 100644 index 0000000..c71f67b --- /dev/null +++ b/examples/facades_pdf_content_editor/binding-and-streams.py @@ -0,0 +1,76 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def constructor_with_document_and_save_stream(infile, outfile): + # Initialize PdfContentEditor using constructor overload that accepts Document + document = ap.Document(infile) + content_editor = pdf_facades.PdfContentEditor(document) + + # Save to memory stream using save(stream) overload, then persist to file + output_stream = BytesIO() + content_editor.save(output_stream) + with open(outfile, "wb") as target_stream: + target_stream.write(output_stream.getvalue()) + + content_editor.close() + + +def bind_from_stream_and_save_stream(infile, outfile): + # Create editor and bind PDF from in-memory stream + content_editor = pdf_facades.PdfContentEditor() + with open(infile, "rb") as source_stream: + input_stream = BytesIO(source_stream.read()) + content_editor.bind_pdf(input_stream) + + # Save through stream overload to demonstrate bind(stream) + save(stream) + output_stream = BytesIO() + content_editor.save(output_stream) + with open(outfile, "wb") as target_stream: + target_stream.write(output_stream.getvalue()) + + content_editor.close() + + +def bind_from_document_and_save_file(infile, outfile): + # Create editor and bind from Document overload + source_document = ap.Document(infile) + content_editor = pdf_facades.PdfContentEditor() + content_editor.bind_pdf(source_document) + + # Save to file-path overload + content_editor.save(outfile) + content_editor.close() + + +def run_all_examples(data_dir=None, license_path=None): + """Run PdfContentEditor binding and stream overload examples.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Constructor With Document And Save Stream", constructor_with_document_and_save_stream), + ("Bind From Stream And Save Stream", bind_from_stream_and_save_stream), + ("Bind From Document And Save File", bind_from_document_and_save_file), + ] + + for name, func in examples: + try: + func( + path.join(input_dir, "sample.pdf"), + path.join(output_dir, f"{func.__name__}.pdf"), + ) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_content_editor/document-actions.py b/examples/facades_pdf_content_editor/document-actions.py new file mode 100644 index 0000000..4831651 --- /dev/null +++ b/examples/facades_pdf_content_editor/document-actions.py @@ -0,0 +1,77 @@ +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_bookmark_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a bookmark action to navigate to page 1 + content_editor.create_bookmarks_action( + "PdfContentEditor Bookmark", + apd.Color.blue, + True, + False, + "", + "GoTo", + "1", + ) + # Save updated document + content_editor.save(outfile) + + +def add_document_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add JavaScript action for document open event + content_editor.add_document_additional_action( + content_editor.DOCUMENT_OPEN, + "app.alert('Document opened with PdfContentEditor action');", + ) + # Save updated document + content_editor.save(outfile) + + +def remove_open_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Remove open action from the document + content_editor.remove_document_open_action() + # Save updated document + content_editor.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all document action examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Bookmark Action", add_bookmark_action), + ("Add Document Action", add_document_action), + ("Remove Open Action", remove_open_action), + ] + + for name, func in examples: + try: + func(path.join(input_dir, f"{func.__name__}.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() + diff --git a/examples/facades_pdf_content_editor/drawing-annotations.py b/examples/facades_pdf_content_editor/drawing-annotations.py new file mode 100644 index 0000000..947fbb4 --- /dev/null +++ b/examples/facades_pdf_content_editor/drawing-annotations.py @@ -0,0 +1,146 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Drawing Annotations +# Line +# Square and Circle +# Polygon +# Polyline +# Curve + +def add_line_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create LineAnnotation object + rect = apd.Rectangle(100, 100, 200, 200) + contents = "This is line annotation" + content_editor.create_line(rect, contents, 100, 100, 200, 200, 1, 1, apd.Color.red, "Solid", [3,2], ["Square"]) + + # Save output PDF file + content_editor.save(outfile) + +def add_square_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create SquareAnnotation object + rect = apd.Rectangle(100, 300, 200, 400) + contents = "This is square annotation" + content_editor.create_square_circle(rect, contents, apd.Color.blue, True, 1, 3) + + # Save output PDF file + content_editor.save(outfile) + +def add_circle_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create CircleAnnotation object + rect = apd.Rectangle(300, 300, 400, 400) + contents = "This is circle annotation" + content_editor.create_square_circle(rect, contents, apd.Color.blue, False, 1, 3) + + # Save output PDF file + content_editor.save(outfile) + + +def add_polygon_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 0 # 0 - Solid + line_info.vertice_coordinate = [100, 200, 150, 260, 220, 220, 200, 160] + content_editor.create_polygon( + line_info, + 1, + apd.Rectangle(90, 150, 150, 120), + "This is polygon annotation", + ) + + # Save output PDF file + content_editor.save(outfile) + + +def add_polyline_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 0 # 0 - Solid + line_info.vertice_coordinate = [120, 420, 180, 460, 230, 430, 290, 470] + content_editor.create_poly_line( + line_info, + 1, + apd.Rectangle(110, 410, 200, 90), + "This is polyline annotation", + ) + + # Save output PDF file + content_editor.save(outfile) + + +def add_curve_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 1 # 1 - Dashed + line_info.vertice_coordinate = [120, 520, 160, 560, 220, 540, 280, 580] + line_info.visibility = True + content_editor.draw_curve( + line_info, + 1, + apd.Rectangle(110, 510, 220, 100), + "This is curve annotation", + ) + + # Save output PDF file + content_editor.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all form field modification examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Line Annotation", add_line_annotation), + ("Square Annotation", add_square_annotation), + ("Circle Annotation", add_circle_annotation), + ("Polygon Annotation", add_polygon_annotation), + ("Polyline Annotation", add_polyline_annotation), + ("Curve Annotation", add_curve_annotation), + ] + + for name, func in examples: + try: + func(path.join(input_dir, "sample.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_content_editor/images.py b/examples/facades_pdf_content_editor/images.py new file mode 100644 index 0000000..13b8771 --- /dev/null +++ b/examples/facades_pdf_content_editor/images.py @@ -0,0 +1,72 @@ +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_image(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace image on page 1 + content_editor.replace_image(1, 1, image_file) + # Save updated document + content_editor.save(outfile) + + +def delete_images(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Delete image on page 1 + content_editor.delete_image(1, [2]) + # Save updated document + content_editor.save(outfile) + + +def delete_all_image(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Delete all images from the document + content_editor.delete_image() + # Save updated document + content_editor.save(outfile) + + +def run_examples(data_dir=None, license_path=None): + """Run all form field modification examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Replace Image", replace_image), + ("Delete Image", delete_images), + ("Delete All Images", delete_all_image), + ] + + for name, func in examples: + try: + if func.__name__ == "replace_image": + func( + path.join(input_dir, f"{func.__name__}.pdf"), + path.join(input_dir, "replacement_image.jpg"), + path.join(output_dir, f"{func.__name__}.pdf"), + ) + else: + func( + path.join(input_dir, f"{func.__name__}.pdf"), + path.join(output_dir, f"{func.__name__}.pdf"), + ) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + +if __name__ == "__main__": + run_examples() diff --git a/examples/facades_pdf_content_editor/link-and-navigation.py b/examples/facades_pdf_content_editor/link-and-navigation.py new file mode 100644 index 0000000..833d2c2 --- /dev/null +++ b/examples/facades_pdf_content_editor/link-and-navigation.py @@ -0,0 +1,166 @@ +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_web_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a web link annotation to page 1 + content_editor.create_web_link( + apd.Rectangle(100, 650, 200, 20), + "https://products.aspose.com/pdf/python-net/", + 1, + apd.Color.blue, + ) + # Save updated document + content_editor.save(outfile) + + +def add_local_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a local link on page 1 to destination page 1 + content_editor.create_local_link( + apd.Rectangle(120, 620, 220, 20), + 1, + 1, + apd.Color.red, + ) + # Save updated document + content_editor.save(outfile) + + +def add_pdf_document_link(infile, linked_pdf, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add link to another PDF document + content_editor.create_pdf_document_link( + apd.Rectangle(140, 590, 240, 20), + linked_pdf, + 1, + 1, + apd.Color.green, + ) + # Save updated document + content_editor.save(outfile) + + +def add_javascript_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add JavaScript link action + content_editor.create_java_script_link( + "app.alert('PdfContentEditor JavaScript link');", + apd.Rectangle(160, 560, 260, 20), + 1, + apd.Color.orange, + ) + # Save updated document + content_editor.save(outfile) + + +def add_application_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add application launch link + content_editor.create_application_link( + apd.Rectangle(180, 530, 260, 20), + "notepad.exe", + 1, + apd.Color.purple, + ) + # Save updated document + content_editor.save(outfile) + + +def add_custom_action_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add custom action link. Empty action list keeps the sample runnable + # without requiring additional enum lookups. + content_editor.create_custom_action_link( + apd.Rectangle(200, 500, 260, 20), + 1, + apd.Color.dark_red, + [], + ) + # Save updated document + content_editor.save(outfile) + + +def extract_links(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Extract links from the document + links = content_editor.extract_link() + + count = 0 + for link in links: + count += 1 + print(f"Link {count}: {link.rect}") + if is_assignable(link, ap.annotations.LinkAnnotation): + annotation = cast(ap.annotations.LinkAnnotation, link) + if is_assignable(annotation.action, ap.annotations.GoToURIAction): + action = cast(ap.annotations.GoToURIAction, annotation.action) + print(f" URI: {action.uri}") + + if count == 0: + print("No links found") + + +def run_all_examples(data_dir=None, license_path=None): + """Run all link and navigation examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Web Link", add_web_link), + ("Add Local Link", add_local_link), + ("Add PDF Document Link", add_pdf_document_link), + ("Add JavaScript Link", add_javascript_link), + ("Add Application Link", add_application_link), + ("Add Custom Action Link", add_custom_action_link), + ("Extract Links", extract_links), + ] + + for name, func in examples: + try: + if func.__name__ == "add_pdf_document_link": + func(path.join(input_dir, "sample.pdf"), + path.join(input_dir, "linked_document.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + elif func.__name__ == "extract_links": + func(path.join(input_dir, "sample_links.pdf")) + else: + func(path.join(input_dir, "sample.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_content_editor/multimedia.py b/examples/facades_pdf_content_editor/multimedia.py new file mode 100644 index 0000000..8a6ef5d --- /dev/null +++ b/examples/facades_pdf_content_editor/multimedia.py @@ -0,0 +1,60 @@ +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_movie_annotation(infile, movie_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add movie annotation to page 1 + content_editor.create_movie(apd.Rectangle(80, 500, 220, 120), movie_file, 1) + # Save updated document + content_editor.save(outfile) + + +def add_sound_annotation(infile, sound_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add sound annotation to page 1 + content_editor.create_sound(apd.Rectangle(80, 450, 30, 30), sound_file, "Speaker", 1, "8000") + # Save updated document + content_editor.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all multimedia examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Movie Annotation", add_movie_annotation), + ("Add Sound Annotation", add_sound_annotation), + ] + + for name, func in examples: + try: + if func.__name__ == "add_movie_annotation": + func(path.join(input_dir, "sample.pdf"), + path.join(input_dir, "sample_video.avi"), + path.join(output_dir, f"{func.__name__}.pdf")) + else: + func(path.join(input_dir, "sample.pdf"), + path.join(input_dir, "sample_audio.wav"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() + diff --git a/examples/facades_pdf_content_editor/stamps.py b/examples/facades_pdf_content_editor/stamps.py new file mode 100644 index 0000000..a7508ef --- /dev/null +++ b/examples/facades_pdf_content_editor/stamps.py @@ -0,0 +1,271 @@ +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_rubber_stamp(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + for i in range(1, 5): + content_editor.create_rubber_stamp( + i, + apd.Rectangle(120, 450, 180, 60), + "Approved", + "Approved by reviewer", + apd.Color.green, + ) + # Save updated document + content_editor.save(outfile) + + +def delete_stamp_by_index(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + content_editor.delete_stamp(1, [2,3]) + # Save updated document + content_editor.save(outfile) + + +def manage_stamp_by_id(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(200, 380, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 480, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + # Apply ID-based stamp operations + content_editor.hide_stamp_by_id(1, 1) + content_editor.show_stamp_by_id(1, 2) + + # Save updated document + content_editor.save(outfile) + + +def delete_stamp_by_ids_examples(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + # Create two stamps on page 1 so they can be deleted by ID + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(120, 320, 180, 60), + "Draft", + "Delete by single ID", + apd.Color.orange, + ) + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(120, 250, 180, 60), + "Draft", + "Delete by multiple IDs", + apd.Color.orange, + ) + + # Delete by single ID overload and by IDs overload + content_editor.delete_stamp_by_id(1, 1) + content_editor.delete_stamp_by_ids(1, [2]) + + # Save updated document + content_editor.save(outfile) + + +def move_stamp_by_index(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 380, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 480, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + content_editor.save(outfile) + + # Move first stamp on page 1 by index + # content_editor.move_stamp(1, 1, 10, 10) + # Save updated document + content_editor.save(outfile) + + +def move_stamp_by_id_example(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(300, 420, 180, 60), + "Approved", + "Move this stamp by ID", + apd.Color.green, + ) + + # Move stamp by ID overload + content_editor.move_stamp_by_id(1, 1, 240, 360) + + # Save updated document + content_editor.save(outfile) + + +def create_rubber_stamp_with_appearance_file(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Create rubber stamp using appearance_file overload (image path) + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(100, 400, 200, 60), + "Stamp with custom appearance", + apd.Color.dark_green, + image_file, + ) + # Save updated document + content_editor.save(outfile) + + +def create_rubber_stamp_with_appearance_stream(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Read image into an in-memory stream + with open(image_file, "rb") as src: + appearance_stream = BytesIO(src.read()) + # Create rubber stamp using appearance_stream overload + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(100, 320, 200, 60), + "Stamp with appearance stream", + apd.Color.dark_green, + appearance_stream, + ) + # Save updated document + content_editor.save(outfile) + + +def delete_stamps_globally(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + # Add stamps across multiple pages so global deletion is meaningful + for page in range(1, 5): + content_editor.create_rubber_stamp( + page, + apd.Rectangle(120, 500, 180, 60), + "Draft", + "Stamp for global deletion", + apd.Color.gray, + ) + + # delete_stamp_by_id without page number removes stamp ID from all pages + content_editor.delete_stamp_by_id(1) + # delete_stamp_by_ids without page number removes a list of IDs from all pages + content_editor.delete_stamp_by_ids([2, 3]) + + # Save updated document + content_editor.save(outfile) + + +def list_stamps(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # List all stamps on page 1 + stamps = content_editor.get_stamps(1) + + count = 0 + for stamp in stamps: + count += 1 + print(f"Stamp {count}: {stamp}") + + if count == 0: + print("No stamps found") + + +def run_all_examples(data_dir=None, license_path=None): + """Run all stamp examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Rubber Stamp", add_rubber_stamp), + ("Delete Stamp By Index", delete_stamp_by_index), + ("Manage Stamp By ID", manage_stamp_by_id), + ("Delete Stamp By IDs", delete_stamp_by_ids_examples), + ("Move Stamp By Index", move_stamp_by_index), + ("Move Stamp By ID", move_stamp_by_id_example), + ("Create Rubber Stamp With Appearance File", create_rubber_stamp_with_appearance_file), + ("Create Rubber Stamp With Appearance Stream", create_rubber_stamp_with_appearance_stream), + ("Delete Stamps Globally", delete_stamps_globally), + ("List Stamps", list_stamps), + ] + + image_file = path.join(input_dir, "replacement_image.jpg") + + for name, func in examples: + try: + if func.__name__ == "list_stamps": + func(path.join(input_dir, f"{func.__name__}.pdf")) + elif func.__name__ in ( + "create_rubber_stamp_with_appearance_file", + "create_rubber_stamp_with_appearance_stream", + ): + func( + path.join(input_dir, "sample4pages.pdf"), + image_file, + path.join(output_dir, f"{func.__name__}.pdf"), + ) + else: + func(path.join(input_dir, f"sample4pages.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_content_editor/text-editing.py b/examples/facades_pdf_content_editor/text-editing.py new file mode 100644 index 0000000..86feef2 --- /dev/null +++ b/examples/facades_pdf_content_editor/text-editing.py @@ -0,0 +1,108 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_simple(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text in the whole document + content_editor.replace_text_strategy.replace_scope = pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + content_editor.replace_text("33", "XXXIII ") + # Save updated document + content_editor.save(outfile) + +def replace_text_regex(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text in the whole document + content_editor.replace_text_strategy.replace_scope = pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + content_editor.replace_text_strategy.is_regular_expression_used = True + content_editor.replace_text(r"\d{4}", "[NUMBER]") + # Save updated document + content_editor.save(outfile) + +def replace_text_on_page(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text on page 1 + content_editor.replace_text_strategy.replace_scope = pdf_facades.ReplaceTextStrategy.Scope.REPLACE_FIRST + content_editor.replace_text("PDF", "Page 1 Replaced Text", 14) + # Save updated document + content_editor.save(outfile) + +def replace_text_with_state(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.blue + text_state.font_size = 14 + + # Replace text with explicit text formatting + content_editor.replace_text_strategy.replace_scope = pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + content_editor.replace_text("software", "SOFTWARE", text_state) + # Save updated document + content_editor.save(outfile) + + +def replace_text_on_page_with_state(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.red + text_state.font_size = 12 + + # Replace text on a specific page with explicit text formatting + content_editor.replace_text_strategy.replace_scope = pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + content_editor.replace_text("software", 1, "SOFTWARE PAGE 1", text_state) + # Save updated document + content_editor.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all text editing examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Replace Text Simple", replace_text_simple), + ("Replace Text Regex", replace_text_regex), + ("Replace Text On Page", replace_text_on_page), + ("Replace Text With State", replace_text_with_state), + ("Replace Text On Page With State", replace_text_on_page_with_state), + ] + + for name, func in examples: + try: + if func.__name__ == "replace_text_on_page_with_state": + func( + path.join(input_dir, "replace_text_with_state.pdf"), + path.join(output_dir, f"{func.__name__}.pdf"), + ) + else: + func(path.join(input_dir, f"{func.__name__}.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_content_editor/viewer-preferences.py b/examples/facades_pdf_content_editor/viewer-preferences.py new file mode 100644 index 0000000..2e9c2c7 --- /dev/null +++ b/examples/facades_pdf_content_editor/viewer-preferences.py @@ -0,0 +1,100 @@ +import aspose.pdf.facades as pdf_facades +import sys +from enum import IntFlag +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +class ViewerPreference(IntFlag): + """Bit flags for PDF viewer preferences.""" + + PAGE_LAYOUT_SINGLE_PAGE = 1 + PAGE_LAYOUT_ONE_COLUMN = 2 + PAGE_LAYOUT_TWO_COLUMN_LEFT = 4 + PAGE_LAYOUT_TWO_COLUMN_RIGHT = 8 + + PAGE_MODE_USE_NONE = 16 + PAGE_MODE_USE_OUTLINES = 32 + PAGE_MODE_USE_THUMBS = 64 + PAGE_MODE_FULL_SCREEN = 128 + + HIDE_TOOLBAR = 256 + HIDE_MENUBAR = 512 + HIDE_WINDOW_UI = 1024 + FIT_WINDOW = 2048 + CENTER_WINDOW = 4096 + + NON_FULL_SCREEN_PAGE_MODE_USE_NONE = 8192 + NON_FULL_SCREEN_PAGE_MODE_USE_OUTLINES = 16384 + NON_FULL_SCREEN_PAGE_MODE_USE_THUMBS = 32768 + + DIRECTION_L2R = 65536 + DIRECTION_R2L = 131072 + + DISPLAY_DOC_TITLE = 262144 + NON_FULL_SCREEN_PAGE_MODE_USE_OC = 524288 + PAGE_MODE_USE_OC = 1048576 + PAGE_MODE_USE_ATTACHMENT = 2097152 + + SIMPLEX = 4194304 + DUPLEX_FLIP_SHORT_EDGE = 8388608 + DUPLEX_FLIP_LONG_EDGE = 16777216 + PRINT_SCALING_APP_DEFAULT = 1 << 25 + PRINT_SCALING_NONE = 1 << 26 + PICK_TRAY_BY_PDF_SIZE = 1 << 27 + + + +def get_viewer_preferences(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Read current viewer preference flags + viewer_preference = ViewerPreference(content_editor.get_viewer_preference()) + if viewer_preference & ViewerPreference.PAGE_MODE_USE_OUTLINES: + print("PageModeUseOutlines is enabled") + print(f"Current viewer preference: {viewer_preference}") + + +def change_viewer_preferences(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + current_preference = ViewerPreference(content_editor.get_viewer_preference()) + # Toggle one low-order flag to demonstrate viewer preference update + updated_preference = current_preference | ViewerPreference.PAGE_LAYOUT_SINGLE_PAGE + content_editor.change_viewer_preference(int(updated_preference)) + + # Save updated document + content_editor.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all viewer preference examples and report status.""" + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Get Viewer Preferences", get_viewer_preferences), + ("Change Viewer Preferences", change_viewer_preferences), + ] + + for name, func in examples: + try: + if func.__name__ == "get_viewer_preferences": + func(path.join(input_dir, f"{func.__name__}.pdf")) + else: + func(path.join(input_dir, f"{func.__name__}.pdf"), + path.join(output_dir, f"{func.__name__}.pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_file_editor/booklet-and-nup-layout.py b/examples/facades_pdf_file_editor/booklet-and-nup-layout.py new file mode 100644 index 0000000..03c3267 --- /dev/null +++ b/examples/facades_pdf_file_editor/booklet-and-nup-layout.py @@ -0,0 +1,78 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Create PDF Booklet +def create_pdf_booklet(infile, outfile): + # Create BookletMaker object + booklet_maker = pdf_facades.PdfFileEditor() + # Make booklet from input PDF file and save to output PDF file + booklet_maker.make_booklet(FileIO(infile), FileIO(outfile, "w")) + +def try_create_pdf_booklet(infile, outfile): + # Create BookletMaker object + booklet_maker = pdf_facades.PdfFileEditor() + # Make booklet from input PDF file and save to output PDF file + # The try_make_booklet method is like the make_booklet method, + # except the try_make_booklet method does not throw an exception if the operation fails. + if not booklet_maker.try_make_booklet(FileIO(infile), FileIO(outfile, "w")): + print("Failed to create booklet.") + + +# Create N-Up PDF Document +def create_nup_pdf_document(infile, outfile): + # Create NUpMaker object + nup_maker = pdf_facades.PdfFileEditor() + # Make N-Up layout from input PDF file and save to output PDF file + nup_maker.make_n_up(FileIO(infile), FileIO(outfile, "w"), 2, 2) # 2 rows and 2 columns for N-Up layout + +# Create N-Up PDF Document +def try_create_nup_pdf_document(infile, outfile): + # Create NUpMaker object + nup_maker = pdf_facades.PdfFileEditor() + # Make N-Up layout from input PDF file and save to output PDF file + if not nup_maker.try_make_n_up(FileIO(infile), FileIO(outfile, "w"), 2, 2): + print("Failed to create N-Up PDF document.") + +def run_all_examples(data_dir=None, license_path=None): + """Run all booklet and N-Up layout examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + + ("Create PDF Booklet", create_pdf_booklet), + ("Create N-Up PDF Document", create_nup_pdf_document), + ("Try Create PDF Booklet", try_create_pdf_booklet), + ("Try Create N-Up PDF Document", try_create_nup_pdf_document) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, func.__name__ + ".pdf") + output_file_name = path.join(output_dir, func.__name__ + ".pdf") + func(input_file_name, output_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll booklet and N-Up layout examples finished.\n") + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_file_editor/merge-pdf-documents.py b/examples/facades_pdf_file_editor/merge-pdf-documents.py new file mode 100644 index 0000000..020481c --- /dev/null +++ b/examples/facades_pdf_file_editor/merge-pdf-documents.py @@ -0,0 +1 @@ +#─ Concatenate or Merge PDF Files \ No newline at end of file diff --git a/examples/facades_pdf_file_editor/page-layout-and-margins.py b/examples/facades_pdf_file_editor/page-layout-and-margins.py new file mode 100644 index 0000000..c389c09 --- /dev/null +++ b/examples/facades_pdf_file_editor/page-layout-and-margins.py @@ -0,0 +1,92 @@ +# Page Layout & Margins +# ─ Add Margins to PDF Pages +# ─ Resize PDF Page Contents +# ─ Add Page Breaks in PDF + +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Add Margins to PDF Pages +def add_margins_to_pdf_pages(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + # Define the margins to be added (in points) + left_margin = 36 # 0.5 inch + right_margin = 36 # 0.5 inch + top_margin = 36 # 0.5 inch + bottom_margin = 36 # 0.5 inch + + pdf_editor.add_margins( + infile, outfile, [1, 3], left_margin, right_margin, top_margin, bottom_margin + ) + + +# Resize PDF Page Contents +def resize_pdf_page_contents(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + if not pdf_editor.resize_contents( + FileIO(infile), FileIO(outfile, "w"), [1, 3], 400, 750 + ): + raise Exception("Failed to resize PDF page contents.") + + +# Add Page Breaks in PDF +def add_page_breaks_in_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.add_page_break( + infile, + outfile, + [ + pdf_facades.PdfFileEditor.PageBreak(1, 400), + ], + ) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all page layout and margins examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Add Margins to PDF Pages", add_margins_to_pdf_pages), + ("Resize PDF Page Contents", resize_pdf_page_contents), + ( + "Add Page Breaks in PDF", + add_page_breaks_in_pdf, + ), + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, func.__name__ + ".pdf") + output_file_name = path.join(output_dir, func.__name__ + ".pdf") + func(input_file_name, output_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll page layout and margins examples finished.") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_file_editor/page-managment.py b/examples/facades_pdf_file_editor/page-managment.py new file mode 100644 index 0000000..4783866 --- /dev/null +++ b/examples/facades_pdf_file_editor/page-managment.py @@ -0,0 +1,97 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +# Extract Pages from PDF +def extract_pages_from_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page numbers to be extracted (1-based index) + pages_to_extract = [1, 4, 3] + + # Extract the specified pages from the PDF document and save to a new PDF document + pdf_editor.extract(infile, pages_to_extract, outfile) + + +# Delete Pages from PDF +def delete_pages_from_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page numbers to be deleted (1-based index) + pages_to_delete = [2, 4] + + # Delete the specified pages from the PDF document + pdf_editor.delete(infile, pages_to_delete, outfile) + + +# Insert Pages into PDF +def insert_pages_into_pdf(infile, sample_file, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page number where new pages will be inserted (1-based index) + insert_page_number = 2 + + pdf_editor.insert(infile, insert_page_number, sample_file, [1, 2], outfile) + + +# Append Pages to PDF +def append_pages_to_pdf(infile, sample_file, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + # Append pages from the specified PDF document to the end of the source PDF document + pdf_editor.append(infile, [sample_file], 1, 2, outfile) + +def run_all_examples(data_dir=None, license_path=None): + """Run all page management examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Insert Pages into PDF", insert_pages_into_pdf), + ("Append Pages to PDF", append_pages_to_pdf), + ("Extract Pages from PDF", extract_pages_from_pdf), + ("Delete Pages from PDF", delete_pages_from_pdf), + ] + + for name, func in examples: + input_file_name = path.join(input_dir, func.__name__ + ".pdf") + output_file_name = path.join(output_dir, func.__name__ + ".pdf") + try: + if ( + func.__name__ == "insert_pages_into_pdf" + or func.__name__ == "append_pages_to_pdf" + ): + func( + input_file_name, + path.join(input_dir, "sample_data.pdf"), + output_file_name, + ) + else: + func(input_file_name, output_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll page management examples finished.") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_file_editor/page-merging.py b/examples/facades_pdf_file_editor/page-merging.py new file mode 100644 index 0000000..8d9d502 --- /dev/null +++ b/examples/facades_pdf_file_editor/page-merging.py @@ -0,0 +1,95 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + +def concatenate_two_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.concatenate(files_to_merge[0], files_to_merge[1], output_file) + +def concatenate_pdf_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.concatenate(files_to_merge, output_file) + + +def try_concatenate_two_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + if not pdf_editor.try_concatenate(files_to_merge[0], files_to_merge[1], output_file): + print("Concatenation failed for the provided files.") + +def try_concatenate_pdf_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + if not pdf_editor.try_concatenate(files_to_merge, output_file): + print("Concatenation failed for the provided files.") + +def concatenate_large_number_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.use_disk_buffer = True # Enable disk buffering for large files + pdf_editor.concatenate(files_to_merge, output_file) + +def concatenate_pdf_files_with_optimization(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.optimize_size = True # Enable optimization for smaller output file size + pdf_editor.concatenate(files_to_merge, output_file) + +def concatenate_pdf_forms(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.unique_suffix = "_xy_%NUM%" # Set a unique suffix to avoid form field name conflicts + pdf_editor.concatenate(files_to_merge, output_file) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all page management examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Concatenate Two PDF Files", concatenate_two_files), + ("Concatenate Multiple PDF Files", concatenate_pdf_files), + ("Try Concatenate Two PDF Files", try_concatenate_two_files), + ("Try Concatenate Multiple PDF Files", try_concatenate_pdf_files), + ("Concatenate Large Number of PDF Files", concatenate_large_number_files), + ("Concatenate PDF Files with Optimization", concatenate_pdf_files_with_optimization), + ("Concatenate PDF Forms with Unique Suffix", concatenate_pdf_forms) + ] + + input_files = ["merge_1.pdf", "merge_2.pdf", "merge_3.pdf"] # Example input files + form_files = ["form1.pdf", "form2.pdf"] # Example form files for concatenation + pdf_files_to_merge = [path.join(input_dir, file) for file in input_files] + form_files_to_merge = [path.join(input_dir, file) for file in form_files] + + for name, func in examples: + try: + if "Form" in name: + func(form_files_to_merge, path.join(output_dir, func.__name__ + ".pdf")) + else: + func(pdf_files_to_merge, path.join(output_dir, func.__name__ + ".pdf")) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll page management examples finished.") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_file_editor/splitting-pdf-documents.py b/examples/facades_pdf_file_editor/splitting-pdf-documents.py new file mode 100644 index 0000000..70a44e1 --- /dev/null +++ b/examples/facades_pdf_file_editor/splitting-pdf-documents.py @@ -0,0 +1,62 @@ +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Split PDF from Beginning +def split_pdf_from_beginning(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_from_first(input_pdf_path, 3, output_pdf_path) + +# Split PDF to End +def split_pdf_to_end(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_to_end(input_pdf_path, 2, output_pdf_path) + +# Split PDF into Single Pages +def split_pdf_into_single_pages(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_to_pages(input_pdf_path, output_pdf_path) + +def run_all_examples(data_dir=None, license_path=None): + """Run all page splitting examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Split PDF from Beginning", split_pdf_from_beginning), + ("Split PDF to End", split_pdf_to_end), + ("Split PDF into Single Pages", split_pdf_into_single_pages) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, func.__name__ + ".pdf") + if func.__name__ == "split_pdf_into_single_pages": + output_file_name = path.join(output_dir, func.__name__ + "_%NUM%.pdf") + else: + output_file_name = path.join(output_dir, func.__name__ + ".pdf") + func(input_file_name, output_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll page splitting examples finished.") + + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_file_info/document-properties.py b/examples/facades_pdf_file_info/document-properties.py new file mode 100644 index 0000000..f50dc56 --- /dev/null +++ b/examples/facades_pdf_file_info/document-properties.py @@ -0,0 +1,67 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir +# Document Properties +# │ ├─ Get PDF Version +# │ └─ Get Document Privileges + +def get_pdf_version(input_file_name): + + pdf_metadata = pdf_facades.PdfFileInfo(input_file_name) + version = pdf_metadata.get_pdf_version() + print(f"\nPDF Version: {version}") + +def get_document_privileges(input_file_name): + pdf_metadata = pdf_facades.PdfFileInfo(input_file_name) + + privileges = pdf_metadata.get_document_privilege() + + print("Document Privileges:") + print(f" Can Print: {privileges.allow_print}") + print(f" Can Degraded Print: {privileges.allow_degraded_printing}") + print(f" Can Copy: {privileges.allow_copy}") + print(f" Can Modify Contents: {privileges.allow_modify_contents}") + print(f" Can Modify Annotations: {privileges.allow_modify_annotations}") + print(f" Can Fill In: {privileges.allow_fill_in}") + print(f" Can Screen Readers: {privileges.allow_screen_readers}") + print(f" Can Assembly: {privileges.allow_assembly}") + + +def run_all_examples(data_dir=None, license_path=None): + """Run all PDF metadata examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Get PDF Version", get_pdf_version), + ("Get Document Privileges", get_document_privileges) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, "sample.pdf") + func(input_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll PDF metadata examples finished.\n") + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_file_info/page-information.py b/examples/facades_pdf_file_info/page-information.py new file mode 100644 index 0000000..7d9c60e --- /dev/null +++ b/examples/facades_pdf_file_info/page-information.py @@ -0,0 +1,64 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +def get_page_information(infile): + + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + page_width = pdf_info.get_page_width(1) + page_height = pdf_info.get_page_height(1) + page_rotation = pdf_info.get_page_rotation(1) + page_x_offset = pdf_info.get_page_x_offset(1) + page_y_offset = pdf_info.get_page_y_offset(1) + + print(f"Page Width: {page_width}") + print(f"Page Height: {page_height}") + print(f"Page Rotation: {page_rotation}") + +def get_page_offsets(infile): + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + page_x_offset = pdf_info.get_page_x_offset(1)/72.0 + page_y_offset = pdf_info.get_page_y_offset(1)/72.0 + print(f"Page X Offset: {page_x_offset} inches") + print(f"Page Y Offset: {page_y_offset} inches") + +def run_all_examples(data_dir=None, license_path=None): + """Run all PDF metadata examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Get Page Information", get_page_information, "sample2.pdf"), + ("Get Page Offsets", get_page_offsets, "sample3.pdf") + ] + + for name, func, file_name in examples: + try: + input_file_name = path.join(input_dir, file_name) + func(input_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll PDF metadata examples finished.\n") + +if __name__ == "__main__": + run_all_examples() diff --git a/examples/facades_pdf_file_info/pdf-metadata.py b/examples/facades_pdf_file_info/pdf-metadata.py new file mode 100644 index 0000000..9c146b3 --- /dev/null +++ b/examples/facades_pdf_file_info/pdf-metadata.py @@ -0,0 +1,120 @@ +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir +# PDF Metadata +# ├─ Get PDF Metadata +# ├─ Set PDF Metadata +# ├─ Clear PDF Metadata +# └─ Save Metadata with XMP + +def get_pdf_metadata(infile): + + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + print(f"Subject: {pdf_info.subject}") + print(f"Title: {pdf_info.title}") + print(f"Keywords: {pdf_info.keywords}") + print(f"Creator: {pdf_info.creator}") + print(f"Creation Date: {pdf_info.creation_date}") + print(f"Modification Date: {pdf_info.mod_date}") + + # Check PDF status + print(f"Is Valid PDF: {pdf_info.is_pdf_file}") + print(f"Is Encrypted: {pdf_info.is_encrypted}") + print(f"Has Open Password: {pdf_info.has_open_password}") + print(f"Has Edit Password: {pdf_info.has_edit_password}") + print(f"Is Portfolio: {pdf_info.has_collection}") + + # Retrieve and display a specific custom attribute + reviewer = pdf_info.get_meta_info("Reviewer") + print(f"Reviewer: {reviewer if reviewer else 'No Reviewer metadata found.'}") + +def set_pdf_metadata(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Set PDF metadata + pdf_info.subject = "Aspose PDF for Python via .NET" + pdf_info.title = "Aspose PDF for Python via .NET" + pdf_info.keywords = "Aspose, PDF, Python, .NET" + pdf_info.creator = "Aspose Team" + + pdf_info.set_meta_info("CustomKey", "CustomValue") + + # pdf_info.save_new_info(outfile) + # Is obsolete, use save() method instead + + # Save updated metadata + pdf_info.save(outfile) + +def clear_pdf_metadata(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Clear PDF metadata + pdf_info.clear_info() + + # Save updated metadata + pdf_info.save(outfile) + +def save_info_with_xmp(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Set PDF metadata + pdf_info.subject = "Aspose PDF for Python via .NET" + pdf_info.title = "Aspose PDF for Python via .NET" + pdf_info.keywords = "Aspose, PDF, Python, .NET" + pdf_info.creator = "Aspose Team" + + # Save updated metadata + pdf_info.save_new_info_with_xmp(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all PDF metadata examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Get PDF Metadata", get_pdf_metadata), + ("Set PDF Metadata", set_pdf_metadata), + ("Clear PDF Metadata", clear_pdf_metadata), + ("Save Metadata with XMP", save_info_with_xmp) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, "sample.pdf") + output_file_name = path.join(output_dir, func.__name__ + ".pdf") + if func.__name__ == "get_pdf_metadata": + func(input_file_name) + else: + func(input_file_name, output_file_name) + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll PDF metadata examples finished.\n") + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_file_security/change-password.py b/examples/facades_pdf_file_security/change-password.py new file mode 100644 index 0000000..5c4a7f3 --- /dev/null +++ b/examples/facades_pdf_file_security/change-password.py @@ -0,0 +1,119 @@ +# Change User and Owner Password +# ├── Change User and Owner Password +# ├── Change Password and Reset Security +# └── Try Change Password Without Exception + +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Change User and Owner Password +def change_user_and_owner_password(infile, outfile): + """Change user and owner passwords while keeping existing security settings.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Change passwords + file_security.change_password( + "owner_password", + "new_user_password", + "new_owner_password" + ) + + # Save updated PDF + file_security.save(outfile) + + +# Change Password and Reset Security +def change_password_and_reset_security(infile, outfile): + """Change passwords and reset document security settings.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define new privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Change passwords and reset security + file_security.change_password( + "owner_password", + "new_user_password", + "new_owner_password", + privilege, + pdf_facades.KeySize.X128 + ) + + # Save updated PDF + file_security.save(outfile) + + +# Try Change Password Without Exception +def try_change_password_without_exception(infile, outfile): + """Attempt to change passwords without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Attempt to change passwords + result = file_security.try_change_password( + "owner_password", + "new_user_password", + "new_owner_password" + ) + + # Save only if operation succeeded + if result: + file_security.save(outfile) + else: + print("Password change failed. Check owner password or document security.") + + +def run_all_examples(data_dir=None, license_path=None): + """Run all change password examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Change User and Owner Password", change_user_and_owner_password), + ("Change Password and Reset Security", change_password_and_reset_security), + ("Try Change Password Without Exception", try_change_password_without_exception) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, "secured.pdf") + output_file_name = path.join(output_dir, f"{func.__name__}_out.pdf") + func(input_file_name, output_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll change password examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_file_security/decrypt-pdf.py b/examples/facades_pdf_file_security/decrypt-pdf.py new file mode 100644 index 0000000..d1bde96 --- /dev/null +++ b/examples/facades_pdf_file_security/decrypt-pdf.py @@ -0,0 +1,79 @@ +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Decrypt PDF with Owner Password +def decrypt_pdf_with_owner_password(infile, outfile): + """Decrypt a PDF document using the owner password.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Decrypt the PDF + file_security.decrypt_file("owner_password") + + # Save decrypted PDF + file_security.save(outfile) + + +# Try Decrypt PDF Without Exception +def try_decrypt_pdf_without_exception(infile, outfile): + """Attempt to decrypt a PDF without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Attempt to decrypt the PDF + result = file_security.try_decrypt_file("owner_password") + + # Save only if decryption was successful + if result: + file_security.save(outfile) + else: + print("Decryption failed. Check password or document security.") + + +def run_all_examples(data_dir=None, license_path=None): + """Run all decrypt PDF examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Decrypt PDF with Owner Password", decrypt_pdf_with_owner_password), + ("Try Decrypt PDF Without Exception", try_decrypt_pdf_without_exception) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, "encrypted.pdf") + output_file_name = path.join(output_dir, f"{func.__name__}_out.pdf") + func(input_file_name, output_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll decrypt PDF examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_file_security/encrypt-pdf.py b/examples/facades_pdf_file_security/encrypt-pdf.py new file mode 100644 index 0000000..bbbc822 --- /dev/null +++ b/examples/facades_pdf_file_security/encrypt-pdf.py @@ -0,0 +1,121 @@ +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + +# Encrypt PDF with User and Owner Password +def encrypt_pdf_with_user_owner_password(infile, outfile): + """Encrypt a PDF document using user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define document privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Encrypt the PDF + file_security.encrypt_file( + "user_password", + "owner_password", + privilege, + pdf_facades.KeySize.X128 + ) + + # Save encrypted PDF + file_security.save(outfile) + + +# Encrypt PDF with Permissions +def encrypt_pdf_with_permissions(infile, outfile): + """Encrypt a PDF document and configure specific permissions.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Configure privileges + privilege = pdf_facades.DocumentPrivilege.allow_all + privilege.allow_print = False + privilege.allow_copy = False + + # Encrypt the PDF + file_security.encrypt_file( + "user_password", + "owner_password", + privilege, + pdf_facades.KeySize.X128 + ) + + # Save encrypted PDF + file_security.save(outfile) + + +# Encrypt PDF with Encryption Algorithm +def encrypt_pdf_with_encryption_algorithm(infile, outfile): + """Encrypt a PDF document using a specific encryption algorithm.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Encrypt the PDF using AES algorithm + file_security.encrypt_file( + "user_password", + "owner_password", + privilege, + pdf_facades.KeySize.X256, + pdf_facades.Algorithm.AES + ) + + # Save encrypted PDF + file_security.save(outfile) + + +def run_all_examples(data_dir=None, license_path=None): + """Run all encrypt PDF examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Encrypt PDF with User and Owner Password", encrypt_pdf_with_user_owner_password), + ("Encrypt PDF with Permissions", encrypt_pdf_with_permissions), + ("Encrypt PDF with Encryption Algorithm", encrypt_pdf_with_encryption_algorithm) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, "sample.pdf") + output_file_name = path.join(output_dir, f"{func.__name__}_out.pdf") + func(input_file_name, output_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll encrypt PDF examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_file_security/set-privileges.py b/examples/facades_pdf_file_security/set-privileges.py new file mode 100644 index 0000000..5cf1791 --- /dev/null +++ b/examples/facades_pdf_file_security/set-privileges.py @@ -0,0 +1,117 @@ +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Set PDF Privileges Without Passwords +def set_pdf_privileges_without_passwords(infile, outfile): + """Set PDF privileges without specifying user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Apply privileges (owner password will be generated automatically) + file_security.set_privilege(privilege) + + # Save updated PDF + file_security.save(outfile) + + +# Set PDF Privileges with User and Owner Passwords +def set_pdf_privileges_with_passwords(infile, outfile): + """Set PDF privileges using user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + privilege.allow_copy = False + + # Apply privileges with passwords + file_security.set_privilege( + "user_password", + "owner_password", + privilege + ) + + # Save updated PDF + file_security.save(outfile) + + +# Try Set PDF Privileges Without Exception +def try_set_pdf_privileges_without_exception(infile, outfile): + """Attempt to set PDF privileges without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Attempt to apply privileges + result = file_security.try_set_privilege( + "user_password", + "owner_password", + privilege + ) + + # Save only if operation succeeded + if result: + file_security.save(outfile) + else: + print("Setting privileges failed. Check passwords or document state.") + + +def run_all_examples(data_dir=None, license_path=None): + """Run all set PDF privileges examples and report status. + + Args: + data_dir (str, optional): Input/output directory override. + license_path (str, optional): Path to Aspose.PDF license file. + + Returns: + None + """ + set_license(license_path) + input_dir, output_dir = initialize_data_dir(data_dir) + + examples = [ + ("Set PDF Privileges Without Passwords", set_pdf_privileges_without_passwords), + ("Set PDF Privileges with User and Owner Passwords", set_pdf_privileges_with_passwords), + ("Try Set PDF Privileges Without Exception", try_set_pdf_privileges_without_exception) + ] + + for name, func in examples: + try: + input_file_name = path.join(input_dir, "sample.pdf") + output_file_name = path.join(output_dir, f"{func.__name__}_out.pdf") + func(input_file_name, output_file_name) + + print(f"✅ Success: {name}") + except Exception as e: + print(f"❌ Failed: {name} - {str(e)}") + + print("\nAll set PDF privileges examples finished.") + + +if __name__ == "__main__": + run_all_examples() \ No newline at end of file diff --git a/examples/facades_pdf_file_signature/add-signature-in-pdf-file_1.py b/examples/facades_pdf_file_signature/add-signature-in-pdf-file_1.py new file mode 100644 index 0000000..e71fe51 --- /dev/null +++ b/examples/facades_pdf_file_signature/add-signature-in-pdf-file_1.py @@ -0,0 +1,39 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\add-signature-in-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import ( + PdfFileSignature, + PKCS7Detached, + Rectangle +) + +def add_signature_to_pdf(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "input.pdf" + output_pdf = data_dir + "SignedOutput.pdf" + cert_file = data_dir + "certificate.pfx" + cert_password = "your_cert_password" + + # Create PdfFileSignature object + pdf_sign = PdfFileSignature() + + # Bind PDF document (input & output) + pdf_sign.bind_pdf(input_pdf, output_pdf) + + # Define signature placement (page 1, rectangle coordinates) + sig_rect = Rectangle(100, 500, 300, 650) + + # Create PKCS7Detached signature using certificate + signature = PKCS7Detached(cert_file, cert_password) + + # Optionally set signature appearance + pdf_sign.signature_appearance = data_dir + "signature_image.jpg" + + # Sign the PDF + pdf_sign.sign(1, cert_file, cert_password, "Reason for signing", "Contact", "Location", sig_rect, signature) + + # Save the signed document + pdf_sign.save() diff --git a/examples/facades_pdf_file_signature/add-signature-in-pdf-file_2.py b/examples/facades_pdf_file_signature/add-signature-in-pdf-file_2.py new file mode 100644 index 0000000..921e252 --- /dev/null +++ b/examples/facades_pdf_file_signature/add-signature-in-pdf-file_2.py @@ -0,0 +1,59 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\add-signature-in-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature +from aspose.pdf.forms import PKCS1 +from aspose.pdf import Rectangle + +def add_two_signatures(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "input.pdf" + cert_file = data_dir + "rsa_cert.pfx" + cert_password = "12345" + + # Create PdfFileSignature object + pdf_signature = PdfFileSignature() + + # ========================= + # First signature + # ========================= + pdf_signature.bind_pdf(input_pdf) + + rect1 = Rectangle(10, 10, 300, 50) + signature1 = PKCS1(cert_file, cert_password) + + pdf_signature.sign( + 1, + "I'm document author", + "test@aspose-pdf-demo.local", + "Aspose Pdf Demo, Australia", + True, + rect1, + signature1 + ) + + first_signed_pdf = data_dir + "DigitallySign_out.pdf" + pdf_signature.save(first_signed_pdf) + + # ========================= + # Second signature + # ========================= + pdf_signature.bind_pdf(first_signed_pdf) + + rect2 = Rectangle(10, 10, 300, 50) + signature2 = PKCS1(cert_file, cert_password) + + pdf_signature.sign( + 2, + "I'm document reviewer", + "test02@aspose-pdf-demo.local", + "Aspose Pdf Demo, Australia", + True, + rect2, + signature2 + ) + + pdf_signature.save(data_dir + "DigitallySign2_out.pdf") diff --git a/examples/facades_pdf_file_signature/add-signature-in-pdf-file_3.py b/examples/facades_pdf_file_signature/add-signature-in-pdf-file_3.py new file mode 100644 index 0000000..09f730d --- /dev/null +++ b/examples/facades_pdf_file_signature/add-signature-in-pdf-file_3.py @@ -0,0 +1,35 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\add-signature-in-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature +from aspose.pdf.forms import PKCS1, SignatureCustomAppearance + +def add_pdf_file_signature_field(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "input.pdf" + output_pdf = data_dir + "DigitallySign_out.pdf" + cert_file = data_dir + "rsa_cert.pfx" + cert_password = "12345" + + pdf_signature = PdfFileSignature() + + # Bind PDF document + pdf_signature.bind_pdf(input_pdf) + + # Create PKCS#1 signature with custom appearance + signature = PKCS1(cert_file, cert_password) + signature.reason = "Sign as Author" + + appearance = SignatureCustomAppearance() + appearance.font_size = 6 + appearance.font_family_name = "Calibri" + signature.custom_appearance = appearance + + # Sign PDF using a named signature field + pdf_signature.sign("Signature1", signature) + + # Save signed PDF + pdf_signature.save(output_pdf) diff --git a/examples/facades_pdf_file_signature/add-signature-in-pdf-file_4.py b/examples/facades_pdf_file_signature/add-signature-in-pdf-file_4.py new file mode 100644 index 0000000..ee8a3d8 --- /dev/null +++ b/examples/facades_pdf_file_signature/add-signature-in-pdf-file_4.py @@ -0,0 +1,47 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\add-signature-in-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature +from aspose.pdf.forms import PKCS1, SignatureCustomAppearance + +def add_pdf_file_signature_field2(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "input.pdf" + cert_file = data_dir + "rsa_cert.pfx" + cert_password = "12345" + + pdf_signature = PdfFileSignature() + + # ========================= + # First signature field + # ========================= + pdf_signature.bind_pdf(input_pdf) + + signature1 = PKCS1(cert_file, cert_password) + signature1.reason = "Sign as Author" + + appearance1 = SignatureCustomAppearance() + appearance1.font_size = 6 + signature1.custom_appearance = appearance1 + + pdf_signature.sign("Signature1", signature1) + first_signed_pdf = data_dir + "DigitallySign_out.pdf" + pdf_signature.save(first_signed_pdf) + + # ========================= + # Second signature field + # ========================= + pdf_signature.bind_pdf(first_signed_pdf) + + signature2 = PKCS1(cert_file, cert_password) + signature2.reason = "Sign as Reviewer" + + appearance2 = SignatureCustomAppearance() + appearance2.font_size = 6 + signature2.custom_appearance = appearance2 + + pdf_signature.sign("Signature2", signature2) + pdf_signature.save(data_dir + "DigitallySign2_out.pdf") diff --git a/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_1.py b/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_1.py new file mode 100644 index 0000000..ad93809 --- /dev/null +++ b/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_1.py @@ -0,0 +1,28 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\remove-signature-from-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature + +def remove_signature(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "signed_rsa.pdf" + output_pdf = data_dir + "RemoveSignature_out.pdf" + + pdf_signature = PdfFileSignature() + + # Bind PDF document + pdf_signature.bind_pdf(input_pdf) + + # Get list of signature names + signature_names = pdf_signature.get_sign_names() + + # Remove all signatures + for name in signature_names: + print(f"Removed {name}") + pdf_signature.remove_signature(name) + + # Save PDF without signatures + pdf_signature.save(output_pdf) diff --git a/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_2.py b/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_2.py new file mode 100644 index 0000000..a5a047d --- /dev/null +++ b/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_2.py @@ -0,0 +1,23 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\remove-signature-from-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature + +def remove_signature_but_keep_field(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "signed_rsa.pdf" + output_pdf = data_dir + "RemoveSignature_out.pdf" + + pdf_signature = PdfFileSignature() + + # Bind PDF document + pdf_signature.bind_pdf(input_pdf) + + # Remove signature but keep the signature field + pdf_signature.remove_signature("Signature1", False) + + # Save updated PDF + pdf_signature.save(output_pdf) diff --git a/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_3.py b/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_3.py new file mode 100644 index 0000000..fbe3af5 --- /dev/null +++ b/examples/facades_pdf_file_signature/remove-signature-from-pdf-file_3.py @@ -0,0 +1,27 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\remove-signature-from-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature + +def remove_signature_but_keep_field2(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "signed_rsa.pdf" + output_pdf = data_dir + "RemoveSignature_out.pdf" + + pdf_signature = PdfFileSignature() + + # Bind PDF document + pdf_signature.bind_pdf(input_pdf) + + # Get all signature field names + signature_names = pdf_signature.get_signature_names() + + # Remove signatures but keep fields + for sig_name in signature_names: + pdf_signature.remove_signature(sig_name, False) + + # Save updated PDF + pdf_signature.save(output_pdf) diff --git a/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_1.py b/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_1.py new file mode 100644 index 0000000..82b8eb2 --- /dev/null +++ b/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_1.py @@ -0,0 +1,20 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\verify-signature-in-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature + +def is_pdf_signed(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "signed_rsa.pdf" + + pdf_signature = PdfFileSignature() + + # Bind PDF document + pdf_signature.bind_pdf(input_pdf) + + # Check if the document contains any signatures + if pdf_signature.contains_signature(): + print("Document Signed") diff --git a/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_2.py b/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_2.py new file mode 100644 index 0000000..136d2eb --- /dev/null +++ b/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_2.py @@ -0,0 +1,20 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\verify-signature-in-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature + +def is_pdf_signed_with_given_signature(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "signed_rsa.pdf" + + pdf_signature = PdfFileSignature() + + # Bind PDF document + pdf_signature.bind_pdf(input_pdf) + + # Verify specific signature field + if pdf_signature.verify_signature("Signature1"): + print("PDF Signed") diff --git a/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_3.py b/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_3.py new file mode 100644 index 0000000..1416cd5 --- /dev/null +++ b/examples/facades_pdf_file_signature/verify-signature-in-pdf-file_3.py @@ -0,0 +1,20 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\verify-signature-in-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature + +def is_pdf_signature_valid(): + data_dir = RunExamples.get_data_dir_aspose_pdf_security_signatures() + + input_pdf = data_dir + "signed_rsa.pdf" + + pdf_signature = PdfFileSignature() + + # Bind PDF document + pdf_signature.bind_pdf(input_pdf) + + # Verify the specified signature + if pdf_signature.verify_signature("Signature1"): + print("Signature Verified") diff --git a/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_1.py b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_1.py new file mode 100644 index 0000000..aed0fd0 --- /dev/null +++ b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_1.py @@ -0,0 +1,22 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\working-with-signature-in-a-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature + +def extract_signature_info(): + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_security_signatures() + + pdf_signature = PdfFileSignature() + pdf_signature.bind_pdf(data_dir + "signed_rsa.pdf") + + signature_names = pdf_signature.get_signature_names() + if signature_names: + sig_name = signature_names[0] + + # Extract certificate as a stream + cer_stream = pdf_signature.extract_certificate(sig_name) + if cer_stream is not None: + with open(data_dir + "extracted_cert.pfx", "wb") as fs: + fs.write(cer_stream.read()) diff --git a/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_2.py b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_2.py new file mode 100644 index 0000000..935ae84 --- /dev/null +++ b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_2.py @@ -0,0 +1,19 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\working-with-signature-in-a-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature + +def extract_signature_image(): + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_security_signatures() + + signature = PdfFileSignature() + signature.bind_pdf(data_dir + "ExtractingImage.pdf") + + if signature.contains_signature(): + for sig_name in signature.get_signature_names(): + image_stream = signature.extract_image(sig_name) + if image_stream: + with open(data_dir + "ExtractedImage_out.jpg", "wb") as fs: + fs.write(image_stream.read()) diff --git a/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_3.py b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_3.py new file mode 100644 index 0000000..d829fd2 --- /dev/null +++ b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_3.py @@ -0,0 +1,29 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\working-with-signature-in-a-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature +from aspose.pdf.forms import PKCS1 +from aspose.pdf import Rectangle + +def suppress_location_and_reason(): + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_security_signatures() + + pdf_signature = PdfFileSignature() + pdf_signature.bind_pdf(data_dir + "input.pdf") + + rect = Rectangle(10, 10, 300, 50) + signature = PKCS1(data_dir + "rsa_cert.pfx", "12345") + + # Suppress reason and location by leaving empty strings + pdf_signature.sign( + 1, + "", # empty reason + "test01@aspose-pdf-demo.local", + "", # empty location + True, + rect, + signature + ) + pdf_signature.save(data_dir + "DigitallySign_out.pdf") diff --git a/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_4.py b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_4.py new file mode 100644 index 0000000..9e80faa --- /dev/null +++ b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_4.py @@ -0,0 +1,26 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\working-with-signature-in-a-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature +from aspose.pdf.forms import PKCS1, SignatureCustomAppearance +from aspose.pdf import Rectangle + +def customize_signature_appearance(): + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_security_signatures() + + pdf_signature = PdfFileSignature() + pdf_signature.bind_pdf(data_dir + "input.pdf") + + rect = Rectangle(10, 10, 300, 50) + signature = PKCS1(data_dir + "rsa_cert.pfx", "12345") + + appearance = SignatureCustomAppearance() + appearance.font_size = 6 + appearance.font_family_name = "Times New Roman" + appearance.digital_signed_label = "Signed by:" + signature.custom_appearance = appearance + + pdf_signature.sign(1, True, rect, signature) + pdf_signature.save(data_dir + "DigitallySign_out.pdf") diff --git a/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_5.py b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_5.py new file mode 100644 index 0000000..486824e --- /dev/null +++ b/examples/facades_pdf_file_signature/working-with-signature-in-a-pdf-file_5.py @@ -0,0 +1,32 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilesignature\working-with-signature-in-a-pdf-file +# Code fence language: python + + +from aspose.pdf.facades import PdfFileSignature +from aspose.pdf.forms import PKCS1, SignatureCustomAppearance +from aspose.pdf import Rectangle + +def signature_with_image(): + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_security_signatures() + image_path = data_dir + "aspose-logo.jpg" + + pdf_signature = PdfFileSignature() + pdf_signature.bind_pdf(data_dir + "input.pdf") + + rect = Rectangle(10, 10, 300, 50) + signature = PKCS1(data_dir + "rsa_cert.pfx", "12345") + + appearance = SignatureCustomAppearance() + appearance.font_size = 6 + appearance.font_family_name = "Times New Roman" + appearance.digital_signed_label = "Signed by:" + appearance.is_foreground_image = True # show image on top + + signature.custom_appearance = appearance + + # Set the appearance image + pdf_signature.signature_appearance = image_path + + pdf_signature.sign(1, True, rect, signature) + pdf_signature.save(data_dir + "DigitallySign_out.pdf") diff --git a/examples/facades_pdf_file_stamp/add-pdf-page-stamp_1.py b/examples/facades_pdf_file_stamp/add-pdf-page-stamp_1.py new file mode 100644 index 0000000..6f7a208 --- /dev/null +++ b/examples/facades_pdf_file_stamp/add-pdf-page-stamp_1.py @@ -0,0 +1,35 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\add-pdf-page-stamp +# Code fence language: python + + +from aspose.pdf.facades import PdfFileStamp, Stamp + +def add_page_stamp_on_all_pages(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + # Create PdfFileStamp object + file_stamp = PdfFileStamp() + + # Bind source PDF document + file_stamp.bind_pdf(data_dir + "SourcePDF.pdf") + + # Create stamp object + stamp = Stamp() + + # Bind PDF page to be used as stamp (page 1) + stamp.bind_pdf(data_dir + "AddPageStampOnAllPages.pdf", 1) + + # Set stamp position and appearance + stamp.set_origin(20, 20) + stamp.rotation = 90.0 + stamp.is_background = True + + # Add stamp to all pages + file_stamp.add_stamp(stamp) + + # Save output PDF + file_stamp.save(data_dir + "PageStampOnAllPages_out.pdf") + + # Close the stamp object + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/add-pdf-page-stamp_2.py b/examples/facades_pdf_file_stamp/add-pdf-page-stamp_2.py new file mode 100644 index 0000000..f25991e --- /dev/null +++ b/examples/facades_pdf_file_stamp/add-pdf-page-stamp_2.py @@ -0,0 +1,38 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\add-pdf-page-stamp +# Code fence language: python + + +from aspose.pdf.facades import PdfFileStamp, Stamp + +def add_page_stamp_on_certain_pages(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + # Create PdfFileStamp object + file_stamp = PdfFileStamp() + + # Bind source PDF document + file_stamp.bind_pdf(data_dir + "SourcePDF.pdf") + + # Create stamp object + stamp = Stamp() + + # Bind PDF page to be used as stamp (page 1) + stamp.bind_pdf(data_dir + "PageStampOnCertainPages.pdf", 1) + + # Configure stamp properties + stamp.set_origin(20, 20) + stamp.rotation = 90.0 + stamp.is_background = True + + # Apply stamp only to selected pages (1 and 3) + stamp.pages = [1, 3] + + # Add stamp to the PDF + file_stamp.add_stamp(stamp) + + # Save output PDF + file_stamp.save(data_dir + "PageStampOnCertainPages_out.pdf") + + # Close the stamp object + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/add-pdf-page-stamp_3.py b/examples/facades_pdf_file_stamp/add-pdf-page-stamp_3.py new file mode 100644 index 0000000..9eb6331 --- /dev/null +++ b/examples/facades_pdf_file_stamp/add-pdf-page-stamp_3.py @@ -0,0 +1,56 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\add-pdf-page-stamp +# Code fence language: python + + +from aspose.pdf.facades import ( + PdfFileStamp, + PdfFileInfo, + FormattedText, + FontStyle, + EncodingType +) +from aspose.pdf.facades import PageNumPosition +from System.Drawing import Color + +def add_page_number_in_pdf_file(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + input_pdf = data_dir + "StampPDF.pdf" + output_pdf = data_dir + "AddPageNumber_out.pdf" + + # Create PdfFileStamp object + file_stamp = PdfFileStamp() + + # Bind PDF document + file_stamp.bind_pdf(input_pdf) + + # Get total number of pages + pdf_info = PdfFileInfo(input_pdf) + total_pages = pdf_info.number_of_pages + + # Create formatted text for page number ("#" is replaced by current page number) + formatted_text = FormattedText( + f"Page # of {total_pages}", + Color.AntiqueWhite, + Color.Gray, + FontStyle.times_bold_italic, + EncodingType.winansi, + False, + 12 + ) + + # Set starting page number + file_stamp.starting_number = 1 + + # Add page number at upper-right position + file_stamp.add_page_number( + formatted_text, + PageNumPosition.pos_upper_right + ) + + # Save output PDF + file_stamp.save(output_pdf) + + # Close the stamp object + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/add-pdf-page-stamp_4.py b/examples/facades_pdf_file_stamp/add-pdf-page-stamp_4.py new file mode 100644 index 0000000..7e7b5f0 --- /dev/null +++ b/examples/facades_pdf_file_stamp/add-pdf-page-stamp_4.py @@ -0,0 +1,61 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\add-pdf-page-stamp +# Code fence language: python + + +from aspose.pdf.facades import ( + PdfFileStamp, + PdfFileInfo, + FormattedText, + FontStyle, + EncodingType, + PageNumPosition +) +from aspose.pdf import NumberingStyle +from System.Drawing import Color + +def add_custom_page_number_in_pdf_file(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + input_pdf = data_dir + "StampPDF.pdf" + output_pdf = data_dir + "AddCustomPageNumber_out.pdf" + + # Create PdfFileStamp object + file_stamp = PdfFileStamp() + + # Bind PDF document + file_stamp.bind_pdf(input_pdf) + + # Get total number of pages + pdf_info = PdfFileInfo(input_pdf) + total_pages = pdf_info.number_of_pages + + # Create formatted text for page number + # "#" will be replaced by the current page number + formatted_text = FormattedText( + f"Page # of {total_pages}", + Color.AntiqueWhite, + Color.Gray, + FontStyle.times_bold_italic, + EncodingType.winansi, + False, + 12 + ) + + # Specify numbering style (Roman numerals, uppercase) + file_stamp.numbering_style = NumberingStyle.numerals_roman_uppercase + + # Set starting page number + file_stamp.starting_number = 1 + + # Add page number in the upper-right corner + file_stamp.add_page_number( + formatted_text, + PageNumPosition.pos_upper_right + ) + + # Save output PDF + file_stamp.save(output_pdf) + + # Close the stamp object + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/add-text-and-image-stamp_1.py b/examples/facades_pdf_file_stamp/add-text-and-image-stamp_1.py new file mode 100644 index 0000000..b743402 --- /dev/null +++ b/examples/facades_pdf_file_stamp/add-text-and-image-stamp_1.py @@ -0,0 +1,51 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\add-text-and-image-stamp +# Code fence language: python + + +from aspose.pdf.facades import ( + PdfFileStamp, + Stamp, + FormattedText, + FontStyle, + EncodingType +) +from System.Drawing import Color + +def add_text_stamp_on_all_pages_in_pdf_file(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + # Create PdfFileStamp object + file_stamp = PdfFileStamp() + + # Bind source PDF document + file_stamp.bind_pdf(data_dir + "sample.pdf") + + # Create stamp object + stamp = Stamp() + + # Create formatted text and bind it as a logo (text stamp) + text = FormattedText( + "Hello World!", + Color.Blue, + Color.Gray, + FontStyle.helvetica, + EncodingType.winansi, + True, + 14 + ) + stamp.bind_logo(text) + + # Configure stamp properties + stamp.set_origin(10, 400) + stamp.rotation = 90.0 + stamp.is_background = True + + # Add stamp to all pages + file_stamp.add_stamp(stamp) + + # Save output PDF + file_stamp.save(data_dir + "AddTextStampOnAllPages_out.pdf") + + # Close the stamp object + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/add-text-and-image-stamp_2.py b/examples/facades_pdf_file_stamp/add-text-and-image-stamp_2.py new file mode 100644 index 0000000..75eda6b --- /dev/null +++ b/examples/facades_pdf_file_stamp/add-text-and-image-stamp_2.py @@ -0,0 +1,54 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\add-text-and-image-stamp +# Code fence language: python + + +from aspose.pdf.facades import ( + PdfFileStamp, + Stamp, + FormattedText, + FontStyle, + EncodingType +) +from System.Drawing import Color + +def add_text_stamp_on_particular_pages_in_pdf_file(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + # Create PdfFileStamp object + file_stamp = PdfFileStamp() + + # Bind source PDF document + file_stamp.bind_pdf(data_dir + "sample.pdf") + + # Create stamp object + stamp = Stamp() + + # Create formatted text and bind it as a logo (text stamp) + text = FormattedText( + "Hello World!", + Color.Blue, + Color.Gray, + FontStyle.helvetica, + EncodingType.winansi, + True, + 14 + ) + stamp.bind_logo(text) + + # Configure stamp properties + stamp.set_origin(10, 400) + stamp.rotation = 90.0 + stamp.is_background = True + + # Apply stamp only to selected pages (page 2) + stamp.pages = [2] + + # Add stamp to the PDF + file_stamp.add_stamp(stamp) + + # Save output PDF + file_stamp.save(data_dir + "AddTextStampOnParticularPages_out.pdf") + + # Close the stamp object + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/add-text-and-image-stamp_3.py b/examples/facades_pdf_file_stamp/add-text-and-image-stamp_3.py new file mode 100644 index 0000000..ae4d902 --- /dev/null +++ b/examples/facades_pdf_file_stamp/add-text-and-image-stamp_3.py @@ -0,0 +1,39 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\add-text-and-image-stamp +# Code fence language: python + + +from aspose.pdf.facades import PdfFileStamp, Stamp + +def add_image_stamp_on_all_pages_in_pdf_file(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + # Create PdfFileStamp object + file_stamp = PdfFileStamp() + + # Bind source PDF document + file_stamp.bind_pdf(data_dir + "sample.pdf") + + # Create stamp object + stamp = Stamp() + + # Bind image to stamp + stamp.bind_image(data_dir + "StampImage.png") + + # Configure stamp properties + stamp.set_origin(10, 200) + stamp.rotation = 90.0 + stamp.is_background = True + + # OPTIONAL: + # If you want to apply the stamp only to selected pages, uncomment below + # stamp.pages = [2] + + # Add stamp to PDF file (applies to all pages by default) + file_stamp.add_stamp(stamp) + + # Save output PDF + file_stamp.save(data_dir + "AddImageStampOnAllPages_out.pdf") + + # Close the stamp object + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/add-text-and-image-stamp_4.py b/examples/facades_pdf_file_stamp/add-text-and-image-stamp_4.py new file mode 100644 index 0000000..af37c23 --- /dev/null +++ b/examples/facades_pdf_file_stamp/add-text-and-image-stamp_4.py @@ -0,0 +1,38 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\add-text-and-image-stamp +# Code fence language: python + + +from aspose.pdf.facades import PdfFileStamp, Stamp + +def add_image_stamp_on_particular_pages_in_pdf_file(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + # Create PdfFileStamp object + file_stamp = PdfFileStamp() + + # Bind source PDF document + file_stamp.bind_pdf(data_dir + "sample.pdf") + + # Create stamp object + stamp = Stamp() + + # Bind image to stamp + stamp.bind_image(data_dir + "StampImage.png") + + # Configure stamp properties + stamp.set_origin(10, 200) + stamp.rotation = 90.0 + stamp.is_background = True + + # Apply stamp only to selected pages (e.g., page 2) + stamp.pages = [2] + + # Add stamp to PDF file + file_stamp.add_stamp(stamp) + + # Save output PDF + file_stamp.save(data_dir + "AddImageStampOnParticularPages_out.pdf") + + # Close the stamp object + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/manage-header-and-footer_1.py b/examples/facades_pdf_file_stamp/manage-header-and-footer_1.py new file mode 100644 index 0000000..f173841 --- /dev/null +++ b/examples/facades_pdf_file_stamp/manage-header-and-footer_1.py @@ -0,0 +1,36 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\manage-header-and-footer +# Code fence language: python + + +from aspose.pdf.facades import ( + PdfFileStamp, + FormattedText, + FontStyle, + EncodingType +) +from System.Drawing import Color + +def add_header(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + file_stamp = PdfFileStamp() + file_stamp.bind_pdf(data_dir + "sample.pdf") + + # Create formatted text for header + header_text = FormattedText( + "Aspose - Your File Format Experts!", + Color.Yellow, + Color.Black, + FontStyle.courier, + EncodingType.winansi, + False, + 14 + ) + + # Add header with top margin + file_stamp.add_header(header_text, 10) + + # Save output PDF + file_stamp.save(data_dir + "AddHeader_out.pdf") + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/manage-header-and-footer_2.py b/examples/facades_pdf_file_stamp/manage-header-and-footer_2.py new file mode 100644 index 0000000..09a0657 --- /dev/null +++ b/examples/facades_pdf_file_stamp/manage-header-and-footer_2.py @@ -0,0 +1,36 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\manage-header-and-footer +# Code fence language: python + + +from aspose.pdf.facades import ( + PdfFileStamp, + FormattedText, + FontStyle, + EncodingType +) +from System.Drawing import Color + +def add_footer(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + file_stamp = PdfFileStamp() + file_stamp.bind_pdf(data_dir + "sample.pdf") + + # Create formatted text for footer + footer_text = FormattedText( + "Aspose - Your File Format Experts!", + Color.Blue, + Color.Gray, + FontStyle.courier, + EncodingType.winansi, + False, + 14 + ) + + # Add footer with bottom margin + file_stamp.add_footer(footer_text, 10) + + # Save output PDF + file_stamp.save(data_dir + "AddFooter_out.pdf") + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/manage-header-and-footer_3.py b/examples/facades_pdf_file_stamp/manage-header-and-footer_3.py new file mode 100644 index 0000000..7a13695 --- /dev/null +++ b/examples/facades_pdf_file_stamp/manage-header-and-footer_3.py @@ -0,0 +1,20 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\manage-header-and-footer +# Code fence language: python + + +from aspose.pdf.facades import PdfFileStamp + +def add_image_header(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + file_stamp = PdfFileStamp() + file_stamp.bind_pdf(data_dir + "sample.pdf") + + # Open image stream and add as header + with open(data_dir + "ImageHeader.png", "rb") as image_stream: + file_stamp.add_header(image_stream, 10) + + # Save output PDF + file_stamp.save(data_dir + "AddImageHeader_out.pdf") + file_stamp.close() diff --git a/examples/facades_pdf_file_stamp/manage-header-and-footer_4.py b/examples/facades_pdf_file_stamp/manage-header-and-footer_4.py new file mode 100644 index 0000000..442efa0 --- /dev/null +++ b/examples/facades_pdf_file_stamp/manage-header-and-footer_4.py @@ -0,0 +1,20 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdffilestamp\manage-header-and-footer +# Code fence language: python + + +from aspose.pdf.facades import PdfFileStamp + +def add_image_footer(): + data_dir = RunExamples.get_data_dir_aspose_pdf_images() + + file_stamp = PdfFileStamp() + file_stamp.bind_pdf(data_dir + "sample.pdf") + + # Open image stream and add as footer + with open(data_dir + "ImageFooter.png", "rb") as image_stream: + file_stamp.add_footer(image_stream, 10) + + # Save output PDF + file_stamp.save(data_dir + "AddImageFooter_out.pdf") + file_stamp.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_1.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_1.py new file mode 100644 index 0000000..3f673b8 --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_1.py @@ -0,0 +1,33 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf + +# Prepare viewer +viewer = pdf.facades.PdfViewer() + +# Bind the PDF (open) +viewer.bind_pdf("PrintDocument.pdf") + +# Adjust settings +viewer.auto_resize = True +viewer.auto_rotate = True +viewer.print_page_dialog = False + +# Create printer and page settings +ps = pdf.printing.PrinterSettings() +pgs = pdf.printing.PageSettings() + +# You can explicitly specify printer name (optional) +# ps.printer_name = "Your Printer Name" + +# Example: Set A4 page size +pgs.paper_size = pdf.printing.PaperSizes.A4 + +# Print +viewer.print_document_with_settings(pgs, ps) + +# Release resources +viewer.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_2.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_2.py new file mode 100644 index 0000000..83a1125 --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_2.py @@ -0,0 +1,43 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf +import System +from System.Windows.Forms import PrintDialog, DialogResult + +def printing_pdf_display_print_dialog(): + # Path to the documents directory + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_printing() + + # Create PdfViewer object + viewer = pdf.facades.PdfViewer() + + try: + # Bind PDF document + viewer.bind_pdf(data_dir + "PrintDocument.pdf") + + # Set attributes for printing + viewer.auto_resize = True + viewer.auto_rotate = True + + # Show system print dialog + print_dialog = PrintDialog() + + if print_dialog.ShowDialog() == DialogResult.OK: + # Convert .NET PrinterSettings to Aspose equivalents + ps = pdf.printing.PrinterSettings.to_aspose_printer_settings( + print_dialog.PrinterSettings + ) + + pgs = pdf.printing.PageSettings.to_aspose_page_settings( + print_dialog.PrinterSettings.DefaultPageSettings + ) + + # Print document using selected printer and page settings + viewer.print_document_with_settings(pgs, ps) + + finally: + # Release resources + viewer.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_3.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_3.py new file mode 100644 index 0000000..2c3da36 --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_3.py @@ -0,0 +1,26 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf + +viewer = pdf.facades.PdfViewer() +viewer.bind_pdf("PrintDocument.pdf") + +viewer.auto_resize = True +viewer.auto_rotate = True +viewer.print_page_dialog = False + +ps = pdf.printing.PrinterSettings() +pgs = pdf.printing.PageSettings() + +# Set soft printer and print to file +ps.printer_name = "Adobe PDF" # Or another virtual printer +ps.print_file_name = "OutFile.pdf" +ps.print_to_file = True + +pgs.paper_size = pdf.printing.PaperSizes.A4 + +viewer.print_document_with_settings(pgs, ps) +viewer.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_4.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_4.py new file mode 100644 index 0000000..a6d4ded --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_4.py @@ -0,0 +1,22 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf + +viewer = pdf.facades.PdfViewer() +viewer.bind_pdf("PrintDocument.pdf") + +viewer.auto_resize = True +viewer.auto_rotate = True +viewer.print_page_dialog = False +viewer.print_as_grayscale = True # Print in grayscale + +ps = pdf.printing.PrinterSettings() +pgs = pdf.printing.PageSettings() +ps.printer_name = "Microsoft XPS Document Writer" +pgs.paper_size = pdf.printing.PaperSizes.A4 + +viewer.print_document_with_settings(pgs, ps) +viewer.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_5.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_5.py new file mode 100644 index 0000000..9574d0f --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_5.py @@ -0,0 +1,45 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf + +def printing_pdf_hide_print_dialog(): + # Path to the documents directory + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_printing() + + # Create PdfViewer object + viewer = pdf.facades.PdfViewer() + + try: + # Bind PDF document + viewer.bind_pdf(data_dir + "PrintDocument.pdf") + + # Set attributes for printing + # Print the file with adjusted size + viewer.auto_resize = True + # Print the file with adjusted rotation + viewer.auto_rotate = True + # Do not show the page number dialog + viewer.print_page_dialog = False + + # Create printer and page settings + ps = pdf.printing.PrinterSettings() + pgs = pdf.printing.PageSettings() + + # Set XPS/PDF printer name + ps.printer_name = "OneNote for Windows 10" + + # Set page size (A4) + pgs.paper_size = pdf.printing.PaperSizes.A4 + + # Set page margins (left, right, top, bottom) + pgs.margins = pdf.devices.Margins(0, 0, 0, 0) + + # Print document using printer and page settings + viewer.print_document_with_settings(pgs, ps) + + finally: + # Close viewer and release resources + viewer.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_6.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_6.py new file mode 100644 index 0000000..25e34de --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_6.py @@ -0,0 +1,47 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf + +def printing_pdf_to_postscript(): + # Path to the documents directory + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_printing() + + # Create PdfViewer object + viewer = pdf.facades.PdfViewer() + + try: + # Bind PDF document + viewer.bind_pdf(data_dir + "PrintDocument.pdf") + + # Set attributes for printing + viewer.auto_resize = True + viewer.auto_rotate = True + viewer.print_page_dialog = False + viewer.print_as_image = False # Do NOT convert pages to images + + # Create printer and page settings + ps = pdf.printing.PrinterSettings() + pgs = pdf.printing.PageSettings() + + # Set PostScript printer name + ps.printer_name = "HP Universal Printing PS (v7.0.0)" + + # Set output file and enable PrintToFile + ps.print_file_name = data_dir + "PdfToPostScript_out.ps" + ps.print_to_file = True + + # Set page size (A4) + pgs.paper_size = pdf.printing.PaperSizes.A4 + + # Set page margins (left, right, top, bottom) + pgs.margins = pdf.devices.Margins(0, 0, 0, 0) + + # Print document using printer and page settings + viewer.print_document_with_settings(pgs, ps) + + finally: + # Release resources + viewer.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_7.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_7.py new file mode 100644 index 0000000..cea4edf --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_7.py @@ -0,0 +1,55 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf + +def checking_print_job_status(): + # Path to the documents directory + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_printing() + + # Instantiate PdfViewer object + viewer = pdf.facades.PdfViewer() + + try: + # Bind PDF document + viewer.bind_pdf(data_dir + "PrintDocument.pdf") + + # Set attributes for printing + viewer.auto_resize = True + viewer.auto_rotate = True + viewer.print_page_dialog = False + viewer.print_as_image = False + + # Create printer and page settings + ps = pdf.printing.PrinterSettings() + pgs = pdf.printing.PageSettings() + + # Specify the printer name + ps.printer_name = "Microsoft XPS Document Writer" + + # Set output file name and enable PrintToFile + ps.print_file_name = data_dir + "CheckingPrintJobStatus_out.xps" + ps.print_to_file = True + + # Set page size (A4) + pgs.paper_size = pdf.printing.PaperSizes.A4 + + # Set page margins + pgs.margins = pdf.devices.Margins(0, 0, 0, 0) + + # Print document using printer and page settings + viewer.print_document_with_settings(pgs, ps) + + # Check the print status + if viewer.print_status is not None: + # An exception was thrown during printing + print(str(viewer.print_status)) + else: + # Printing completed successfully + print("Printing completed without any issue.") + + finally: + # Release resources + viewer.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_8.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_8.py new file mode 100644 index 0000000..e17a66f --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_8.py @@ -0,0 +1,108 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf +import os + +class PrintingJobSettings: + def __init__(self, from_page, to_page, output_file, duplex_mode): + self.from_page = from_page + self.to_page = to_page + self.output_file = output_file + self.mode = duplex_mode + + +def printing_pages_in_simplex_and_duplex_mode(): + # Path to the documents directory + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_printing() + output_dir = data_dir + + printing_job_index = 0 + printing_jobs = [] + + # Create printing jobs + printing_jobs.append( + PrintingJobSettings( + from_page=1, + to_page=3, + output_file=output_dir + "PrintPageRange_p1-3_out.xps", + duplex_mode=pdf.printing.Duplex.Default + ) + ) + + printing_jobs.append( + PrintingJobSettings( + from_page=4, + to_page=6, + output_file=output_dir + "PrintPageRange_p4-6_out.xps", + duplex_mode=pdf.printing.Duplex.Simplex + ) + ) + + printing_jobs.append( + PrintingJobSettings( + from_page=7, + to_page=7, + output_file=output_dir + "PrintPageRange_p7_out.xps", + duplex_mode=pdf.printing.Duplex.Default + ) + ) + + # Create PdfViewer object + viewer = pdf.facades.PdfViewer() + + try: + # Bind PDF document + viewer.bind_pdf(data_dir + "Print-PageRange.pdf") + + # Set printing attributes + viewer.auto_resize = True + viewer.auto_rotate = True + viewer.print_page_dialog = False + + # Create printer and page settings + ps = pdf.printing.PrinterSettings() + pgs = pdf.printing.PageSettings() + + # Set printer name + ps.printer_name = "Microsoft XPS Document Writer" + + # Set initial job settings + ps.print_to_file = True + ps.print_range = pdf.printing.PrintRange.SomePages + + # Paper size and margins + pgs.paper_size = pdf.printing.PaperSizes.A4 + ps.default_page_settings.paper_size = pgs.paper_size + pgs.margins = pdf.devices.Margins(0, 0, 0, 0) + + # Helper to apply a print job + def apply_print_job(index): + job = printing_jobs[index] + ps.print_file_name = os.path.abspath(job.output_file) + ps.from_page = job.from_page + ps.to_page = job.to_page + ps.duplex = job.mode + + # Apply first job + apply_print_job(printing_job_index) + + # EndPrint event handler (chain next jobs) + def on_end_print(sender, args): + nonlocal printing_job_index + printing_job_index += 1 + + if printing_job_index < len(printing_jobs): + apply_print_job(printing_job_index) + viewer.print_document_with_settings(pgs, ps) + + viewer.end_print += on_end_print + + # Start first print job + viewer.print_document_with_settings(pgs, ps) + + finally: + # Release resources + viewer.close() diff --git a/examples/facades_pdf_viewer/working-with-pdf-printing-facades_9.py b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_9.py new file mode 100644 index 0000000..77a1220 --- /dev/null +++ b/examples/facades_pdf_viewer/working-with-pdf-printing-facades_9.py @@ -0,0 +1,37 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\pdfviewer\working-with-pdf-printing-facades +# Code fence language: python + + +import aspose.pdf as pdf +import os + +def printing_multiple_documents_in_single_job(): + # Path to the documents directory + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_printing() + + # Paths to documents to be printed + path1 = os.path.join(data_dir, "PrintDocument.pdf") + path2 = os.path.join(data_dir, "Print-PageRange.pdf") + path3 = os.path.join(data_dir, "35925_1_3.xps") + + # Create printer settings + printer_settings = pdf.printing.PrinterSettings() + + # Use default system printer (same idea as PrintDocument.PrinterSettings.PrinterName) + # If you want to force a printer, uncomment and set it explicitly: + # printer_settings.printer_name = "Microsoft XPS Document Writer" + + # Create page settings + page_settings = pdf.printing.PageSettings() + page_settings.paper_size = pdf.printing.PaperSizes.A4 + page_settings.margins = pdf.devices.Margins(0, 0, 0, 0) + + # Print multiple documents in a single print job + pdf.facades.PdfViewer.print_documents( + printer_settings, + page_settings, + path1, + path2, + path3 + ) diff --git a/examples/facades_stamp/adding-multi-line-watermark-to-existing-pdf_1.py b/examples/facades_stamp/adding-multi-line-watermark-to-existing-pdf_1.py new file mode 100644 index 0000000..17e479d --- /dev/null +++ b/examples/facades_stamp/adding-multi-line-watermark-to-existing-pdf_1.py @@ -0,0 +1,30 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\stamp\adding-multi-line-watermark-to-existing-pdf +# Code fence language: python + + +import aspose.pdf as pdf +import System +from System.Drawing import Color + +def add_text_stamp_to_pdf(): + # Instantiate a Stamp object + logo_stamp = pdf.facades.Stamp() + + # Create a FormattedText object (first line) + formatted_text = pdf.facades.FormattedText( + "Hello World!", + Color.FromArgb(180, 0, 0), # Semi-transparent red + pdf.facades.FontStyle.TimesItalic, # Font style + pdf.facades.EncodingType.Winansi, # Encoding + False, # Embedded font + 50 # Font size + ) + + # Add another line to the stamp + formatted_text.add_new_line_text("Good Luck") + + # Bind formatted text to the stamp + logo_stamp.bind_logo(formatted_text) + + return logo_stamp diff --git a/examples/facades_stamp/rotating-stamp-about-the-center-point_1.py b/examples/facades_stamp/rotating-stamp-about-the-center-point_1.py new file mode 100644 index 0000000..0f3d91a --- /dev/null +++ b/examples/facades_stamp/rotating-stamp-about-the-center-point_1.py @@ -0,0 +1,53 @@ +# Extracted from: _index.md +# Source folder: E:\Github\Aspose.PDF-Documentation\en\python-net\working-with-facades\stamp\rotating-stamp-about-the-center-point +# Code fence language: python + + +import aspose.pdf as pdf + +def add_rotating_stamp_to_pdf(): + # Path to the documents directory + data_dir = RunExamples.get_data_dir_aspose_pdf_facades_technical_articles() + + # PdfFileInfo is used to get page width and height + file_info = pdf.facades.PdfFileInfo(data_dir + "RotatingStamp.pdf") + + try: + # Create Stamp object + stamp = pdf.facades.Stamp() + + # Bind image to stamp + stamp.bind_image(data_dir + "RotatingStamp.jpg") + + # Specify whether the stamp is background + stamp.is_background = False + + # Specify pages where the stamp will be applied + stamp.pages = [1] + + # Rotate stamp around its center (0–360 degrees) + stamp.rotation = 90 + + # Set the origin (lower-left corner of the stamp) + stamp.set_origin( + file_info.get_page_width(1) / 2, + file_info.get_page_height(1) / 2 + ) + + # Set image size + stamp.set_image_size(100, 100) + + # Open PDF document + document = pdf.Document(data_dir + "RotatingStamp_out.pdf") + + try: + # Create PdfFileStamp to apply the stamp + stamper = pdf.facades.PdfFileStamp(document) + + try: + # Add stamp to the PDF + stamper.add_stamp(stamp) + finally: + stamper.close() + document.close() + file_info.close() diff --git a/examples/working_with_documents/example_formatting_pdf_document.py b/examples/working_with_documents/example_formatting_pdf_document.py index 83482d5..d852e2e 100644 --- a/examples/working_with_documents/example_formatting_pdf_document.py +++ b/examples/working_with_documents/example_formatting_pdf_document.py @@ -129,7 +129,7 @@ def run_all_examples(data_dir=None, license_path=None): ("Configure document window settings", set_document_window), ("Embed fonts in existing PDF", embedded_fonts), ("Embed fonts in new PDF", embedded_fonts_in_new_document), - ("Set default font", set_default_font), + ("Set default font", set_default_font), ("List document fonts", get_all_fonts), ("Improve font embedding", improve_fonts_embedding), ("Set initial zoom factor", set_zoom_factor), diff --git a/sample_data/facades_form/input/fill_barcode_fields_in.pdf b/sample_data/facades_form/input/fill_barcode_fields_in.pdf new file mode 100644 index 0000000..e66a5f1 Binary files /dev/null and b/sample_data/facades_form/input/fill_barcode_fields_in.pdf differ diff --git a/sample_data/facades_form/input/fill_check_box_fields_in.pdf b/sample_data/facades_form/input/fill_check_box_fields_in.pdf new file mode 100644 index 0000000..f25d71d Binary files /dev/null and b/sample_data/facades_form/input/fill_check_box_fields_in.pdf differ diff --git a/sample_data/facades_form/input/fill_fields_by_name_and_value_in.pdf b/sample_data/facades_form/input/fill_fields_by_name_and_value_in.pdf new file mode 100644 index 0000000..9667b00 Binary files /dev/null and b/sample_data/facades_form/input/fill_fields_by_name_and_value_in.pdf differ diff --git a/sample_data/facades_form/input/fill_list_box_fields_in.pdf b/sample_data/facades_form/input/fill_list_box_fields_in.pdf new file mode 100644 index 0000000..81515e8 Binary files /dev/null and b/sample_data/facades_form/input/fill_list_box_fields_in.pdf differ diff --git a/sample_data/facades_form/input/fill_radio_button_fields_in.pdf b/sample_data/facades_form/input/fill_radio_button_fields_in.pdf new file mode 100644 index 0000000..01a8da3 Binary files /dev/null and b/sample_data/facades_form/input/fill_radio_button_fields_in.pdf differ diff --git a/sample_data/facades_form/input/fill_text_fields_in.pdf b/sample_data/facades_form/input/fill_text_fields_in.pdf new file mode 100644 index 0000000..b615bad Binary files /dev/null and b/sample_data/facades_form/input/fill_text_fields_in.pdf differ diff --git a/sample_data/facades_form/input/get_field_facades_in.pdf b/sample_data/facades_form/input/get_field_facades_in.pdf new file mode 100644 index 0000000..1cd33d9 Binary files /dev/null and b/sample_data/facades_form/input/get_field_facades_in.pdf differ diff --git a/sample_data/facades_form/input/get_field_values_in.pdf b/sample_data/facades_form/input/get_field_values_in.pdf new file mode 100644 index 0000000..1cd33d9 Binary files /dev/null and b/sample_data/facades_form/input/get_field_values_in.pdf differ diff --git a/sample_data/facades_form/input/get_radio_button_options_in.pdf b/sample_data/facades_form/input/get_radio_button_options_in.pdf new file mode 100644 index 0000000..0dfb4fb Binary files /dev/null and b/sample_data/facades_form/input/get_radio_button_options_in.pdf differ diff --git a/sample_data/facades_form/input/get_required_field_names_in.pdf b/sample_data/facades_form/input/get_required_field_names_in.pdf new file mode 100644 index 0000000..75d7fe9 Binary files /dev/null and b/sample_data/facades_form/input/get_required_field_names_in.pdf differ diff --git a/sample_data/facades_form/input/get_rich_text_values_in.pdf b/sample_data/facades_form/input/get_rich_text_values_in.pdf new file mode 100644 index 0000000..e673b1f Binary files /dev/null and b/sample_data/facades_form/input/get_rich_text_values_in.pdf differ diff --git a/sample_data/facades_form/input/get_rich_text_values_in_data.xml b/sample_data/facades_form/input/get_rich_text_values_in_data.xml new file mode 100644 index 0000000..00f5ed9 --- /dev/null +++ b/sample_data/facades_form/input/get_rich_text_values_in_data.xml @@ -0,0 +1,12 @@ + +YellowtownAlexanderGreenfieldAspose.PDF for Python via .NET, PDF Processing API that allows the developers to work with PDF documents without needing Microsoft Office® or Adobe Acrobat Automation. \ No newline at end of file diff --git a/sample_data/facades_form/input/resolve_full_field_names_in.pdf b/sample_data/facades_form/input/resolve_full_field_names_in.pdf new file mode 100644 index 0000000..e673b1f Binary files /dev/null and b/sample_data/facades_form/input/resolve_full_field_names_in.pdf differ diff --git a/sample_data/facades_form/input/sample_form.fdf b/sample_data/facades_form/input/sample_form.fdf new file mode 100644 index 0000000..ea61cbc --- /dev/null +++ b/sample_data/facades_form/input/sample_form.fdf @@ -0,0 +1,7 @@ +%FDF-1.2 % 1 0 obj +<><><><><>]/Annots[]>>>> +endobj + +trailer +<> +%%EOF \ No newline at end of file diff --git a/sample_data/facades_form/input/sample_form.json b/sample_data/facades_form/input/sample_form.json new file mode 100644 index 0000000..9ce8ee2 --- /dev/null +++ b/sample_data/facades_form/input/sample_form.json @@ -0,0 +1,26 @@ +[ + { + "Name": "First Name", + "PageIndex": 1, + "Flags": 4, + "Value": "Thomas" + }, + { + "Name": "Last Name", + "PageIndex": 1, + "Flags": 4, + "Value": "Jacksonn" + }, + { + "Name": "City", + "PageIndex": 1, + "Flags": 4, + "Value": "Yellowville" + }, + { + "Name": "Country", + "PageIndex": 1, + "Flags": 4, + "Value": "Kenya" + } +] \ No newline at end of file diff --git a/sample_data/facades_form/input/sample_form.pdf b/sample_data/facades_form/input/sample_form.pdf new file mode 100644 index 0000000..1cd33d9 Binary files /dev/null and b/sample_data/facades_form/input/sample_form.pdf differ diff --git a/sample_data/facades_form/input/sample_form.xfdf b/sample_data/facades_form/input/sample_form.xfdf new file mode 100644 index 0000000..1fde6c6 --- /dev/null +++ b/sample_data/facades_form/input/sample_form.xfdf @@ -0,0 +1,17 @@ + + + + + Alexander + + + Greenfield + + + Yellowtown + + + Redland + + + \ No newline at end of file diff --git a/sample_data/facades_form/input/sample_form.xml b/sample_data/facades_form/input/sample_form.xml new file mode 100644 index 0000000..4292929 --- /dev/null +++ b/sample_data/facades_form/input/sample_form.xml @@ -0,0 +1,15 @@ + + + + Thomas + + + Andersson + + + Seattle + + + Brownland + + \ No newline at end of file diff --git a/sample_data/facades_form/input/sample_form_image.jpg b/sample_data/facades_form/input/sample_form_image.jpg new file mode 100644 index 0000000..6f8d5bd Binary files /dev/null and b/sample_data/facades_form/input/sample_form_image.jpg differ diff --git a/sample_data/facades_form/input/sample_form_image.pdf b/sample_data/facades_form/input/sample_form_image.pdf new file mode 100644 index 0000000..3f54c2b Binary files /dev/null and b/sample_data/facades_form/input/sample_form_image.pdf differ diff --git a/sample_data/facades_form/input/sample_form_new.pdf b/sample_data/facades_form/input/sample_form_new.pdf new file mode 100644 index 0000000..5d7ae0b Binary files /dev/null and b/sample_data/facades_form/input/sample_form_new.pdf differ diff --git a/sample_data/facades_form/input/sample_form_xfa.xml b/sample_data/facades_form/input/sample_form_xfa.xml new file mode 100644 index 0000000..b8d1c80 --- /dev/null +++ b/sample_data/facades_form/input/sample_form_xfa.xml @@ -0,0 +1,60 @@ + + + +
+ 123 + + Aspose + + + + + + + + + + + + + + + + + +
+ + + + + + + + 0 + + 0.00000000 + 0 + + 0.00000000 + 0 + + 0.00000000 + + +