File size: 1,843 Bytes
3b2d5b2
a1622dd
49acc9d
 
 
 
3b2d5b2
49acc9d
a1622dd
49acc9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b2d5b2
 
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
50
51
52
53
54
import gradio as gr
import tempfile
from pdf2image import convert_from_path
from PIL import Image
import img2pdf
import os

def downscale_pdf(pdf_file, dpi=150, max_width=1500):
    with tempfile.TemporaryDirectory() as tmpdir:
        # ステップ 1: PDF → 画像(dpiを指定)
        images = convert_from_path(pdf_file.name, dpi=dpi, output_folder=tmpdir)

        downscaled_paths = []

        for i, img in enumerate(images):
            # ステップ 2: サイズを制限
            w, h = img.size
            if w > max_width:
                new_h = int(h * max_width / w)
                img = img.resize((max_width, new_h), Image.LANCZOS)

            # 一時保存
            img_path = os.path.join(tmpdir, f"page_{i}.jpg")
            img.save(img_path, "JPEG", quality=85)
            downscaled_paths.append(img_path)

        # ステップ 3: 画像をPDFに再結合
        output_pdf_path = os.path.join(tmpdir, "downscaled.pdf")
        with open(output_pdf_path, "wb") as f_out:
            f_out.write(img2pdf.convert(downscaled_paths))

        # 返却
        return output_pdf_path

with gr.Blocks() as demo:
    gr.Markdown("# PDF 解像度ダウンサイザー\nPDFのページ画像を縮小して容量を減らします。")
    with gr.Row():
        with gr.Column():
            pdf_input = gr.File(label="入力PDF", file_types=[".pdf"])
            dpi_input = gr.Slider(72, 300, value=150, step=1, label="変換DPI")
            width_input = gr.Slider(500, 3000, value=1500, step=50, label="最大幅(px)")
            convert_button = gr.Button("変換")

        with gr.Column():
            pdf_output = gr.File(label="出力PDF")

    convert_button.click(
        fn=downscale_pdf,
        inputs=[pdf_input, dpi_input, width_input],
        outputs=pdf_output
    )

demo.launch()