Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -6,31 +6,36 @@ import img2pdf
|
|
6 |
import os
|
7 |
|
8 |
def downscale_pdf(pdf_file, dpi=150, max_width=1500):
|
|
|
|
|
9 |
with tempfile.TemporaryDirectory() as tmpdir:
|
10 |
-
# ステップ 1: PDF →
|
11 |
images = convert_from_path(pdf_file.name, dpi=dpi, output_folder=tmpdir)
|
12 |
|
13 |
downscaled_paths = []
|
14 |
-
|
15 |
for i, img in enumerate(images):
|
16 |
-
# ステップ 2: サイズを制限
|
17 |
w, h = img.size
|
18 |
if w > max_width:
|
19 |
new_h = int(h * max_width / w)
|
20 |
img = img.resize((max_width, new_h), Image.LANCZOS)
|
21 |
|
22 |
-
# 一時保存
|
23 |
img_path = os.path.join(tmpdir, f"page_{i}.jpg")
|
24 |
img.save(img_path, "JPEG", quality=85)
|
25 |
downscaled_paths.append(img_path)
|
26 |
|
27 |
-
# ステップ
|
28 |
-
|
29 |
-
with open(
|
30 |
f_out.write(img2pdf.convert(downscaled_paths))
|
31 |
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
with gr.Blocks() as demo:
|
36 |
gr.Markdown("# PDF 解像度ダウンサイザー\nPDFのページ画像を縮小して容量を減らします。")
|
|
|
6 |
import os
|
7 |
|
8 |
def downscale_pdf(pdf_file, dpi=150, max_width=1500):
|
9 |
+
import shutil
|
10 |
+
|
11 |
with tempfile.TemporaryDirectory() as tmpdir:
|
12 |
+
# ステップ 1: PDF → 画像
|
13 |
images = convert_from_path(pdf_file.name, dpi=dpi, output_folder=tmpdir)
|
14 |
|
15 |
downscaled_paths = []
|
|
|
16 |
for i, img in enumerate(images):
|
|
|
17 |
w, h = img.size
|
18 |
if w > max_width:
|
19 |
new_h = int(h * max_width / w)
|
20 |
img = img.resize((max_width, new_h), Image.LANCZOS)
|
21 |
|
|
|
22 |
img_path = os.path.join(tmpdir, f"page_{i}.jpg")
|
23 |
img.save(img_path, "JPEG", quality=85)
|
24 |
downscaled_paths.append(img_path)
|
25 |
|
26 |
+
# ステップ 2: 画像 → PDF
|
27 |
+
tmp_output_path = os.path.join(tmpdir, "downscaled.pdf")
|
28 |
+
with open(tmp_output_path, "wb") as f_out:
|
29 |
f_out.write(img2pdf.convert(downscaled_paths))
|
30 |
|
31 |
+
# ここでtmpdirは消えるので、ファイルを別の場所にコピー
|
32 |
+
result_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
|
33 |
+
with open(tmp_output_path, "rb") as src:
|
34 |
+
shutil.copyfileobj(src, result_file)
|
35 |
+
result_file.close()
|
36 |
+
|
37 |
+
return result_file.name
|
38 |
+
|
39 |
|
40 |
with gr.Blocks() as demo:
|
41 |
gr.Markdown("# PDF 解像度ダウンサイザー\nPDFのページ画像を縮小して容量を減らします。")
|