import fitz # PyMuPDF for PDF manipulation import gradio as gr import tempfile import re # Convert inches to pixels for dimension scaling def inches_to_pixels(inches, dpi=300): return int(inches * dpi) # Convert PDF to SVG with specified dimensions and thickness scaling def pdf_to_svg(pdf_file, width_in, height_in, thickness_scale=1.0): try: # Open the PDF and load the first page pdf_document = fitz.open(pdf_file.name) page = pdf_document.load_page(0) # Render PDF page as SVG data using a high-resolution matrix svg_data = page.get_svg_image(matrix=fitz.Matrix(8, 8)) # 8x scaling for high fidelity # Ensure we have valid SVG data if not svg_data: print("Error: SVG data extraction failed.") return None # Adjust stroke width in the SVG data if thickness scaling is applied if thickness_scale != 1.0: svg_data = re.sub( r'stroke-width="([\d.]+)"', lambda match: f'stroke-width="{float(match.group(1)) * thickness_scale}"', svg_data ) # Convert width and height to pixels at 300 DPI for SVG scaling width_px = inches_to_pixels(width_in) height_px = inches_to_pixels(height_in) # Embed dimensions into the SVG svg_data = re.sub(r'width="([\d.]+)pt"', f'width="{width_px}px"', svg_data) svg_data = re.sub(r'height="([\d.]+)pt"', f'height="{height_px}px"', svg_data) # Save SVG data to a temporary file temp_svg_path = tempfile.mktemp(suffix=".svg", prefix="enhanced_diagram_") with open(temp_svg_path, 'w') as svg_file: svg_file.write(svg_data) return temp_svg_path # Return path of the saved SVG except Exception as e: print(f"Error during SVG conversion: {str(e)}") return None # Gradio Interface with width and height inputs def adjust_and_convert_pdf(pdf_file, width_in, height_in, thickness_scale=1.0): svg_path = pdf_to_svg(pdf_file, width_in, height_in, thickness_scale=thickness_scale) # Handle cases where the SVG path is None if svg_path is None: return "Error: Unable to convert PDF to editable SVG." return svg_path # Return the SVG file path for download # Gradio interface with width, height, and thickness scale inputs iface = gr.Interface( fn=adjust_and_convert_pdf, inputs=[ gr.File(label="Upload PDF"), gr.Number(label="Width (inches)", value=5.0), gr.Number(label="Height (inches)", value=4.0), gr.Slider(minimum=1, maximum=3, step=0.1, value=1.0, label="Thickness Scale") ], outputs=gr.File(label="Editable SVG"), title="PDF to Fully Editable SVG Converter for CorelDRAW", description="Upload a PDF to convert it to a fully editable SVG with specific width and height dimensions in inches. Ideal for CorelDRAW editing." ) # Launch the interface on Hugging Face Spaces iface.launch()