C#/VB.NET : insérer des liens hypertexte vers des documents Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
Un lien hypertexte dans un document Word permet aux lecteurs de passer de son emplacement à un autre endroit du document, ou à un autre fichier ou site Web, ou à un nouveau message électronique. Les hyperliens permettent aux lecteurs de naviguer rapidement et facilement vers des informations connexes. Cet article montre comment ajoutez des hyperliens vers du texte ou des images en C# et VB.NET à l'aide de Spire.Doc for .NET.
- Insérer des hyperliens lors de l'ajout de paragraphes à Word
- Ajouter des hyperliens au texte existant dans Word
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
Insérer des hyperliens lors de l'ajout de paragraphes à Word
Spire.Doc propose la méthode Paragraph.AppendHyperlink() pour ajouter un lien Web, un lien de courrier électronique, un lien de fichier ou un lien de signet à un morceau de texte ou une image à l'intérieur d'un paragraphe. Voici les étapes détaillées.
- Créez un objet Document.
- Ajoutez-y une section et un paragraphe.
- Insérez un lien hypertexte basé sur du texte à l’aide de la méthode Paragraph.AppendHyerplink (string link, string text, HyperlinkType type).
- Ajoutez une image au paragraphe à l’aide de la méthode Paragraph.AppendPicture().
- Insérez un lien hypertexte basé sur l'image à l'aide de la méthode Paragraph.AppendHyerplink (string link, Spire.Doc.Fields.DocPicture, type HyperlinkType).
- Enregistrez le document à l'aide de la méthode 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); } } }
Ajouter des hyperliens au texte existant dans Word
L'ajout d'hyperliens vers du texte existant dans un document est un peu plus compliqué. Vous devrez d’abord trouver la chaîne cible, puis la remplacer dans le paragraphe par un champ de lien hypertexte. Voici les étapes.
- Créez un objet Document.
- Chargez un fichier Word à l'aide de la méthode Document.LoadFromFile().
- Recherchez toutes les occurrences de la chaîne cible dans le document à l'aide de la méthode Document.FindAllString() et obtenez celle spécifique par son index dans la collection.
- Obtenez le propre paragraphe de la chaîne et sa position dans celui-ci.
- Supprimez la chaîne du paragraphe.
- Créez un champ de lien hypertexte et insérez-le à l'emplacement où se trouve la chaîne.
- Enregistrez le document dans un autre fichier à l'aide de la méthode 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); } } }
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 Images in Word
Table of Contents
Installed via NuGet
PM> Install-Package Spire.Doc
Related Links
Images in Word documents are often closely related to the textual content. Compared with documents full of text, documents with images are more illustrative and attractive. In this article, you will learn how to programmatically insert images in a Word document using Spire.Doc for .NET. With this professional Word library, you can also set the image size, position as well as wrapping styles.
- Insert Images and Set their Wrapping Styles in a Word Document
- Insert an Image at a Specified Location in a Word document
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 DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Insert Images and Set their Wrapping Styles in a Word Document
Spire.Doc for .NET supports common wrapping styles such as In Line with Text, Square, Tight, Through, Top and Bottom, Behind the Text as well as In Front of Text. Below are the detailed steps to insert images and then set their wrapping styles.
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Get the first section of the Word Document using Document.Sections[] property.
- Get a specified paragraph of the section using Section.Paragraphs[] property.
- Load an image and insert the image in the specified paragraph using Paragraph.AppendPicture() method.
- Set the wrapping style of the image using DocPicture.TextWrappingType property.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Insert an Image at a Specified Location in a Word document
The DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties offered by Spire.Doc for .NET allows you to insert an image at a specified location. The detailed steps are as follows.
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Get the first section of the Word Document using Document.Sections[] property.
- Get a specified paragraph of the section using Section.Paragraphs[] property.
- Load an image and insert the image to the document using Paragraph.AppendPicture() method.
- Set the horizontal and vertical position of the image using DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties.
- Set the height and width of the image using DocPicture.Width and DocPicture.Height properties.
- Set the wrapping style of the image using DocPicture.TextWrappingType property.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", 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 imagens no Word
Índice
Instalado via NuGet
PM> Install-Package Spire.Doc
Links Relacionados
As imagens em documentos do Word geralmente estão intimamente relacionadas ao conteúdo textual. Comparados com documentos cheios de texto, os documentos com imagens são mais ilustrativos e atraentes. Neste artigo, você aprenderá como programar insira imagens em um documento do Word usando Spire.Doc for .NET. Com esta biblioteca profissional do Word, você também pode defina o tamanho, a posição e os estilos de quebra da imagem.
- Insira imagens e defina seus estilos de quebra automática em um documento do Word
- Insira uma imagem em um local especificado em um documento do Word
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 DLLs podem ser baixados deste link ou instalados via NuGet.
PM> Install-Package Spire.Doc
Insira imagens e defina seus estilos de quebra automática em um documento do Word
Spire.Doc for .NET oferece suporte a estilos de quebra automática comuns, como Alinhado ao texto, Quadrado, Apertado, Através, Superior e Inferior, Atrás do texto e também Na frente do texto. Abaixo estão as etapas detalhadas para inserir imagens e definir seus estilos de quebra automática.
- Crie uma instância de documento.
- Carregue um documento do Word de amostra usando o método Document.LoadFromFile().
- Obtenha a primeira seção do documento do Word usando a propriedade Document.Sections[].
- Obtenha um parágrafo especificado da seção usando a propriedade Section.Paragraphs[].
- Carregue uma imagem e insira-a no parágrafo especificado usando o método Paragraph.AppendPicture().
- Defina o estilo de quebra automática da imagem usando a propriedade DocPicture.TextWrappingType.
- Salve o documento em outro arquivo usando o método Document.SaveToFile().
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Insira uma imagem em um local especificado em um documento do Word
As propriedades DocPicture.HorizontalPosition e DocPicture.VerticalPosition oferecidas pelo Spire.Doc for .NET permitem inserir uma imagem em um local especificado. As etapas detalhadas são as seguintes.
- Crie uma instância de documento.
- Carregue um documento do Word de amostra usando o método Document.LoadFromFile().
- Obtenha a primeira seção do documento do Word usando a propriedade Document.Sections[].
- Obtenha um parágrafo especificado da seção usando a propriedade Section.Paragraphs[].
- Carregue uma imagem e insira-a no documento usando o método Paragraph.AppendPicture().
- Defina a posição horizontal e vertical da imagem usando as propriedades DocPicture.HorizontalPosition e DocPicture.VerticalPosition.
- Defina a altura e a largura da imagem usando as propriedades DocPicture.Width e DocPicture.Height.
- Defina o estilo de quebra automática da imagem usando a propriedade DocPicture.TextWrappingType.
- Salve o documento em outro arquivo usando o método Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", 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 часто тесно связаны с текстовым содержимым. По сравнению с документами, полными текста, документы с изображениями более наглядны и привлекательны. В этой статье вы узнаете, как программно вставляйте изображения в документ Word с помощью Spire.Doc for .NET. С помощью этой профессиональной библиотеки Word вы также можете установить размер изображения, положение, а также стили обтекания.
- Вставка изображений и установка стилей их переноса в документ Word
- Вставка изображения в указанное место в документе Word
Установите Spire.Doc for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.Doc
Вставка изображений и установка стилей их переноса в документ Word
Spire.Doc for .NET поддерживает распространенные стили обтекания, такие как «В линию с текстом», «Квадрат», «Плотно», «Сквозь», «Сверху и снизу», «За текстом», а также «Перед текстом». Ниже приведены подробные инструкции по вставке изображений и настройке стилей их упаковки.
- Создайте экземпляр документа.
- Загрузите образец документа Word, используя метод Document.LoadFromFile().
- Получите первый раздел документа Word, используя свойство Document.Sections[].
- Получите указанный абзац раздела, используя свойство Раздел.Параграфы[].
- Загрузите изображение и вставьте его в указанный абзац, используя метод Paragraph.AppendPicture().
- Задайте стиль переноса изображения с помощью свойства DocPicture.TextWrappingType.
- Сохраните документ в другой файл, используя метод Document.SaveToFile().
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Вставка изображения в указанное место в документе Word
Свойства DocPicture.HorizontalPosition и DocPicture.VerticalPosition, предлагаемые Spire.Doc for .NET, позволяют вставлять изображение в указанное место. Подробные шаги заключаются в следующем.
- Создайте экземпляр документа.
- Загрузите образец документа Word, используя метод Document.LoadFromFile().
- Получите первый раздел документа Word, используя свойство Document.Sections[].
- Получите указанный абзац раздела, используя свойство аздел.Параграфы[]Р.
- Загрузите изображение и вставьте его в документ с помощью метода Paragraph.AppendPicture().
- Задайте горизонтальное и вертикальное положение изображения с помощью свойств DocPicture.HorizontalPosition и DocPicture.VerticalPosition.
- Задайте высоту и ширину изображения с помощью свойств DocPicture.Width и DocPicture.Height.
- Задайте стиль переноса изображения с помощью свойства DocPicture.TextWrappingType.
- Сохраните документ в другой файл, используя метод Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", FileFormat.Docx); } } }
Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
C#/VB.NET: Bilder in Word einfügen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.Doc
verwandte Links
Bilder in Word-Dokumenten stehen oft in engem Zusammenhang mit dem Textinhalt. Im Vergleich zu Dokumenten voller Text sind Dokumente mit Bildern anschaulicher und attraktiver. In diesem Artikel erfahren Sie, wie Sie programmgesteuert vorgehen Bilder in ein Word-Dokument einfügen Verwendung von Spire.Doc for .NET. Mit dieser professionellen Word-Bibliothek können Sie auch festlegen die Bildgröße, Position sowie Umbruchsstile.
- Fügen Sie Bilder ein und legen Sie deren Umbruchsstile in einem Word-Dokument fest
- Fügen Sie ein Bild an einer angegebenen Stelle in ein Word-Dokument ein
Installieren Sie Spire.Doc for .NET
Zunächst müssen Sie die im Spire.Doc für .NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
PM> Install-Package Spire.Doc
Fügen Sie Bilder ein und legen Sie deren Umbruchsstile in einem Word-Dokument fest
Spire.Doc for .NET unterstützt gängige Umbruchsstile wie „In einer Linie mit dem Text“, „Quadrat“, „Enge“, „Durchgehend“, „Oben und Unten“, „Hinter dem Text“ sowie „Vor dem Text“. Nachfolgend finden Sie die detaillierten Schritte zum Einfügen von Bildern und zum anschließenden Festlegen ihrer Umbruchsstile.
- Erstellen Sie eine Document-Instanz.
- Laden Sie ein Beispiel-Word-Dokument mit der Methode Document.LoadFromFile().
- Rufen Sie den ersten Abschnitt des Word-Dokuments mit der Eigenschaft Document.Sections[] ab.
- Rufen Sie mithilfe der Section.Paragraphs[]-Eigenschaft einen bestimmten Absatz des Abschnitts ab.
- Laden Sie ein Bild und fügen Sie das Bild mit der Methode Paragraph.AppendPicture() in den angegebenen Absatz ein.
- Legen Sie den Umbruchstil des Bildes mit der Eigenschaft DocPicture.TextWrappingType fest.
- Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer anderen Datei.
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Fügen Sie ein Bild an einer angegebenen Stelle in ein Word-Dokument ein
Mit den von Spire.Doc for .NET angebotenen Eigenschaften DocPicture.HorizontalPosition und DocPicture.VerticalPosition können Sie ein Bild an einer bestimmten Stelle einfügen. Die detaillierten Schritte sind wie folgt.
- Erstellen Sie eine Document-Instanz.
- Laden Sie ein Beispiel-Word-Dokument mit der Methode Document.LoadFromFile().
- Rufen Sie den ersten Abschnitt des Word-Dokuments mit der Eigenschaft Document.Sections[] ab.
- Rufen Sie mithilfe der Section.Paragraphs[]-Eigenschaft einen bestimmten Absatz des Abschnitts ab.
- Laden Sie ein Bild und fügen Sie das Bild mit der Methode Paragraph.AppendPicture() in das Dokument ein.
- Legen Sie die horizontale und vertikale Position des Bildes mithilfe der Eigenschaften DocPicture.HorizontalPosition und DocPicture.VerticalPosition fest.
- Legen Sie die Höhe und Breite des Bildes mithilfe der Eigenschaften DocPicture.Width und DocPicture.Height fest.
- Legen Sie den Umbruchstil des Bildes mit der Eigenschaft DocPicture.TextWrappingType fest.
- Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer anderen Datei.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", 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 imágenes en Word
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.Doc
enlaces relacionados
Las imágenes de los documentos de Word suelen estar estrechamente relacionadas con el contenido textual. Comparados con los documentos llenos de texto, los documentos con imágenes son más ilustrativos y atractivos. En este artículo, aprenderá cómo programar insertar imágenes en un documento de Word usando Spire.Doc for .NET. Con esta biblioteca profesional de Word, también puedes establezca el tamaño de la imagen, la posición y los estilos de envoltura.
- Insertar imágenes y establecer sus estilos de ajuste en un documento de Word
- Insertar una imagen en una ubicación especificada en un documento de Word
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 instalar a través de NuGet.
PM> Install-Package Spire.Doc
Insertar imágenes y establecer sus estilos de ajuste en un documento de Word
Spire.Doc for .NET admite estilos de ajuste comunes, como En línea con el texto, Cuadrado, Ajustado, A través, Superior e inferior, Detrás del texto y Delante del texto. A continuación se detallan los pasos para insertar imágenes y luego configurar sus estilos de envoltura.
- Cree una instancia de documento.
- Cargue un documento de Word de muestra utilizando el método Document.LoadFromFile().
- Obtenga la primera sección del documento de Word usando la propiedad Document.Sections[].
- Obtenga un párrafo específico de la sección usando la propiedad Sección.Paragraphs[].
- Cargue una imagen e insértela en el párrafo especificado usando el método Paragraph.AppendPicture().
- Establezca el estilo de ajuste de la imagen utilizando la propiedad DocPicture.TextWrappingType.
- Guarde el documento en otro archivo utilizando el método Document.SaveToFile().
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Insertar una imagen en una ubicación especificada en un documento de Word
Las propiedades DocPicture.HorizontalPosition y DocPicture.VerticalPosition ofrecidas por Spire.Doc for .NET le permiten insertar una imagen en una ubicación específica. Los pasos detallados son los siguientes.
- Cree una instancia de documento.
- Cargue un documento de Word de muestra utilizando el método Document.LoadFromFile().
- Obtenga la primera sección del documento de Word usando la propiedad Document.Sections[].
- Obtenga un párrafo específico de la sección usando la propiedad Sección.Paragraphs[].
- Cargue una imagen e insértela en el documento utilizando el método Paragraph.AppendPicture().
- Establezca la posición horizontal y vertical de la imagen utilizando las propiedades DocPicture.HorizontalPosition y DocPicture.VerticalPosition.
- Establezca la altura y el ancho de la imagen usando las propiedades DocPicture.Width y DocPicture.Height.
- Establezca el estilo de ajuste de la imagen utilizando la propiedad DocPicture.TextWrappingType.
- Guarde el documento en otro archivo utilizando el método Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", 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 문서의 이미지는 텍스트 내용과 밀접한 관련이 있는 경우가 많습니다. 텍스트로 가득한 문서에 비해 이미지가 포함된 문서는 더 설명적이고 매력적입니다. 이 기사에서는 프로그래밍 방식으로 방법을 배웁니다 Word 문서에 이미지 삽입 Spire.Doc for .NET사용합니다. 이 전문적인 Word 라이브러리를 사용하면 다음과 같은 작업도 할 수 있습니다 이미지 크기, 위치, 배치 스타일을 설정합니다.
Spire.Doc for .NET 설치
먼저 .NET 프로젝트의 참조로 Spire.Doc for .NET 패키지에 포함된 DLL 파일을 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.Doc
Word 문서에 이미지 삽입 및 배치 스타일 설정
Spire.Doc for .NET In Line with Text, Square, Tight, Through, Top and Bottom, Behind the Text 및 In Front of Text와 같은 일반적인 래핑 스타일을 지원합니다. 다음은 이미지를 삽입하고 배치 스타일을 설정하는 자세한 단계입니다.
- 문서 인스턴스를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 샘플 Word 문서를 로드합니다.
- Document.Sections[] 속성을 사용하여 Word 문서의 첫 번째 섹션을 가져옵니다.
- Section.Paragraphs[] 속성을 사용하여 섹션의 지정된 단락을 가져옵니다.
- Paragraph.AppendPicture() 메서드를 사용하여 이미지를 로드하고 지정된 단락에 이미지를 삽입합니다.
- DocPicture.TextWrappingType 속성을 사용하여 이미지의 래핑 스타일을 설정합니다.
- Document.SaveToFile() 메서드를 사용하여 문서를 다른 파일에 저장합니다.
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Word 문서의 지정된 위치에 이미지 삽입
Spire.Doc for .NET에서 제공하는 DocPicture.HorizontalPosition 및 DocPicture.VerticalPosition 속성을 사용하면 지정된 위치에 이미지를 삽입할 수 있습니다. 자세한 단계는 다음과 같습니다.
- 문서 인스턴스를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 샘플 Word 문서를 로드합니다.
- Document.Sections[] 속성을 사용하여 Word 문서의 첫 번째 섹션을 가져옵니다.
- Section.Paragraphs[] 속성을 사용하여 섹션의 지정된 단락을 가져옵니다.
- Paragraph.AppendPicture() 메서드를 사용하여 이미지를 로드하고 문서에 이미지를 삽입합니다.
- DocPicture.HorizontalPosition 및 DocPicture.VerticalPosition 속성을 사용하여 이미지의 가로 및 세로 위치를 설정합니다.
- DocPicture.Width 및 DocPicture.Height 속성을 사용하여 이미지의 높이와 너비를 설정합니다.
- DocPicture.TextWrappingType 속성을 사용하여 이미지의 래핑 스타일을 설정합니다.
- Document.SaveToFile() 메서드를 사용하여 문서를 다른 파일에 저장합니다.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", FileFormat.Docx); } } }
임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
C#/VB.NET: inserisci immagini in Word
Sommario
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
Le immagini nei documenti Word sono spesso strettamente correlate al contenuto testuale. Rispetto ai documenti pieni di testo, i documenti con immagini sono più illustrativi e attraenti. In questo articolo imparerai come farlo a livello di codice inserire immagini in un documento Word utilizzando Spire.Doc for .NET. Con questa libreria Word professionale, puoi anche farlo imposta la dimensione dell'immagine, la posizione e gli stili di avvolgimento.
- Inserisci immagini e imposta i relativi stili di disposizione in un documento Word
- Inserisci un'immagine in una posizione specificata in un documento di 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 immagini e imposta i relativi stili di disposizione in un documento Word
Spire.Doc for .NET supporta stili di disposizione comuni come In linea con il testo, Quadrato, Stretto, Attraverso, Alto e basso, Dietro il testo e Davanti al testo. Di seguito sono riportati i passaggi dettagliati per inserire immagini e quindi impostare i relativi stili di avvolgimento.
- Crea un'istanza del documento.
- Carica un documento Word di esempio utilizzando il metodo Document.LoadFromFile().
- Ottieni la prima sezione del documento di Word utilizzando la proprietà Document.Sections[].
- Ottieni un paragrafo specificato della sezione utilizzando la proprietà Sezione.Paragraphs[].
- Carica un'immagine e inserisci l'immagine nel paragrafo specificato utilizzando il metodo Paragraph.AppendPicture().
- Imposta lo stile di disposizione dell'immagine utilizzando la proprietà DocPicture.TextWrappingType.
- Salva il documento in un altro file utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Inserisci un'immagine in una posizione specificata in un documento di Word
Le proprietà DocPicture.HorizontalPosition e DocPicture.VerticalPosition offerte da Spire.Doc for .NET consentono di inserire un'immagine in una posizione specificata. I passaggi dettagliati sono i seguenti.
- Crea un'istanza del documento.
- Carica un documento Word di esempio utilizzando il metodo Document.LoadFromFile().
- Ottieni la prima sezione del documento di Word utilizzando la proprietà Document.Sections[].
- Ottieni un paragrafo specificato della sezione utilizzando la proprietà Sezione.Paragraphs[].
- Carica un'immagine e inserisci l'immagine nel documento utilizzando il metodo Paragraph.AppendPicture().
- Imposta la posizione orizzontale e verticale dell'immagine utilizzando le proprietà DocPicture.HorizontalPosition e DocPicture.VerticalPosition.
- Imposta l'altezza e la larghezza dell'immagine utilizzando le proprietà DocPicture.Width e DocPicture.Height.
- Imposta lo stile di disposizione dell'immagine utilizzando la proprietà DocPicture.TextWrappingType.
- Salva il documento in un altro file utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", 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.
C#/VB.NET : insérer des images dans Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
Les images des documents Word sont souvent étroitement liées au contenu textuel. Comparés aux documents remplis de texte, les documents contenant des images sont plus illustratifs et plus attrayants. Dans cet article, vous apprendrez à programmer insérez des images dans un document Word à l'aide de Spire.Doc for .NET. Avec cette bibliothèque Word professionnelle, vous pouvez également définir la taille, la position et les styles d'habillage de l'image.
- Insérer des images et définir leurs styles d'habillage dans un document Word
- Insérer une image à un emplacement spécifié dans un document Word
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
Insérer des images et définir leurs styles d'habillage dans un document Word
Spire.Doc for .NET prend en charge les styles d'habillage courants tels que Aligné avec le texte, Carré, Serré, Traversant, Haut et Bas, Derrière le texte ainsi que Devant le texte. Vous trouverez ci-dessous les étapes détaillées pour insérer des images, puis définir leurs styles d'habillage.
- Créez une instance de document.
- Chargez un exemple de document Word à l’aide de la méthode Document.LoadFromFile().
- Obtenez la première section du document Word à l’aide de la propriété Document.Sections[].
- Obtenez un paragraphe spécifié de la section à l’aide de la propriété Section.Paragraphs[].
- Chargez une image et insérez l'image dans le paragraphe spécifié à l'aide de la méthode Paragraph.AppendPicture().
- Définissez le style d'habillage de l'image à l'aide de la propriété DocPicture.TextWrappingType.
- Enregistrez le document dans un autre fichier à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Insérer une image à un emplacement spécifié dans un document Word
Les propriétés DocPicture.HorizontalPosition et DocPicture.VerticalPosition proposées par Spire.Doc for .NET vous permettent d'insérer une image à un emplacement spécifié. Les étapes détaillées sont les suivantes.
- Créez une instance de document.
- Chargez un exemple de document Word à l’aide de la méthode Document.LoadFromFile().
- Obtenez la première section du document Word à l’aide de la propriété Document.Sections[].
- Obtenez un paragraphe spécifié de la section à l’aide de la propriété Section.Paragraphs[].
- Chargez une image et insérez l'image dans le document à l'aide de la méthode Paragraph.AppendPicture().
- Définissez la position horizontale et verticale de l'image à l'aide des propriétés DocPicture.HorizontalPosition et DocPicture.VerticalPosition.
- Définissez la hauteur et la largeur de l'image à l'aide des propriétés DocPicture.Width et DocPicture.Height.
- Définissez le style d'habillage de l'image à l'aide de la propriété DocPicture.TextWrappingType.
- Enregistrez le document dans un autre fichier à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", FileFormat.Docx); } } }
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: Remove Paragraphs in a Word Document
Table of Contents
Installed via NuGet
PM> Install-Package Spire.Doc
Related Links
When processing a Word document, you may need to remove some paragraphs. For example, after you copied contents from the Internet with a lot of redundant paragraphs to your document, you need to delete the extra paragraphs and keep only those that are useful. The deletion can be easily achieved by Spire.Doc for .NET by programming with no need for other software. This article will show you the detailed steps of removing paragraphs in a Word document 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
Delete a Specific Paragraph in a Word Document
Spire.Doc for .NET provides a method RemoveAt() under ParagraphCollection to remove paragraphs.
The detailed steps of removing a specific paragraph are as follows:
- Create an object of Document class.
- Load a Word document using Document.LoadFromFile() method.
- Get the first section using Document.Section[] property.
- Remove the 4th paragraph using Section.Paragraphs.RemoveAt() method.
- Save the document using Document.SaveToFile() method.
- C#
- VB.NET
using System; using Spire.Doc; namespace RemoveParagraphs { internal class Program { static void Main(string[] args) { //Create an object of Document class Document document = new Document(); //Load a Word document document.LoadFromFile("Sample.docx"); //Get the first section Section section = document.Sections[0]; //Remove the first paragraph in the section section.Paragraphs.RemoveAt(3); //Save the document document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013); } } }
Delete All Paragraphs in a Word Document
To remove all paragraphs, you can use the method Clear() under ParagraphCollection provided by Spire.Doc for .NET.
The detailed steps are as follows:
- Create an object of Document class.
- Load a Word Document using Document.LoadFromFile() method.
- Loop through all sections, and remove all paragraphs in each section using Section.Paragraphs.Clear() method.
- Save the document using Document.SaveToFile() method.
- C#
- VB.NET
using System; using Spire.Doc; namespace RemoveAllParagraphs { internal class Program { static void Main(string[] args) { //Create an object of Document class Document document = new Document(); //Load a Word document document.LoadFromFile("Sample.docx"); //Loop through all sections foreach (Section section in document.Sections) { //Remove all paragraphs in the section section.Paragraphs.Clear(); } //Save the document document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013); } } }
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.