File size: 1,689 Bytes
3b2d5b2
49acc9d
99ee49c
 
 
 
f2134aa
99ee49c
c8dac6a
 
 
f2134aa
 
 
 
 
99ee49c
f2134aa
c8dac6a
 
 
99ee49c
c8dac6a
 
 
 
 
 
 
 
 
f2134aa
c8dac6a
f2134aa
 
 
03f50bc
49acc9d
c8dac6a
 
 
 
 
 
 
 
3b2d5b2
99ee49c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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()