チュートリアル

簡単にライブラリーを使用するためのチュートリアルコレクション

チュートリアル»Python»Spire.Doc for Python»ハイパーリンク»Python:Word 文書でハイパーリンクを挿入・削除する方法
2025-03-13

Python:Word 文書でハイパーリンクを挿入・削除する方法

ハイパーリンクは、動的でインタラクティブな Word 文書を作成するために欠かせない要素です。特定のテキストやオブジェクトを他の文書、ウェブページ、メールアドレス、または同じ文書内の特定の位置にリンクすることで、ユーザーは情報をシームレスに移動できます。本記事では、Spire.Doc for Python を使用して、Python で Word 文書にハイパーリンクを追加または削除する方法を学びます。

Spire.Doc for Python のインストール

この操作には、Spire.Doc for Python と plum-dispatch v1.7.4 が必要です。これらは、Spire.Doc for Python の公式ウェブサイトから手動でダウンロードするか、以下の pip コマンドでインストールできます。

pip install Spire.Doc

Python で Word にハイパーリンクを追加する

Spire.Doc for Python は、段落内のテキストや画像にウェブリンク、メールリンク、ファイルリンク、またはブックマークリンクを追加するための Paragraph.AppendHyperlink() メソッドを提供します。以下に詳細な手順を示します。

  • Document オブジェクトを作成します。
  • セクションと段落を追加します。
  • Paragraph.AppendHyperlink(link: str, text: str, type: HyperlinkType) メソッドを使用して、テキストに基づいたハイパーリンクを挿入します。
  • Paragraph.AppendPicture() メソッドを使用して、段落に画像を追加します。
  • Paragraph.AppendHyperlink(link: str, picture: DocPicture, type: HyperlinkType) メソッドを使用して、画像に基づいたハイパーリンクを挿入します。
  • Document.SaveToFile() メソッドを使用して、結果の文書を保存します。
  • Python
from spire.doc import *

# Word文書を作成する
doc = Document()

# セクションを追加する
section = doc.AddSection()
section.PageSetup.Margins.All = 72.0

# 段落スタイルを作成する
style = ParagraphStyle(doc)
style.Name = "例のスタイル"
style.CharacterFormat.FontName = "Yu Gothic UI"
style.CharacterFormat.FontSize = 16.0
doc.Styles.Add(style)

# 段落を追加する
paragraph = section.AddParagraph()
paragraph.ApplyStyle(style.Name)
paragraph.AppendHyperlink("https://jp.e-iceblue.com/", "ホームページ", HyperlinkType.WebLink)

# 改行を挿入する
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# メールリンクを追加する
paragraph.AppendHyperlink("mailto:support @e-iceblue.com", "メールを送る", HyperlinkType.EMailLink)

# 改行を挿入する
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# ファイルリンクを追加する
filePath = "レポート.xlsx"
paragraph.AppendHyperlink(filePath, "レポートを開く", HyperlinkType.FileLink)

# 改行を挿入する
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 別のセクションを追加し、ブックマークを作成する
section2 = doc.AddSection()
bookmarkParagraph = section2.AddParagraph()
bookmarkParagraph.AppendText("ここにブックマークがあります")
start = bookmarkParagraph.AppendBookmarkStart("myBookmark")
bookmarkParagraph.Items.Insert(0, start)
bookmarkParagraph.AppendBookmarkEnd("myBookmark")

# ブックマークへのリンクを追加する
paragraph.AppendHyperlink("myBookmark", "この文書内の場所へ移動", HyperlinkType.Bookmark)

# 改行を挿入する
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 画像リンクを追加する
imagePath = "Logo.png"
picture = paragraph.AppendPicture(imagePath)
paragraph.AppendHyperlink("https://jp.e-iceblue.com/", picture, HyperlinkType.WebLink)

# ファイルに保存する
doc.SaveToFile("output/Wordでハイパーリンクを作成.docx", FileFormat.Docx2019)
doc.Dispose()

PythonコードによるWord文書へのハイパーリンク挿入

Python で Word からハイパーリンクを削除する

