import os import io import requests import fitz # PyMuPDF from PIL import Image, ImageEnhance from flask import Flask, request, render_template_string app = Flask(__name__) def extract_nameplate(pdf_file, output_path, resize_width=None, resize_height=None, brightness_factor=1.0): # Open the PDF file pdf_file = fitz.open(pdf_file) # Create output directory if it doesn't exist os.makedirs(os.path.dirname(output_path), exist_ok=True) # Get the first page (assuming nameplate is on the first page) page = pdf_file[0] # Extract images from the page images_list = page.get_images(full=True) if len(images_list) == 0: raise ValueError('No images found in the uploaded PDF.') # Iterate over images to process the nameplate for img_index, img in enumerate(images_list): xref = img[0] base_image = pdf_file.extract_image(xref) image_bytes = base_image['image'] # Open the image using PIL image = Image.open(io.BytesIO(image_bytes)) # Adjust dimensions if resize_width and resize_height: image = image.resize((resize_width, resize_height), Image.ANTIALIAS) # Adjust brightness enhancer = ImageEnhance.Brightness(image) image = enhancer.enhance(brightness_factor) # Save the modified image output_image_path = f"extracted_nameplate_{img_index + 1}.png" image.save(output_image_path, format='PNG') # Create a new PDF with the adjusted image pdf_image = fitz.open() pdf_page = pdf_image.new_page(width=image.width, height=image.height) pdf_page.insert_image(pdf_page.rect, filename=output_image_path) # Save the output PDF pdf_image.save(output_path, garbage=4, deflate=True) pdf_file.close() print(f"Nameplate adjusted and saved to {output_path}") @app.route('/') def upload_form(): return render_template_string(''' Upload PDF

Upload a PDF File

''') @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return 'No file part' file = request.files['file'] if file.filename == '': return 'No selected file' destination = 'uploaded_sample_file.pdf' output_pdf_path = 'output_nameplate.pdf' try: # Save the uploaded file file.save(destination) width, height = 400, 200 # Example dimensions brightness = 1.4 # Example brightness adjustment factor extract_nameplate(destination, output_pdf_path, resize_width=width, resize_height=height, brightness_factor=brightness) return f'File processed successfully. Download it here.' except Exception as e: return str(e) if __name__ == "__main__": app.run(debug=True)