C#/VB.NET: Word에서 주석 추가, 회신 또는 삭제
목차
NuGet을 통해 설치됨
PM> Install-Package Spire.Doc
관련된 링크들
Microsoft Word의 주석 기능은 사람들이 문서의 내용을 변경하거나 중단하지 않고도 Word 문서에 통찰력이나 의견을 추가할 수 있는 훌륭한 방법을 제공합니다. 누군가 문서에 댓글을 달면 문서 작성자나 다른 사용자는 동시에 문서를 보고 있지 않더라도 댓글에 답하여 그 사람과 토론할 수 있습니다. 이 문서에서는 다음 방법을 보여줍니다 C# 및 VB.NET의 Word에서 주석 추가, 회신 또는 삭제 사용하여 Spire.Doc for .NET 도서관.
- C# 및 VB.NET에서 Word의 단락에 설명 추가
- C# 및 VB.NET에서 Word의 텍스트에 설명 추가
- C# 및 VB.NET의 Word에서 주석에 응답
- C# 및 VB.NET의 Word에서 주석 삭제
Spire.Doc for .NET 설치
먼저 Spire.Doc for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.Doc
C# 및 VB.NET에서 Word의 단락에 설명 추가
Spire.Doc for .NET은 특정 단락에 주석을 추가하기 위한 Paragraph.AppendComment() 메서드를 제공합니다. 자세한 단계는 다음과 같습니다.
- Document 클래스의 인스턴스를 초기화합니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.Sections[int] 속성을 통해 해당 인덱스로 문서의 특정 섹션에 액세스합니다.
- Section.Paragraphs[int] 속성을 통해 해당 색인으로 섹션의 특정 단락에 액세스합니다.
- Paragraph.AppendComment() 메서드를 사용하여 단락에 설명을 추가합니다.
- Comment.Format.Author 속성을 통해 댓글 작성자를 설정합니다.
- Document.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace AddComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"Sample.docx"); //Get the first section in the document Section section = document.Sections[0]; //Get the first paragraph in the section Paragraph paragraph = section.Paragraphs[0]; //Add a comment to the paragraph Comment comment = paragraph.AppendComment("This comment is added using Spire.Doc for .NET."); //Set comment author comment.Format.Author = "Eiceblue"; comment.Format.Initial = "CM"; //Save the result document document.SaveToFile("AddCommentToParagraph.docx", FileFormat.Docx2013); document.Close(); } } }
C# 및 VB.NET에서 Word의 텍스트에 설명 추가
Paragraph.AppendComment() 메서드는 전체 단락에 주석을 추가하는 데 사용됩니다. 기본적으로 주석 표시는 단락 끝에 배치됩니다. 특정 텍스트에 주석을 추가하려면 Document.FindString() 메서드를 사용하여 텍스트를 검색한 다음 텍스트의 시작과 끝 부분에 주석 표시를 배치해야 합니다. 자세한 단계는 다음과 같습니다.
- Document 클래스의 인스턴스를 초기화합니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.FindString() 메서드를 사용하여 문서에서 특정 텍스트를 찾습니다.
- 찾은 텍스트의 시작과 끝 부분에 각각 배치될 주석 시작 표시와 주석 끝 표시를 만듭니다.
- 새 댓글을 생성하려면 Comment 클래스의 인스턴스를 초기화하세요. 그런 다음 댓글의 내용과 작성자를 설정합니다.
- 발견된 텍스트의 소유자 단락을 가져옵니다. 그런 다음 단락에 주석을 하위 개체로 추가합니다.
- 텍스트 범위 앞에 주석 시작 표시를 삽입하고 텍스트 범위 뒤에 주석 끝 표시를 삽입합니다.
- Document.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace AddCommentsToText { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"CommentTemplate.docx"); //Find a specific string TextSelection find = document.FindString("Microsoft Office", false, true); //Create the comment start mark and comment end mark CommentMark commentmarkStart = new CommentMark(document); commentmarkStart.Type = CommentMarkType.CommentStart; CommentMark commentmarkEnd = new CommentMark(document); commentmarkEnd.Type = CommentMarkType.CommentEnd; //Create a comment and set its content and author Comment comment = new Comment(document); comment.Body.AddParagraph().Text = "Developed by Microsoft."; comment.Format.Author = "Shaun"; //Get the found text as a single text range TextRange range = find.GetAsOneRange(); //Get the owner paragraph of the text range Paragraph para = range.OwnerParagraph; //Add the comment to the paragraph para.ChildObjects.Add(comment); //Get the index of text range in the paragraph int index = para.ChildObjects.IndexOf(range); //Insert the comment start mark before the text range para.ChildObjects.Insert(index, commentmarkStart); //Insert the comment end mark after the text range para.ChildObjects.Insert(index + 2, commentmarkEnd); //Save the result document document.SaveToFile("AddCommentForText.docx", FileFormat.Docx2013); document.Close(); } } }
C# 및 VB.NET의 Word에서 주석에 응답
기존 댓글에 답글을 추가하려면 Comment.ReplyToComment() 메서드를 사용할 수 있습니다. 자세한 단계는 다음과 같습니다.
- Document 클래스의 인스턴스를 초기화합니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.Comments[int] 속성을 통해 문서의 특정 설명을 가져옵니다.
- 새 댓글을 생성하려면 Comment 클래스의 인스턴스를 초기화하세요. 그런 다음 댓글의 내용과 작성자를 설정합니다.
- Comment.ReplyToComment() 메서드를 사용하여 특정 댓글에 대한 응답으로 새 댓글을 추가합니다.
- Document.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Fields; namespace ReplyToComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"AddCommentToParagraph.docx"); //Get the first comment in the document Comment comment1 = document.Comments[0]; //Create a new comment and specify its author and content Comment replyComment1 = new Comment(document); replyComment1.Format.Author = "Michael"; replyComment1.Body.AddParagraph().AppendText("Spire.Doc is a wonderful Word library."); //Add the comment as a reply to the first comment comment1.ReplyToComment(replyComment1); //Save the result document document.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013); document.Close(); } } }
C# 및 VB.NET의 Word에서 주석 삭제
Spire.Doc for .NET Word 문서에서 특정 주석을 제거하는 Document.Comments.RemoveAt(int) 메서드와 Word 문서에서 모든 주석을 제거하는 Document.Comments.Clear() 메서드를 제공합니다. 자세한 단계는 다음과 같습니다.
- Document 클래스의 인스턴스를 초기화합니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.Comments.RemoveAt(int) 메서드 또는 Document.Comments.Clear() 메서드를 사용하여 문서의 특정 주석 또는 모든 주석을 삭제합니다.
- Document.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Doc; namespace DeleteComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"AddCommentToParagraph.docx"); //Delete the first comment in the document document.Comments.RemoveAt(0); //Delete all comments in the document //document.Comments.Clear(); //Save the result document document.SaveToFile("DeleteComment.docx", FileFormat.Docx2013); document.Close(); } } }
임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
C#/VB.NET: aggiungere, rispondere o eliminare commenti in Word
Sommario
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
La funzionalità di commento in Microsoft Word offre alle persone un modo eccellente per aggiungere i propri approfondimenti o opinioni a un documento di Word senza dover modificare o interrompere il contenuto del documento. Se qualcuno commenta un documento, l'autore del documento o altri utenti possono rispondere al commento per discutere con lui, anche se non stanno visualizzando il documento contemporaneamente. Questo articolo mostrerà come farlo aggiungere, rispondere o eliminare commenti in Word in C# e VB.NET utilizzando la libreria Spire.Doc for .NET.
- Aggiungi un commento al paragrafo in Word in C# e VB.NET
- Aggiungi un commento al testo in Word in C# e VB.NET
- Rispondi a un commento in Word in C# e VB.NET
- Elimina commenti in Word in C# e VB.NET
Installa Spire.Doc for .NET
Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.Doc per.NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
PM> Install-Package Spire.Doc
Aggiungi un commento al paragrafo in Word in C# e VB.NET
Spire.Doc for .NET fornisce il metodo Paragraph.AppendComment() per aggiungere un commento a un paragrafo specifico. Di seguito sono riportati i passaggi dettagliati:
- Inizializza un'istanza della classe Document.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Accedi a una sezione specifica del documento tramite il suo indice tramite la proprietà Document.Sections[int].
- Accedi a un paragrafo specifico nella sezione tramite il suo indice tramite la proprietà Sezione.Paragraphs[int].
- Aggiungi un commento al paragrafo utilizzando il metodo Paragraph.AppendComment().
- Imposta l'autore del commento tramite la proprietà Comment.Format.Author.
- Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace AddComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"Sample.docx"); //Get the first section in the document Section section = document.Sections[0]; //Get the first paragraph in the section Paragraph paragraph = section.Paragraphs[0]; //Add a comment to the paragraph Comment comment = paragraph.AppendComment("This comment is added using Spire.Doc for .NET."); //Set comment author comment.Format.Author = "Eiceblue"; comment.Format.Initial = "CM"; //Save the result document document.SaveToFile("AddCommentToParagraph.docx", FileFormat.Docx2013); document.Close(); } } }
Aggiungi un commento al testo in Word in C# e VB.NET
Il metodo Paragraph.AppendComment() viene utilizzato per aggiungere commenti a un intero paragrafo. Per impostazione predefinita, i contrassegni di commento verranno posizionati alla fine del paragrafo. Per aggiungere un commento a un testo specifico, è necessario cercare il testo utilizzando il metodo Document.FindString(), quindi posizionare i contrassegni di commento all'inizio e alla fine del testo. Di seguito sono riportati i passaggi dettagliati:
- Inizializza un'istanza della classe Document.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Trova il testo specifico nel documento utilizzando il metodo Document.FindString().
- Crea un segno di inizio commento e un segno di fine commento, che verranno posizionati rispettivamente all'inizio e alla fine del testo trovato.
- Inizializza un'istanza della classe Comment per creare un nuovo commento. Quindi imposta il contenuto e l'autore del commento.
- Ottieni il paragrafo proprietario del testo trovato. Quindi aggiungi il commento al paragrafo come oggetto figlio.
- Inserisci il segno di inizio commento prima dell'intervallo di testo e il segno di fine commento dopo l'intervallo di testo.
- Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace AddCommentsToText { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"CommentTemplate.docx"); //Find a specific string TextSelection find = document.FindString("Microsoft Office", false, true); //Create the comment start mark and comment end mark CommentMark commentmarkStart = new CommentMark(document); commentmarkStart.Type = CommentMarkType.CommentStart; CommentMark commentmarkEnd = new CommentMark(document); commentmarkEnd.Type = CommentMarkType.CommentEnd; //Create a comment and set its content and author Comment comment = new Comment(document); comment.Body.AddParagraph().Text = "Developed by Microsoft."; comment.Format.Author = "Shaun"; //Get the found text as a single text range TextRange range = find.GetAsOneRange(); //Get the owner paragraph of the text range Paragraph para = range.OwnerParagraph; //Add the comment to the paragraph para.ChildObjects.Add(comment); //Get the index of text range in the paragraph int index = para.ChildObjects.IndexOf(range); //Insert the comment start mark before the text range para.ChildObjects.Insert(index, commentmarkStart); //Insert the comment end mark after the text range para.ChildObjects.Insert(index + 2, commentmarkEnd); //Save the result document document.SaveToFile("AddCommentForText.docx", FileFormat.Docx2013); document.Close(); } } }
Rispondi a un commento in Word in C# e VB.NET
Per aggiungere una risposta a un commento esistente, puoi utilizzare il metodo Comment.ReplyToComment(). Di seguito sono riportati i passaggi dettagliati:
- Inizializza un'istanza della classe Document.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Ottieni un commento specifico nel documento tramite la proprietà Document.Comments[int].
- Inizializza un'istanza della classe Comment per creare un nuovo commento. Quindi imposta il contenuto e l'autore del commento.
- Aggiungi il nuovo commento come risposta al commento specifico utilizzando il metodo Comment.ReplyToComment().
- Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Fields; namespace ReplyToComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"AddCommentToParagraph.docx"); //Get the first comment in the document Comment comment1 = document.Comments[0]; //Create a new comment and specify its author and content Comment replyComment1 = new Comment(document); replyComment1.Format.Author = "Michael"; replyComment1.Body.AddParagraph().AppendText("Spire.Doc is a wonderful Word library."); //Add the comment as a reply to the first comment comment1.ReplyToComment(replyComment1); //Save the result document document.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013); document.Close(); } } }
Elimina commenti in Word in C# e VB.NET
Spire.Doc for .NET offre il metodo Document.Comments.RemoveAt(int) per rimuovere un commento specifico da un documento Word e il metodo Document.Comments.Clear() per rimuovere tutti i commenti da un documento Word. Di seguito sono riportati i passaggi dettagliati:
- Inizializza un'istanza della classe Document.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Elimina un commento specifico o tutti i commenti nel documento utilizzando il metodo Document.Comments.RemoveAt(int) o Document.Comments.Clear().
- Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; namespace DeleteComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"AddCommentToParagraph.docx"); //Delete the first comment in the document document.Comments.RemoveAt(0); //Delete all comments in the document //document.Comments.Clear(); //Save the result document document.SaveToFile("DeleteComment.docx", FileFormat.Docx2013); document.Close(); } } }
Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.
C#/VB.NET : ajouter, répondre ou supprimer des commentaires dans Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
La fonctionnalité de commentaire de Microsoft Word constitue un excellent moyen permettant aux utilisateurs d'ajouter leurs idées ou leurs opinions à un document Word sans avoir à modifier ou interrompre le contenu du document. Si quelqu'un commente un document, l'auteur du document ou d'autres utilisateurs peuvent répondre au commentaire pour discuter avec lui, même s'ils ne consultent pas le document en même temps. Cet article montrera comment ajoutez, répondez ou supprimez des commentaires dans Word en C# et VB.NET à l'aide de la bibliothèque Spire.Doc for .NET.
- Ajouter un commentaire au paragraphe dans Word en C# et VB.NET
- Ajouter un commentaire au texte dans Word en C# et VB.NET
- Répondre à un commentaire dans Word en C# et VB.NET
- Supprimer des commentaires dans Word en C# et VB.NET
Installer Spire.Doc for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc for.NET comme références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.
PM> Install-Package Spire.Doc
Ajouter un commentaire au paragraphe dans Word en C# et VB.NET
Spire.Doc for .NET fournit la méthode Paragraph.AppendComment() pour ajouter un commentaire à un paragraphe spécifique. Voici les étapes détaillées :
- Initialisez une instance de la classe Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Accédez à une section spécifique du document par son index via la propriété Document.Sections[int].
- Accédez à un paragraphe spécifique de la section par son index via la propriété Section.Paragraphs[int].
- Ajoutez un commentaire au paragraphe à l’aide de la méthode Paragraph.AppendComment().
- Définissez l’auteur du commentaire via la propriété Comment.Format.Author.
- Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace AddComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"Sample.docx"); //Get the first section in the document Section section = document.Sections[0]; //Get the first paragraph in the section Paragraph paragraph = section.Paragraphs[0]; //Add a comment to the paragraph Comment comment = paragraph.AppendComment("This comment is added using Spire.Doc for .NET."); //Set comment author comment.Format.Author = "Eiceblue"; comment.Format.Initial = "CM"; //Save the result document document.SaveToFile("AddCommentToParagraph.docx", FileFormat.Docx2013); document.Close(); } } }
Ajouter un commentaire au texte dans Word en C# et VB.NET
La méthode Paragraph.AppendComment() est utilisée pour ajouter des commentaires à un paragraphe entier. Par défaut, les marques de commentaire seront placées à la fin du paragraphe. Pour ajouter un commentaire à un texte spécifique, vous devez rechercher le texte à l'aide de la méthode Document.FindString(), puis placer les marques de commentaire au début et à la fin du texte. Voici les étapes détaillées :
- Initialisez une instance de la classe Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Recherchez le texte spécifique dans le document à l'aide de la méthode Document.FindString().
- Créez une marque de début de commentaire et une marque de fin de commentaire, qui seront placées respectivement au début et à la fin du texte trouvé.
- Initialisez une instance de la classe Comment pour créer un nouveau commentaire. Définissez ensuite le contenu et l'auteur du commentaire.
- Obtenez le paragraphe propriétaire du texte trouvé. Ajoutez ensuite le commentaire au paragraphe en tant qu'objet enfant.
- Insérez la marque de début du commentaire avant la plage de texte et la marque de fin du commentaire après la plage de texte.
- Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace AddCommentsToText { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"CommentTemplate.docx"); //Find a specific string TextSelection find = document.FindString("Microsoft Office", false, true); //Create the comment start mark and comment end mark CommentMark commentmarkStart = new CommentMark(document); commentmarkStart.Type = CommentMarkType.CommentStart; CommentMark commentmarkEnd = new CommentMark(document); commentmarkEnd.Type = CommentMarkType.CommentEnd; //Create a comment and set its content and author Comment comment = new Comment(document); comment.Body.AddParagraph().Text = "Developed by Microsoft."; comment.Format.Author = "Shaun"; //Get the found text as a single text range TextRange range = find.GetAsOneRange(); //Get the owner paragraph of the text range Paragraph para = range.OwnerParagraph; //Add the comment to the paragraph para.ChildObjects.Add(comment); //Get the index of text range in the paragraph int index = para.ChildObjects.IndexOf(range); //Insert the comment start mark before the text range para.ChildObjects.Insert(index, commentmarkStart); //Insert the comment end mark after the text range para.ChildObjects.Insert(index + 2, commentmarkEnd); //Save the result document document.SaveToFile("AddCommentForText.docx", FileFormat.Docx2013); document.Close(); } } }
Répondre à un commentaire dans Word en C# et VB.NET
Pour ajouter une réponse à un commentaire existant, vous pouvez utiliser la méthode Comment.ReplyToComment(). Voici les étapes détaillées :
- Initialisez une instance de la classe Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Obtenez un commentaire spécifique dans le document via la propriété Document.Comments[int].
- Initialisez une instance de la classe Comment pour créer un nouveau commentaire.Définissez ensuite le contenu et l'auteur du commentaire.
- Ajoutez le nouveau commentaire en réponse au commentaire spécifique à l'aide de la méthode Comment.ReplyToComment().
- Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Fields; namespace ReplyToComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"AddCommentToParagraph.docx"); //Get the first comment in the document Comment comment1 = document.Comments[0]; //Create a new comment and specify its author and content Comment replyComment1 = new Comment(document); replyComment1.Format.Author = "Michael"; replyComment1.Body.AddParagraph().AppendText("Spire.Doc is a wonderful Word library."); //Add the comment as a reply to the first comment comment1.ReplyToComment(replyComment1); //Save the result document document.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013); document.Close(); } } }
Supprimer des commentaires dans Word en C# et VB.NET
Spire.Doc for .NET propose la méthode Document.Comments.RemoveAt(int) pour supprimer un commentaire spécifique d'un document Word et la méthode Document.Comments.Clear() pour supprimer tous les commentaires d'un document Word. Voici les étapes détaillées :
- Initialisez une instance de la classe Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Supprimez un commentaire spécifique ou tous les commentaires du document à l'aide de la méthode Document.Comments.RemoveAt(int) ou Document.Comments.Clear().
- Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; namespace DeleteComments { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document document = new Document(); //Load a Word document document.LoadFromFile(@"AddCommentToParagraph.docx"); //Delete the first comment in the document document.Comments.RemoveAt(0); //Delete all comments in the document //document.Comments.Clear(); //Save the result document document.SaveToFile("DeleteComment.docx", FileFormat.Docx2013); document.Close(); } } }
Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
C#/VB.NET: Insert Hyperlinks to Word Documents
Table of Contents
Installed via NuGet
PM> Install-Package Spire.Doc
Related Links
A hyperlink within a Word document enables readers to jump from its location to a different place within the document, or to a different file or website, or to a new email message. Hyperlinks make it quick and easy for readers to navigate to related information. This article demonstrates how to add hyperlinks to text or images in C# and VB.NET using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Insert Hyperlinks When Adding Paragraphs to Word
Spire.Doc offers the Paragraph.AppendHyperlink() method to add a web link, an email link, a file link, or a bookmark link to a piece of text or an image inside a paragraph. The following are the detailed steps.
- Create a Document object.
- Add a section and a paragraph to it.
- Insert a hyperlink based on text using Paragraph.AppendHyerplink(string link, string text, HyperlinkType type) method.
- Add an image to the paragraph using Paragraph.AppendPicture() method.
- Insert a hyperlink based on the image using Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type) method.
- Save the document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace InsertHyperlinks { class Program { static void Main(string[] args) { //Create a Word document Document doc = new Document(); //Add a section Section section = doc.AddSection(); //Add a paragraph Paragraph paragraph = section.AddParagraph(); paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an email link paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add a file link string filePath = @"C:\Users\Administrator\Desktop\report.xlsx"; paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add another section and create a bookmark Section section2 = doc.AddSection(); Paragraph bookmarkParagrapg = section2.AddParagraph(); bookmarkParagrapg.AppendText("Here is a bookmark"); BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark"); bookmarkParagrapg.Items.Insert(0, start); bookmarkParagrapg.AppendBookmarkEnd("myBookmark"); //Link to the bookmark paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an image link Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png"); Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image); paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink); //Save to file doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013); } } }
Add Hyperlinks to Existing Text in Word
Adding hyperlinks to existing text in a document is a bit more complicated. You’ll need to find the target string first, and then replace it in the paragraph with a hyperlink field. The following are the steps.
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Find all the occurrences of the target string in the document using Document.FindAllString() method, and get the specific one by its index from the collection.
- Get the string’s own paragraph and its position in it.
- Remove the string from the paragraph.
- Create a hyperlink field and insert it to position where the string is located.
- Save the document to another file using Document.SaveToFle() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace AddHyperlinksToExistingText { class Program { static void Main(string[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //Find all the occurrences of the string ".NET Framework" in the document TextSelection[] selections = document.FindAllString(".NET Framework", true, true); //Get the second occurrence TextRange range = selections[1].GetAsOneRange(); //Get its owner paragraph Paragraph parapgraph = range.OwnerParagraph; //Get its position in the paragraph int index = parapgraph.Items.IndexOf(range); //Remove it from the paragraph parapgraph.Items.Remove(range); //Create a hyperlink field Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document); field.Type = Spire.Doc.FieldType.FieldHyperlink; Hyperlink hyperlink = new Hyperlink(field); hyperlink.Type = HyperlinkType.WebLink; hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework"; parapgraph.Items.Insert(index, field); //Insert a field mark "start" to the paragraph IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark); (start as FieldMark).Type = FieldMarkType.FieldSeparator; parapgraph.Items.Insert(index + 1, start); //Insert a text range between two field marks ITextRange textRange = new Spire.Doc.Fields.TextRange(document); textRange.Text = ".NET Framework"; textRange.CharacterFormat.Font = range.CharacterFormat.Font; textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue; textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single; parapgraph.Items.Insert(index + 2, textRange); //Insert a field mark "end" to the paragraph IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; parapgraph.Items.Insert(index + 3, end); //Save to file document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: inserir hiperlinks em documentos do Word
Índice
Instalado via NuGet
PM> Install-Package Spire.Doc
Links Relacionados
Um hiperlink em um documento do Word permite que os leitores saltem de seu local para um local diferente no documento, ou para um arquivo ou site diferente, ou para uma nova mensagem de email. Os hiperlinks facilitam e agilizam a navegação dos leitores pelas informações relacionadas. Este artigo demonstra como adicionar hiperlinks a texto ou imagens em C# e VB.NET usando Spire.Doc for .NET.
Instale o Spire.Doc for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.
PM> Install-Package Spire.Doc
Insira hiperlinks ao adicionar parágrafos ao Word
Spire.Doc oferece o método Paragraph.AppendHyperlink() para adicionar um link da web, um link de e-mail, um link de arquivo ou um link de marcador a um trecho de texto ou imagem dentro de um parágrafo. A seguir estão as etapas detalhadas.
- Crie um objeto Documento.
- Adicione uma seção e um parágrafo a ela.
- Insira um hiperlink baseado em texto usando o método Paragraph.AppendHyerplink(string link, string text, HyperlinkType type).
- Adicione uma imagem ao parágrafo usando o método Paragraph.AppendPicture().
- Insira um hiperlink baseado na imagem usando o método Paragraph.AppendHyerplink (string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type).
- Salve o documento usando o método Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace InsertHyperlinks { class Program { static void Main(string[] args) { //Create a Word document Document doc = new Document(); //Add a section Section section = doc.AddSection(); //Add a paragraph Paragraph paragraph = section.AddParagraph(); paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an email link paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add a file link string filePath = @"C:\Users\Administrator\Desktop\report.xlsx"; paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add another section and create a bookmark Section section2 = doc.AddSection(); Paragraph bookmarkParagrapg = section2.AddParagraph(); bookmarkParagrapg.AppendText("Here is a bookmark"); BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark"); bookmarkParagrapg.Items.Insert(0, start); bookmarkParagrapg.AppendBookmarkEnd("myBookmark"); //Link to the bookmark paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an image link Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png"); Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image); paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink); //Save to file doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013); } } }
Adicionar hiperlinks a texto existente no Word
Adicionar hiperlinks ao texto existente em um documento é um pouco mais complicado. Você precisará primeiro encontrar a string de destino e, em seguida, substituí-la no parágrafo por um campo de hiperlink. A seguir estão as etapas.
- Crie um objeto Documento.
- Carregue um arquivo Word usando o método Document.LoadFromFile().
- Encontre todas as ocorrências da string de destino no documento usando o método Document.FindAllString() e obtenha aquela específica por seu índice da coleção.
- Obtenha o próprio parágrafo da string e sua posição nele.
- Remova a string do parágrafo.
- Crie um campo de hiperlink e insira-o na posição onde a string está localizada.
- Salve o documento em outro arquivo usando o método Document.SaveToFle().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace AddHyperlinksToExistingText { class Program { static void Main(string[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //Find all the occurrences of the string ".NET Framework" in the document TextSelection[] selections = document.FindAllString(".NET Framework", true, true); //Get the second occurrence TextRange range = selections[1].GetAsOneRange(); //Get its owner paragraph Paragraph parapgraph = range.OwnerParagraph; //Get its position in the paragraph int index = parapgraph.Items.IndexOf(range); //Remove it from the paragraph parapgraph.Items.Remove(range); //Create a hyperlink field Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document); field.Type = Spire.Doc.FieldType.FieldHyperlink; Hyperlink hyperlink = new Hyperlink(field); hyperlink.Type = HyperlinkType.WebLink; hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework"; parapgraph.Items.Insert(index, field); //Insert a field mark "start" to the paragraph IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark); (start as FieldMark).Type = FieldMarkType.FieldSeparator; parapgraph.Items.Insert(index + 1, start); //Insert a text range between two field marks ITextRange textRange = new Spire.Doc.Fields.TextRange(document); textRange.Text = ".NET Framework"; textRange.CharacterFormat.Font = range.CharacterFormat.Font; textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue; textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single; parapgraph.Items.Insert(index + 2, textRange); //Insert a field mark "end" to the paragraph IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; parapgraph.Items.Insert(index + 3, end); //Save to file document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx); } } }
Solicite uma licença temporária
Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
C#/VB.NET: вставка гиперссылок в документы Word
Оглавление
Установлено через NuGet
PM> Install-Package Spire.Doc
Ссылки по теме
Гиперссылка в документе Word позволяет читателям перейти из ее местоположения в другое место документа, к другому файлу или веб-сайту, или к новому сообщению электронной почты. Гиперссылки позволяют читателям быстро и легко перейти к соответствующей информации. В этой статье показано, как добавляйте гиперссылки на текст или изображения в C# и VB.NET с помощью Spire.Doc for .NET.
- Вставка гиперссылок при добавлении абзацев в Word
- Добавить гиперссылки к существующему тексту в Word
Установите Spire.Doc for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.Doc
Вставка гиперссылок при добавлении абзацев в Word
Spire.Doc предлагает метод Paragraph.AppendHyperlink() для добавления веб-ссылки, ссылки по электронной почте, ссылки на файл или ссылки на закладку к фрагменту текста или изображению внутри абзаца. Ниже приведены подробные шаги.
- Создайте объект Документ.
- Добавьте к нему раздел и абзац.
- Вставьте гиперссылку на основе текста, используя метод Paragraph.AppendHyerplink(строковая ссылка, текст строки, тип HyperlinkType).
- Добавьте изображение в абзац, используя метод Paragraph.AppendPicture().
- Вставьте гиперссылку на основе изображения с помощью метода Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture image, тип HyperlinkType).
- Сохраните документ, используя метод Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace InsertHyperlinks { class Program { static void Main(string[] args) { //Create a Word document Document doc = new Document(); //Add a section Section section = doc.AddSection(); //Add a paragraph Paragraph paragraph = section.AddParagraph(); paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an email link paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add a file link string filePath = @"C:\Users\Administrator\Desktop\report.xlsx"; paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add another section and create a bookmark Section section2 = doc.AddSection(); Paragraph bookmarkParagrapg = section2.AddParagraph(); bookmarkParagrapg.AppendText("Here is a bookmark"); BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark"); bookmarkParagrapg.Items.Insert(0, start); bookmarkParagrapg.AppendBookmarkEnd("myBookmark"); //Link to the bookmark paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an image link Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png"); Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image); paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink); //Save to file doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013); } } }
Добавить гиперссылки к существующему тексту в Word
Добавление гиперссылок к существующему тексту в документе немного сложнее. Сначала вам нужно будет найти целевую строку, а затем заменить ее в абзаце полем гиперссылки. Ниже приведены шаги.
- Создайте объект Документ.
- Загрузите файл Word с помощью метода Document.LoadFromFile().
- Найдите все вхождения целевой строки в документе с помощью метода Document.FindAllString() и получите конкретную строку по ее индексу из коллекции.
- Получите собственный абзац строки и его позицию в нем.
- Удалите строку из абзаца.
- Создайте поле гиперссылки и вставьте его в то место, где находится строка.
- Сохраните документ в другой файл, используя метод Document.SaveToFle().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace AddHyperlinksToExistingText { class Program { static void Main(string[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //Find all the occurrences of the string ".NET Framework" in the document TextSelection[] selections = document.FindAllString(".NET Framework", true, true); //Get the second occurrence TextRange range = selections[1].GetAsOneRange(); //Get its owner paragraph Paragraph parapgraph = range.OwnerParagraph; //Get its position in the paragraph int index = parapgraph.Items.IndexOf(range); //Remove it from the paragraph parapgraph.Items.Remove(range); //Create a hyperlink field Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document); field.Type = Spire.Doc.FieldType.FieldHyperlink; Hyperlink hyperlink = new Hyperlink(field); hyperlink.Type = HyperlinkType.WebLink; hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework"; parapgraph.Items.Insert(index, field); //Insert a field mark "start" to the paragraph IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark); (start as FieldMark).Type = FieldMarkType.FieldSeparator; parapgraph.Items.Insert(index + 1, start); //Insert a text range between two field marks ITextRange textRange = new Spire.Doc.Fields.TextRange(document); textRange.Text = ".NET Framework"; textRange.CharacterFormat.Font = range.CharacterFormat.Font; textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue; textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single; parapgraph.Items.Insert(index + 2, textRange); //Insert a field mark "end" to the paragraph IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; parapgraph.Items.Insert(index + 3, end); //Save to file document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx); } } }
Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
C#/VB.NET: Hyperlinks in Word-Dokumente einfügen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.Doc
verwandte Links
Ein Hyperlink in einem Word-Dokument ermöglicht es Lesern, von seiner Position zu einer anderen Stelle im Dokument, zu einer anderen Datei oder Website oder zu einer neuen E-Mail-Nachricht zu springen. Mithilfe von Hyperlinks können Leser schnell und einfach zu verwandten Informationen navigieren. Dieser Artikel zeigt, wie es geht Fügen Sie Hyperlinks zu Text oder Bildern in C# und VB.NET hinzu , indem Sie Spire.Doc for .NETverwenden.
- Fügen Sie Hyperlinks ein, wenn Sie Absätze zu Word hinzufügen
- Fügen Sie Hyperlinks zu vorhandenem Text in Word hinzu
Installieren Sie Spire.Doc for .NET
Zunächst müssen Sie die im Spire.Doc for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
PM> Install-Package Spire.Doc
Fügen Sie Hyperlinks ein, wenn Sie Absätze zu Word hinzufügen
Spire.Doc bietet die Methode Paragraph.AppendHyperlink() an, um einen Weblink, einen E-Mail-Link, einen Dateilink oder einen Lesezeichen-Link zu einem Textabschnitt oder einem Bild innerhalb eines Absatzes hinzuzufügen. Im Folgenden finden Sie die detaillierten Schritte.
- Erstellen Sie ein Document-Objekt.
- Fügen Sie einen Abschnitt und einen Absatz hinzu.
- Fügen Sie einen Hyperlink basierend auf Text mit der Methode Paragraph.AppendHyerplink(string link, string text, HyperlinkType type) ein.
- Fügen Sie dem Absatz mit der Methode Paragraph.AppendPicture() ein Bild hinzu.
- Fügen Sie mithilfe der Methode Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type) einen Hyperlink basierend auf dem Bild ein.
- Speichern Sie das Dokument mit der Methode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace InsertHyperlinks { class Program { static void Main(string[] args) { //Create a Word document Document doc = new Document(); //Add a section Section section = doc.AddSection(); //Add a paragraph Paragraph paragraph = section.AddParagraph(); paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an email link paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add a file link string filePath = @"C:\Users\Administrator\Desktop\report.xlsx"; paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add another section and create a bookmark Section section2 = doc.AddSection(); Paragraph bookmarkParagrapg = section2.AddParagraph(); bookmarkParagrapg.AppendText("Here is a bookmark"); BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark"); bookmarkParagrapg.Items.Insert(0, start); bookmarkParagrapg.AppendBookmarkEnd("myBookmark"); //Link to the bookmark paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an image link Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png"); Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image); paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink); //Save to file doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013); } } }
Fügen Sie Hyperlinks zu vorhandenem Text in Word hinzu
Das Hinzufügen von Hyperlinks zu vorhandenem Text in einem Dokument ist etwas komplizierter. Sie müssen zuerst die Zielzeichenfolge finden und sie dann im Absatz durch ein Hyperlink-Feld ersetzen. Im Folgenden sind die Schritte aufgeführt.
- Erstellen Sie ein Document-Objekt.
- Laden Sie eine Word-Datei mit der Methode Document.LoadFromFile().
- Suchen Sie mit der Methode Document.FindAllString() nach allen Vorkommen der Zielzeichenfolge im Dokument und rufen Sie die spezifische Zeichenfolge anhand ihres Index aus der Sammlung ab.
- Rufen Sie den eigenen Absatz der Zeichenfolge und seine Position darin ab.
- Entfernen Sie die Zeichenfolge aus dem Absatz.
- Erstellen Sie ein Hyperlink-Feld und fügen Sie es an der Stelle ein, an der sich die Zeichenfolge befindet.
- Speichern Sie das Dokument mit der Methode Document.SaveToFle() in einer anderen Datei.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace AddHyperlinksToExistingText { class Program { static void Main(string[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //Find all the occurrences of the string ".NET Framework" in the document TextSelection[] selections = document.FindAllString(".NET Framework", true, true); //Get the second occurrence TextRange range = selections[1].GetAsOneRange(); //Get its owner paragraph Paragraph parapgraph = range.OwnerParagraph; //Get its position in the paragraph int index = parapgraph.Items.IndexOf(range); //Remove it from the paragraph parapgraph.Items.Remove(range); //Create a hyperlink field Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document); field.Type = Spire.Doc.FieldType.FieldHyperlink; Hyperlink hyperlink = new Hyperlink(field); hyperlink.Type = HyperlinkType.WebLink; hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework"; parapgraph.Items.Insert(index, field); //Insert a field mark "start" to the paragraph IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark); (start as FieldMark).Type = FieldMarkType.FieldSeparator; parapgraph.Items.Insert(index + 1, start); //Insert a text range between two field marks ITextRange textRange = new Spire.Doc.Fields.TextRange(document); textRange.Text = ".NET Framework"; textRange.CharacterFormat.Font = range.CharacterFormat.Font; textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue; textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single; parapgraph.Items.Insert(index + 2, textRange); //Insert a field mark "end" to the paragraph IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; parapgraph.Items.Insert(index + 3, end); //Save to file document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx); } } }
Beantragen Sie eine temporäre Lizenz
Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.
C#/VB.NET: insertar hipervínculos a documentos de Word
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.Doc
enlaces relacionados
Un hipervínculo dentro de un documento de Word permite a los lectores saltar desde su ubicación a un lugar diferente dentro del documento, a un archivo o sitio web diferente, o a un nuevo mensaje de correo electrónico. Los hipervínculos facilitan y agilizan la navegación de los lectores hacia información relacionada. Este artículo demuestra cómo agregar hipervínculos a texto o imágenes en C# y VB.NET usando Spire.Doc for .NET.
Instalar Spire.Doc for .NET
Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.Doc for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalado a través de NuGet.
PM> Install-Package Spire.Doc
Insertar hipervínculos al agregar párrafos a Word
Spire.Doc ofrece el método Paragraph.AppendHyperlink() para agregar un enlace web, un enlace de correo electrónico, un enlace de archivo o un enlace de marcador a un fragmento de texto o una imagen dentro de un párrafo. Los siguientes son los pasos detallados.
- Crea un objeto de documento.
- Agregue una sección y un párrafo.
- Inserte un hipervínculo basado en texto usando el método Paragraph.AppendHyerplink (enlace de cadena, texto de cadena, tipo HyperlinkType).
- Agregue una imagen al párrafo usando el método Paragraph.AppendPicture().
- Inserte un hipervínculo basado en la imagen usando el método Paragraph.AppendHyerplink (enlace de cadena, imagen Spire.Doc.Fields.DocPicture, tipo HyperlinkType).
- Guarde el documento utilizando el método Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace InsertHyperlinks { class Program { static void Main(string[] args) { //Create a Word document Document doc = new Document(); //Add a section Section section = doc.AddSection(); //Add a paragraph Paragraph paragraph = section.AddParagraph(); paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an email link paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add a file link string filePath = @"C:\Users\Administrator\Desktop\report.xlsx"; paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add another section and create a bookmark Section section2 = doc.AddSection(); Paragraph bookmarkParagrapg = section2.AddParagraph(); bookmarkParagrapg.AppendText("Here is a bookmark"); BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark"); bookmarkParagrapg.Items.Insert(0, start); bookmarkParagrapg.AppendBookmarkEnd("myBookmark"); //Link to the bookmark paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an image link Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png"); Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image); paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink); //Save to file doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013); } } }
Agregar hipervínculos a texto existente en Word
Agregar hipervínculos al texto existente en un documento es un poco más complicado. Primero deberá encontrar la cadena de destino y luego reemplazarla en el párrafo con un campo de hipervínculo. Los siguientes son los pasos.
- Crea un objeto de documento.
- Cargue un archivo de Word usando el método Document.LoadFromFile().
- Encuentre todas las apariciones de la cadena de destino en el documento utilizando el método Document.FindAllString() y obtenga la específica por su índice de la colección.
- Obtenga el párrafo propio de la cadena y su posición en él.
- Elimina la cadena del párrafo.
- Cree un campo de hipervínculo e insértelo en la posición donde se encuentra la cadena.
- Guarde el documento en otro archivo utilizando el método Document.SaveToFle().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace AddHyperlinksToExistingText { class Program { static void Main(string[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //Find all the occurrences of the string ".NET Framework" in the document TextSelection[] selections = document.FindAllString(".NET Framework", true, true); //Get the second occurrence TextRange range = selections[1].GetAsOneRange(); //Get its owner paragraph Paragraph parapgraph = range.OwnerParagraph; //Get its position in the paragraph int index = parapgraph.Items.IndexOf(range); //Remove it from the paragraph parapgraph.Items.Remove(range); //Create a hyperlink field Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document); field.Type = Spire.Doc.FieldType.FieldHyperlink; Hyperlink hyperlink = new Hyperlink(field); hyperlink.Type = HyperlinkType.WebLink; hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework"; parapgraph.Items.Insert(index, field); //Insert a field mark "start" to the paragraph IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark); (start as FieldMark).Type = FieldMarkType.FieldSeparator; parapgraph.Items.Insert(index + 1, start); //Insert a text range between two field marks ITextRange textRange = new Spire.Doc.Fields.TextRange(document); textRange.Text = ".NET Framework"; textRange.CharacterFormat.Font = range.CharacterFormat.Font; textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue; textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single; parapgraph.Items.Insert(index + 2, textRange); //Insert a field mark "end" to the paragraph IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; parapgraph.Items.Insert(index + 3, end); //Save to file document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx); } } }
Solicite una licencia temporal
Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.
C#/VB.NET: Word 문서에 하이퍼링크 삽입
NuGet을 통해 설치됨
PM> Install-Package Spire.Doc
관련된 링크들
Word 문서 내의 하이퍼링크를 통해 독자는 해당 위치에서 문서 내의 다른 위치, 다른 파일이나 웹 사이트, 새 전자 메일 메시지로 이동할 수 있습니다. 하이퍼링크를 사용하면 독자가 관련 정보를 빠르고 쉽게 탐색할 수 있습니다. 이 문서에서는 다음 방법을 보여줍니다 Spire.Doc for .NET사용하여 C# 및 VB.NET의 텍스트나 이미지에 하이퍼링크를 추가합니다.
Spire.Doc for .NET 설치
먼저 Spire.Doc for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.Doc
Word에 단락을 추가할 때 하이퍼링크 삽입
Spire.Doc은 단락 내부의 텍스트나 이미지에 웹 링크, 이메일 링크, 파일 링크 또는 책갈피 링크를 추가하는 Paragraph.AppendHyperlink() 메서드를 제공합니다. 자세한 단계는 다음과 같습니다.
- 문서 개체를 만듭니다.
- 섹션과 단락을 추가합니다.
- Paragraph.AppendHyerplink(문자열 링크, 문자열 텍스트, HyperlinkType 유형) 메소드를 사용하여 텍스트 기반 하이퍼링크를 삽입합니다.
- Paragraph.AppendPicture() 메서드를 사용하여 단락에 이미지를 추가합니다.
- Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type) 메소드를 이용하여 이미지를 기반으로 하이퍼링크를 삽입합니다.
- Document.SaveToFile() 메서드를 사용하여 문서를 저장합니다.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace InsertHyperlinks { class Program { static void Main(string[] args) { //Create a Word document Document doc = new Document(); //Add a section Section section = doc.AddSection(); //Add a paragraph Paragraph paragraph = section.AddParagraph(); paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an email link paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add a file link string filePath = @"C:\Users\Administrator\Desktop\report.xlsx"; paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add another section and create a bookmark Section section2 = doc.AddSection(); Paragraph bookmarkParagrapg = section2.AddParagraph(); bookmarkParagrapg.AppendText("Here is a bookmark"); BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark"); bookmarkParagrapg.Items.Insert(0, start); bookmarkParagrapg.AppendBookmarkEnd("myBookmark"); //Link to the bookmark paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an image link Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png"); Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image); paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink); //Save to file doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013); } } }
Word의 기존 텍스트에 하이퍼링크 추가
문서의 기존 텍스트에 하이퍼링크를 추가하는 것은 좀 더 복잡합니다. 먼저 대상 문자열을 찾은 다음 단락에서 하이퍼링크 필드로 바꿔야 합니다. 다음 단계를 따르세요.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 파일을 로드합니다.
- Document.FindAllString() 메서드를 사용하여 문서에서 대상 문자열의 모든 항목을 찾고 컬렉션의 인덱스를 통해 특정 항목을 가져옵니다.
- 문자열 자체의 단락과 그 위치를 가져옵니다.
- 단락에서 문자열을 제거합니다.
- 하이퍼링크 필드를 생성하고 문자열이 있는 위치에 삽입합니다.
- Document.SaveToFle() 메서드를 사용하여 문서를 다른 파일에 저장합니다.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace AddHyperlinksToExistingText { class Program { static void Main(string[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //Find all the occurrences of the string ".NET Framework" in the document TextSelection[] selections = document.FindAllString(".NET Framework", true, true); //Get the second occurrence TextRange range = selections[1].GetAsOneRange(); //Get its owner paragraph Paragraph parapgraph = range.OwnerParagraph; //Get its position in the paragraph int index = parapgraph.Items.IndexOf(range); //Remove it from the paragraph parapgraph.Items.Remove(range); //Create a hyperlink field Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document); field.Type = Spire.Doc.FieldType.FieldHyperlink; Hyperlink hyperlink = new Hyperlink(field); hyperlink.Type = HyperlinkType.WebLink; hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework"; parapgraph.Items.Insert(index, field); //Insert a field mark "start" to the paragraph IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark); (start as FieldMark).Type = FieldMarkType.FieldSeparator; parapgraph.Items.Insert(index + 1, start); //Insert a text range between two field marks ITextRange textRange = new Spire.Doc.Fields.TextRange(document); textRange.Text = ".NET Framework"; textRange.CharacterFormat.Font = range.CharacterFormat.Font; textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue; textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single; parapgraph.Items.Insert(index + 2, textRange); //Insert a field mark "end" to the paragraph IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; parapgraph.Items.Insert(index + 3, end); //Save to file document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx); } } }
임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
C#/VB.NET : insérer des liens hypertexte vers des documents Word
Sommario
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
Un collegamento ipertestuale all'interno di un documento Word consente ai lettori di passare dalla sua posizione a un punto diverso all'interno del documento, a un file o sito Web diverso o a un nuovo messaggio di posta elettronica. I collegamenti ipertestuali rendono semplice e veloce per i lettori la navigazione verso le informazioni correlate. Questo articolo illustra come aggiungere collegamenti ipertestuali a testo o immagini in C# e VB.NET utilizzando Spire.Doc for .NET.
- Inserisci collegamenti ipertestuali quando aggiungi paragrafi a Word
- Aggiungi collegamenti ipertestuali al testo esistente in Word
Installa Spire.Doc for .NET
Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.Doc for.NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
PM> Install-Package Spire.Doc
Inserisci collegamenti ipertestuali quando aggiungi paragrafi a Word
Spire.Doc offre il metodo Paragraph.AppendHyperlink() per aggiungere un collegamento Web, un collegamento e-mail, un collegamento a un file o un collegamento a un segnalibro a una parte di testo o un'immagine all'interno di un paragrafo. Di seguito sono riportati i passaggi dettagliati.
- Creare un oggetto Documento.
- Aggiungi una sezione e un paragrafo.
- Inserisci un collegamento ipertestuale basato sul testo utilizzando il metodo Paragraph.AppendHyerplink(string link, string text, HyperlinkType type).
- Aggiungi un'immagine al paragrafo utilizzando il metodo Paragraph.AppendPicture().
- Inserisci un collegamento ipertestuale basato sull'immagine utilizzando il metodo Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type).
- Salva il documento utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace InsertHyperlinks { class Program { static void Main(string[] args) { //Create a Word document Document doc = new Document(); //Add a section Section section = doc.AddSection(); //Add a paragraph Paragraph paragraph = section.AddParagraph(); paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an email link paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add a file link string filePath = @"C:\Users\Administrator\Desktop\report.xlsx"; paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add another section and create a bookmark Section section2 = doc.AddSection(); Paragraph bookmarkParagrapg = section2.AddParagraph(); bookmarkParagrapg.AppendText("Here is a bookmark"); BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark"); bookmarkParagrapg.Items.Insert(0, start); bookmarkParagrapg.AppendBookmarkEnd("myBookmark"); //Link to the bookmark paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark); //Append line breaks paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendBreak(BreakType.LineBreak); //Add an image link Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png"); Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image); paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink); //Save to file doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013); } } }
Aggiungi collegamenti ipertestuali al testo esistente in Word
Aggiungere collegamenti ipertestuali al testo esistente in un documento è un po' più complicato. Dovrai prima trovare la stringa di destinazione, quindi sostituirla nel paragrafo con un campo di collegamento ipertestuale. Di seguito sono riportati i passaggi.
- Creare un oggetto Documento.
- Carica un file Word utilizzando il metodo Document.LoadFromFile().
- Trova tutte le occorrenze della stringa di destinazione nel documento utilizzando il metodo Document.FindAllString() e ottieni quella specifica in base al suo indice dalla raccolta.
- Ottieni il paragrafo della stringa e la sua posizione al suo interno.
- Rimuovere la stringa dal paragrafo.
- Crea un campo collegamento ipertestuale e inseriscilo nella posizione in cui si trova la stringa.
- Salva il documento in un altro file utilizzando il metodo Document.SaveToFle().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace AddHyperlinksToExistingText { class Program { static void Main(string[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //Find all the occurrences of the string ".NET Framework" in the document TextSelection[] selections = document.FindAllString(".NET Framework", true, true); //Get the second occurrence TextRange range = selections[1].GetAsOneRange(); //Get its owner paragraph Paragraph parapgraph = range.OwnerParagraph; //Get its position in the paragraph int index = parapgraph.Items.IndexOf(range); //Remove it from the paragraph parapgraph.Items.Remove(range); //Create a hyperlink field Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document); field.Type = Spire.Doc.FieldType.FieldHyperlink; Hyperlink hyperlink = new Hyperlink(field); hyperlink.Type = HyperlinkType.WebLink; hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework"; parapgraph.Items.Insert(index, field); //Insert a field mark "start" to the paragraph IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark); (start as FieldMark).Type = FieldMarkType.FieldSeparator; parapgraph.Items.Insert(index + 1, start); //Insert a text range between two field marks ITextRange textRange = new Spire.Doc.Fields.TextRange(document); textRange.Text = ".NET Framework"; textRange.CharacterFormat.Font = range.CharacterFormat.Font; textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue; textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single; parapgraph.Items.Insert(index + 2, textRange); //Insert a field mark "end" to the paragraph IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; parapgraph.Items.Insert(index + 3, end); //Save to file document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx); } } }
Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.