2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでPDF中にハイライトをする方法

Posted at

PyMuPDFを使用

pip install pymupdf

文字を検索し文字の上からハイライト

import fitz

# PDFを開く
doc = fitz.open("sample.pdf")

# ハイライトするテキストの座標を取得
search_text = "この解釈において、次の各号に掲げる用語の定義は、当該各号による。"

# 各ページをループ
for page_num in range(len(doc)):
    page = doc[page_num]

    # ページ内で検索
    areas = page.search_for(search_text)

    # 見つかったエリアにハイライトを追加
    for area in areas:
        page.add_highlight_annot(area)

# 結果を保存
doc.save("sample_output.pdf")
doc.close()

座標を指定してハイライト

import fitz  # PyMuPDF

# PDFファイルを開く
doc = fitz.open("sample.pdf")

# ハイライトを追加するページと座標を指定
page_number = 0  # ページ番号 (0始まり)
highlight_rects = [
    (100, 200, 300, 250),  # (x0, y0, x1, y1) の座標 (左上と右下)
    (150, 300, 350, 350)   # 複数領域も指定可能
]

# 指定ページを取得
page = doc.load_page(page_number)

# 指定座標に塗りつぶしハイライトを追加
for rect in highlight_rects:
    # 矩形領域を定義
    annotation = page.add_rect_annot(fitz.Rect(rect))
    # 塗りつぶし色 (黄色) と透明度を設定
    annotation.set_colors(fill=(1, 1, 0))  # RGB: 黄色
    annotation.set_opacity(0.3)            # 透明度30%
    annotation.update()

# 保存
doc.save("sample_output.pdf")
doc.close()
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?