Help
Community
Project privacy set to public. By default, its content is available to everyone (authenticated or not). Please note that more restrictive permissions might exist on some items.
Create set of APIs to e-sign a PDF using Flask/Python
API/process 1.
API/process 2.
------------sample code-------------- from flask import Flask, jsonify, request import subprocess from PyPDF2 import PdfReader, PdfWriter import os
app = Flask(name)
@app.route('/generate_certificate', methods=['GET']) def generate_certificate(): try: # Signer details signer_common_name = 'Your Name' signer_organization = 'Your Organization' signer_organization_unit = 'Your Organization Unit' signer_locality = 'Your Locality' signer_state = 'Your State' signer_country = 'Your Country Code'
# Generate private key subprocess.call(['openssl', 'genpkey', '-algorithm', 'RSA', '-out', 'private.key']) # Generate CSR subprocess.call(['openssl', 'req', '-new', '-key', 'private.key', '-out', 'csr.csr', '-subj', '/CN={}/O={}/OU={}/L={}/ST={}/C={}'.format(signer_common_name, signer_organization, signer_organization_unit, signer_locality, signer_state, signer_country)]) # Generate self-signed certificate subprocess.call(['openssl', 'x509', '-req', '-days', '365', '-in', 'csr.csr', '-signkey', 'private.key', '-out', 'certificate.crt']) return jsonify({'message': 'Certificate generated successfully.'}), 200 except Exception as e: return jsonify({'error': str(e)}), 500
@app.route('/sign_pdf', methods=['POST']) def sign_pdf(): try: # Get the uploaded PDF file pdf_file = request.files['file'] pdf_data = pdf_file.read()
# Load the PDF pdf = PdfReader(pdf_data) # Sign the PDF signature_image = 'signature.png' # Path to the signature image output_pdf = 'signed_document.pdf' # Path to the signed PDF for page in pdf.pages: page.merge_page(page) # Add the signature image to the first page signature_page = pdf.pages[0] signature_page.add_image(signature_image, x=100, y=100, width=200, height=50) # Save the signed PDF pdf_writer = PdfWriter() for page in pdf.pages: pdf_writer.add_page(page) with open(output_pdf, 'wb') as output_file: pdf_writer.write(output_file) # Remove the temporary files os.remove('private.key') os.remove('csr.csr') os.remove('certificate.crt') return jsonify({'message': 'PDF signed successfully.'}), 200 except Exception as e: return jsonify({'error': str(e)}), 500
if name == 'main': app.run(debug=True)