Update pdf_to_svg.py
Browse files- pdf_to_svg.py +31 -0
pdf_to_svg.py
CHANGED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import fitz # PyMuPDF
|
| 2 |
+
|
| 3 |
+
def convert_pdf_to_svg(input_pdf, output_svg, width, height):
|
| 4 |
+
"""
|
| 5 |
+
Converts a PDF to an SVG while preserving dimensions and vector data.
|
| 6 |
+
Args:
|
| 7 |
+
input_pdf (str): Path to the input PDF file.
|
| 8 |
+
output_svg (str): Path to save the output SVG file.
|
| 9 |
+
width (float): Target width in inches.
|
| 10 |
+
height (float): Target height in inches.
|
| 11 |
+
"""
|
| 12 |
+
doc = fitz.open(input_pdf)
|
| 13 |
+
svg_content = []
|
| 14 |
+
|
| 15 |
+
# DPI for the conversion (72 DPI = 1 inch)
|
| 16 |
+
dpi = 72
|
| 17 |
+
scaling_x = width * dpi / doc[0].rect.width
|
| 18 |
+
scaling_y = height * dpi / doc[0].rect.height
|
| 19 |
+
|
| 20 |
+
for page_num in range(len(doc)):
|
| 21 |
+
page = doc[page_num]
|
| 22 |
+
matrix = fitz.Matrix(scaling_x, scaling_y)
|
| 23 |
+
svg = page.get_svg_image(matrix=matrix) # Extract SVG with scaling
|
| 24 |
+
svg_content.append(svg)
|
| 25 |
+
|
| 26 |
+
# Wrap SVG content with specified dimensions
|
| 27 |
+
svg_header = f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}in" height="{height}in" viewBox="0 0 {width * dpi} {height * dpi}">'
|
| 28 |
+
svg_footer = "</svg>"
|
| 29 |
+
|
| 30 |
+
with open(output_svg, "w") as svg_file:
|
| 31 |
+
svg_file.write(svg_header + "\n".join(svg_content) + svg_footer)
|