Word 文書内のすべてのハイパーリンクを一度に削除するには、文書内のすべてのハイパーリンクを見つけて、それらをフラット化するカスタムメソッド FlattenHyperlinks() を作成する必要があります。以下に詳細な手順を示します。

  • Document オブジェクトを作成します。
  • Document.LoadFromFile() メソッドを使用して、サンプルの Word 文書を読み込みます。
  • カスタムメソッド FindAllHyperlinks() を使用して、文書内のすべてのハイパーリンクを見つけます。
  • ハイパーリンクをループして、カスタムメソッド FlattenHyperlinks() を使用してすべてをフラット化します。
  • Document.SaveToFile() メソッドを使用して、結果の文書を保存します。
  • Python
from spire.doc import *
from spire.doc.common import *


# ドキュメント内のすべてのハイパーリンクを検索する関数
def FindAllHyperlinks(document):
    hyperlinks = []
    for i in range(document.Sections.Count):
        section = document.Sections.get_Item(i)
        for j in range(section.Body.ChildObjects.Count):
            sec = section.Body.ChildObjects.get_Item(j)
            if sec.DocumentObjectType == DocumentObjectType.Paragraph:
                for k in range((sec if isinstance(sec, Paragraph) else None).ChildObjects.Count):
                    para = (sec if isinstance(sec, Paragraph)
                            else None).ChildObjects.get_Item(k)
                    if para.DocumentObjectType == DocumentObjectType.Field:
                        field = para if isinstance(para, Field) else None
                        if field.Type == FieldType.FieldHyperlink:
                            hyperlinks.append(field)
    return hyperlinks


# ハイパーリンクフィールドを平坦化する関数
def FlattenHyperlinks(field):
    ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.OwnerParagraph)
    fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field)
    sepOwnerPara = field.Separator.OwnerParagraph
    sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.Separator.OwnerParagraph)
    sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(
        field.Separator)
    endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End)
    endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.End.OwnerParagraph)

    FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody,
                          sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex)

    field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex)

    for i in range(sepOwnerParaIndex, ownerParaIndex - 1, -1):
        if i == sepOwnerParaIndex and i == ownerParaIndex:
            for j in range(sepIndex, fieldIndex - 1, -1):
                field.OwnerParagraph.ChildObjects.RemoveAt(j)

        elif i == ownerParaIndex:
            for j in range(field.OwnerParagraph.ChildObjects.Count - 1, fieldIndex - 1, -1):
                field.OwnerParagraph.ChildObjects.RemoveAt(j)

        elif i == sepOwnerParaIndex:
            for j in range(sepIndex, -1, -1):
                sepOwnerPara.ChildObjects.RemoveAt(j)
        else:
            field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i)


# フィールドをテキスト範囲に変換し、テキストの書式設定をクリアする関数
def FormatFieldResultText(ownerBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex):
    for i in range(sepOwnerParaIndex, endOwnerParaIndex + 1):
        para = ownerBody.ChildObjects[i] if isinstance(
            ownerBody.ChildObjects[i], Paragraph) else None
        if i == sepOwnerParaIndex and i == endOwnerParaIndex:
            for j in range(sepIndex + 1, endIndex):
                if isinstance(para.ChildObjects[j], TextRange):
                    FormatText(para.ChildObjects[j])

        elif i == sepOwnerParaIndex:
            for j in range(sepIndex + 1, para.ChildObjects.Count):
                if isinstance(para.ChildObjects[j], TextRange):
                    FormatText(para.ChildObjects[j])
        elif i == endOwnerParaIndex:
            for j in range(0, endIndex):
                if isinstance(para.ChildObjects[j], TextRange):
                    FormatText(para.ChildObjects[j])
        else:
            for j, unusedItem in enumerate(para.ChildObjects):
                if isinstance(para.ChildObjects[j], TextRange):
                    FormatText(para.ChildObjects[j])


# テキストをフォーマットする関数
def FormatText(tr):
    tr.CharacterFormat.TextColor = Color.get_Black()
    tr.CharacterFormat.UnderlineStyle = UnderlineStyle.none


# ドキュメントオブジェクトを作成
doc = Document()

# Wordファイルを読み込む
doc.LoadFromFile("output/Wordでハイパーリンクを作成.docx")

# すべてのハイパーリンクを取得
hyperlinks = FindAllHyperlinks(doc)

# すべてのハイパーリンクを平坦化
for i in range(len(hyperlinks) - 1, -1, -1):
    FlattenHyperlinks(hyperlinks[i])

# 異なるファイルに保存
doc.SaveToFile("output/Wordからハイパーリンクを削除.docx")
doc.Close()

Spire.DocでWord文書からハイパーリンクを削除

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Read 21 times