PDF-resizer / app.py
soiz1's picture
Update app.py
c8dac6a verified
raw
history blame
1.7 kB
import gradio as gr
from pdf2image import convert_from_path
from PIL import Image
import img2pdf
import tempfile
import os
def resize_pdf(pdf_file, width_percent, height_percent):
width_percent = float(width_percent)
height_percent = float(height_percent)
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
output_pdf_path = os.path.join(tmpdir, "resized_output.pdf")
with open(output_pdf_path, "wb") as f_out:
f_out.write(img2pdf.convert(resized_images))
return output_pdf_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()