Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,25 +7,29 @@ class PDFTransformer:
|
|
| 7 |
self.doc = fitz.open(pdf_path)
|
| 8 |
|
| 9 |
def scale_content_to_fit(self, width, height):
|
| 10 |
-
# Resize each page's mediabox and cropbox for proportional scaling
|
| 11 |
for page in self.doc:
|
| 12 |
rect = page.rect
|
| 13 |
original_width, original_height = rect.width, rect.height
|
| 14 |
|
| 15 |
-
#
|
| 16 |
scale_factor = min(width / original_width, height / original_height)
|
| 17 |
-
|
| 18 |
-
# New dimensions based on scale factor
|
| 19 |
-
new_width = original_width * scale_factor
|
| 20 |
-
new_height = original_height * scale_factor
|
| 21 |
-
|
| 22 |
-
# Centering offsets to keep content centered on the new page
|
| 23 |
-
x_offset = (width - new_width) / 2
|
| 24 |
-
y_offset = (height - new_height) / 2
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
def save_to_pdf(self, output_path):
|
| 31 |
self.doc.save(output_path, garbage=4, deflate=True, clean=True)
|
|
|
|
| 7 |
self.doc = fitz.open(pdf_path)
|
| 8 |
|
| 9 |
def scale_content_to_fit(self, width, height):
|
|
|
|
| 10 |
for page in self.doc:
|
| 11 |
rect = page.rect
|
| 12 |
original_width, original_height = rect.width, rect.height
|
| 13 |
|
| 14 |
+
# Determine the scaling factor to maintain aspect ratio
|
| 15 |
scale_factor = min(width / original_width, height / original_height)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Calculate scaled width and height based on scale factor
|
| 18 |
+
scaled_width = original_width * scale_factor
|
| 19 |
+
scaled_height = original_height * scale_factor
|
| 20 |
+
|
| 21 |
+
# Center the content on the new page dimensions
|
| 22 |
+
x_offset = (width - scaled_width) / 2
|
| 23 |
+
y_offset = (height - scaled_height) / 2
|
| 24 |
+
|
| 25 |
+
# Create a transformation matrix
|
| 26 |
+
matrix = fitz.Matrix(scale_factor, scale_factor)
|
| 27 |
+
|
| 28 |
+
# Apply transformation to content and reposition
|
| 29 |
+
page.set_mediabox(fitz.Rect(0, 0, width, height)) # Set page to target dimensions
|
| 30 |
+
page.set_cropbox(fitz.Rect(0, 0, width, height)) # Ensure cropbox matches the new size
|
| 31 |
+
page.apply_transform(matrix) # Scale the content
|
| 32 |
+
page.set_cropbox(fitz.Rect(x_offset, y_offset, x_offset + scaled_width, y_offset + scaled_height))
|
| 33 |
|
| 34 |
def save_to_pdf(self, output_path):
|
| 35 |
self.doc.save(output_path, garbage=4, deflate=True, clean=True)
|