import gradio as gr from pdf2image import convert_from_path from PIL import Image import img2pdf import tempfile import os import shutil def resize_pdf(pdf_file, width_percent, height_percent): width_percent = float(width_percent) height_percent = float(height_percent) # ここで恒久的な一時ファイルを作成 output_fd, output_path = tempfile.mkstemp(suffix=".pdf") os.close(output_fd) # すぐ閉じる with tempfile.TemporaryDirectory() as tmpdir: # PDF → 画像 images = convert_from_path(pdf_file.name, dpi=200, output_folder=tmpdir) resized_images = [] for i, img in enumerate(images): new_width = int(img.width * width_percent / 100) new_height = int(img.height * height_percent / 100) resized_img = img.resize((new_width, new_height), Image.LANCZOS) img_path = os.path.join(tmpdir, f"page_{i}.png") resized_img.save(img_path, format='PNG') resized_images.append(img_path) # 画像 → PDF with open(output_path, "wb") as f_out: f_out.write(img2pdf.convert(resized_images)) return output_path with gr.Blocks() as demo: gr.Markdown("# PDFサイズを%でリサイズ") pdf_input = gr.File(label="PDFファイルを選択") width_input = gr.Number(label="幅の倍率(%)", value=100) height_input = gr.Number(label="高さの倍率(%)", value=100) output_pdf = gr.File(label="リサイズ後のPDF") btn = gr.Button("リサイズ実行") btn.click(resize_pdf, inputs=[pdf_input, width_input, height_input], outputs=output_pdf) demo.launch()