soiz1 commited on
Commit
f2134aa
·
verified ·
1 Parent(s): c8dac6a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -8
app.py CHANGED
@@ -4,33 +4,36 @@ from PIL import Image
4
  import img2pdf
5
  import tempfile
6
  import os
 
7
 
8
  def resize_pdf(pdf_file, width_percent, height_percent):
9
  width_percent = float(width_percent)
10
  height_percent = float(height_percent)
11
-
 
 
 
 
12
  with tempfile.TemporaryDirectory() as tmpdir:
13
- # PDF → 画像(全ページ)
14
  images = convert_from_path(pdf_file.name, dpi=200, output_folder=tmpdir)
15
 
16
  resized_images = []
17
  for i, img in enumerate(images):
18
- # リサイズ幅・高さ計算
19
  new_width = int(img.width * width_percent / 100)
20
  new_height = int(img.height * height_percent / 100)
21
  resized_img = img.resize((new_width, new_height), Image.LANCZOS)
22
 
23
- # 一時保存
24
  img_path = os.path.join(tmpdir, f"page_{i}.png")
25
  resized_img.save(img_path, format='PNG')
26
  resized_images.append(img_path)
27
 
28
  # 画像 → PDF
29
- output_pdf_path = os.path.join(tmpdir, "resized_output.pdf")
30
- with open(output_pdf_path, "wb") as f_out:
31
  f_out.write(img2pdf.convert(resized_images))
32
-
33
- return output_pdf_path
 
34
 
35
  with gr.Blocks() as demo:
36
  gr.Markdown("# PDFサイズを%でリサイズ")
 
4
  import img2pdf
5
  import tempfile
6
  import os
7
+ import shutil
8
 
9
  def resize_pdf(pdf_file, width_percent, height_percent):
10
  width_percent = float(width_percent)
11
  height_percent = float(height_percent)
12
+
13
+ # ここで恒久的な一時ファイルを作成
14
+ output_fd, output_path = tempfile.mkstemp(suffix=".pdf")
15
+ os.close(output_fd) # すぐ閉じる
16
+
17
  with tempfile.TemporaryDirectory() as tmpdir:
18
+ # PDF → 画像
19
  images = convert_from_path(pdf_file.name, dpi=200, output_folder=tmpdir)
20
 
21
  resized_images = []
22
  for i, img in enumerate(images):
 
23
  new_width = int(img.width * width_percent / 100)
24
  new_height = int(img.height * height_percent / 100)
25
  resized_img = img.resize((new_width, new_height), Image.LANCZOS)
26
 
 
27
  img_path = os.path.join(tmpdir, f"page_{i}.png")
28
  resized_img.save(img_path, format='PNG')
29
  resized_images.append(img_path)
30
 
31
  # 画像 → PDF
32
+ with open(output_path, "wb") as f_out:
 
33
  f_out.write(img2pdf.convert(resized_images))
34
+
35
+ return output_path
36
+
37
 
38
  with gr.Blocks() as demo:
39
  gr.Markdown("# PDFサイズを%でリサイズ")