SathvikGanta's picture
Update pdf_to_svg.py
06f551f verified
raw
history blame
1.17 kB
import fitz # PyMuPDF
def convert_pdf_to_svg(input_pdf, output_svg, width, height):
"""
Converts a PDF to an SVG while preserving dimensions and vector data.
Args:
input_pdf (str): Path to the input PDF file.
output_svg (str): Path to save the output SVG file.
width (float): Target width in inches.
height (float): Target height in inches.
"""
doc = fitz.open(input_pdf)
svg_content = []
# DPI for the conversion (72 DPI = 1 inch)
dpi = 72
scaling_x = width * dpi / doc[0].rect.width
scaling_y = height * dpi / doc[0].rect.height
for page_num in range(len(doc)):
page = doc[page_num]
matrix = fitz.Matrix(scaling_x, scaling_y)
svg = page.get_svg_image(matrix=matrix) # Extract SVG with scaling
svg_content.append(svg)
# Wrap SVG content with specified dimensions
svg_header = f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}in" height="{height}in" viewBox="0 0 {width * dpi} {height * dpi}">'
svg_footer = "</svg>"
with open(output_svg, "w") as svg_file:
svg_file.write(svg_header + "\n".join(svg_content) + svg_footer)