Tutoriel sur les éléments de document en C#
IronWord est une puissante bibliothèque de documents Word conçue pour aider les développeurs .NET C# à intégrer les fonctionnalités de création, de lecture et de modification de documents Word et DOCX dans leurs applications. Dans le contexte d'un document Word, les éléments du document sont les composants de base qui constituent le contenu.
Démarrage rapide : Créer un TextRun stylisé et y intégrer une imageVoici comment vous pouvez utiliser IronWord pour ajouter du contenu enrichi - en combinant du texte stylé et une image intégrée dans un document. Cet exemple démontre le modèle de conteneur Run pour le texte stylé.
-
1Installez IronWord avec NuGet Package Manager
-
2Copiez et exécutez cet extrait de code.
using IronWord; using IronWord.Models; // Create document WordDocument doc = new WordDocument(); // Create styled Run Run textRun = new Run(new TextContent("Hello IronWord!")); textRun.Style = new TextStyle() { IsBold = true, Color = Color.Blue }; // Create paragraph and add Run Paragraph paragraph = new Paragraph(); paragraph.AddChild(textRun); paragraph.AddImage(new ImageContent("pic.png")); // Add to document and save doc.AddParagraph(paragraph); doc.SaveAs("output.docx");Imports IronWord Imports IronWord.Models ' Create document Dim doc As New WordDocument() ' Create styled Run Dim textRun As New Run(New TextContent("Hello IronWord!")) textRun.Style = New TextStyle() With {.IsBold = True, .Color = Color.Blue} ' Create paragraph and add Run Dim paragraph As New Paragraph() paragraph.AddChild(textRun) paragraph.AddImage(New ImageContent("pic.png")) ' Add to document and save doc.AddParagraph(paragraph) doc.SaveAs("output.docx")Imports IronWord Imports IronWord.Models ' Create document Dim doc As New WordDocument() ' Create styled Run Dim textRun As New Run(New TextContent("Hello IronWord!")) textRun.Style = New TextStyle() With {.IsBold = True, .Color = Color.Blue} ' Create paragraph and add Run Dim paragraph As New Paragraph() paragraph.AddChild(textRun) paragraph.AddImage(New ImageContent("pic.png")) ' Add to document and save doc.AddParagraph(paragraph) doc.SaveAs("output.docx") -
3Déployez pour tester sur votre environnement de production.
Commencez à utiliser IronWord dans votre projet dès aujourd'hui avec un essai gratuit
Table des matières
- Ajouter du texte
- Contenu du texte (Ajouter, Ajouter à la fin & Diviser)
- Définir le style (Famille de polices & Taille, Couleur, Gras & Italique, Barré, Souligné, Exposant & Indice)
- Intégrer des images
- Ajouter des images
- Charger une image (Fichier & FileStream)
- Définir l'habillage du texte
- Définir les dimensions (Largeur & Hauteur)
- Définir le décalage de position
- Définir la distance par rapport aux coins
Concepts Clés
Hiérarchie des documents
IronWord suit une hiérarchie de document structurée : Document → Paragraph → Run → TextContent. Comprendre cette hiérarchie est essentiel pour travailler avec du texte stylisé :
WordDocument: Le conteneur de niveau supérieur représentant l'ensemble du documentParagraph: Un bloc de contenu dans le documentRun: Un objet conteneur qui contientTextContentet peut avoir un style appliquéTextContent: La chaîne de texte réelle
Ajouter du contenu aux paragraphes
IronWord propose deux méthodes pour ajouter du contenu aux paragraphes :
AddText(TextContent): À utiliser pour le texte brut non stylé. AjouteTextContentdirectement au paragraphe.AddChild(Run): À utiliser pour le texte stylé. Ajoute un objetRun(qui entoureTextContentet contient le style) au paragraphe.
Lorsque vous devez appliquer un style tel que la taille de la police, la couleur ou le formatage en gras, créez un objet Run, assignez un TextStyle au Run, et utilisez AddChild pour l'ajouter au paragraphe.
Ajouter des TextRuns
Contenu textuel
La méthode Split est utilisée pour diviser le flux de texte en une liste de plus petits flux de texte, basé sur un délimiteur spécifié. Cela permet d'organiser et de manipuler les informations textuelles au sein du document.
using IronWord;
using IronWord.Models;
WordDocument doc = new WordDocument();
// Add text
TextContent addText = new TextContent("Add text using IronWord");
doc.AddParagraph(new Paragraph(addText));
// Append text
TextContent appendText = new TextContent("The first text.");
appendText.Append(new TextContent("The second text."));
doc.AddParagraph(new Paragraph(appendText));
// Split text
TextContent splitText = new TextContent("Use split to split the sentence.");
splitText.Split(" ");
doc.AddParagraph(new Paragraph(splitText));
// Export docx
doc.SaveAs("textrun.docx");using IronWord;
using IronWord.Models;
WordDocument doc = new WordDocument();
// Add text
TextContent addText = new TextContent("Add text using IronWord");
doc.AddParagraph(new Paragraph(addText));
// Append text
TextContent appendText = new TextContent("The first text.");
appendText.Append(new TextContent("The second text."));
doc.AddParagraph(new Paragraph(appendText));
// Split text
TextContent splitText = new TextContent("Use split to split the sentence.");
splitText.Split(" ");
doc.AddParagraph(new Paragraph(splitText));
// Export docx
doc.SaveAs("textrun.docx");Imports IronWord
Imports IronWord.Models
Private doc As New WordDocument()
' Add text
Private addText As New TextContent("Add text using IronWord")
doc.AddParagraph(New Paragraph(addText))
' Append text
Dim appendText As New TextContent("The first text.")
appendText.Append(New TextContent("The second text."))
doc.AddParagraph(New Paragraph(appendText))
' Split text
Dim splitText As New TextContent("Use split to split the sentence.")
splitText.Split(" ")
doc.AddParagraph(New Paragraph(splitText))
' Export docx
doc.SaveAs("textrun.docx")Imports IronWord
Imports IronWord.Models
Private doc As New WordDocument()
' Add text
Private addText As New TextContent("Add text using IronWord")
doc.AddParagraph(New Paragraph(addText))
' Append text
Dim appendText As New TextContent("The first text.")
appendText.Append(New TextContent("The second text."))
doc.AddParagraph(New Paragraph(appendText))
' Split text
Dim splitText As New TextContent("Use split to split the sentence.")
splitText.Split(" ")
doc.AddParagraph(New Paragraph(splitText))
' Export docx
doc.SaveAs("textrun.docx")Mise en scène
Définir le style du texte nécessite d'utiliser le modèle de conteneur Run. Créez un objet Run contenant TextContent, puis assignez un TextStyle au Run (pas au TextContent). Le TextStyle vous permet de définir des attributs visuels tels que FontSize, couleur, gras, italique, barré, souligné, exposant et indice.
Notez que FontSize est configuré au niveau TextStyle, tandis que FontFamily est défini à l'intérieur de la propriété TextFont. Une fois stylé, utilisez AddChild pour ajouter le Run à un paragraphe. Cela suit la hiérarchie de document : Document → Paragraph → Run → TextContent.
using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;
// Load docx
WordDocument doc = new WordDocument("document.docx");
// Configure text
Run textRun = new Run(new TextContent("Add text using IronWord"));
textRun.Style = new TextStyle()
{
FontSize = 72,
TextFont = new Font()
{
FontFamily = "Caveat"
},
Color = Color.Red,
IsBold = true,
IsItalic = true,
Underline = new Underline(),
Strike = StrikeValue.Strike,
};
Paragraph paragraph = new Paragraph();
// Add text
paragraph.AddChild(textRun);
// Add paragraph
doc.AddParagraph(paragraph);
// Export docx
doc.SaveAs("save_document.docx");using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;
// Load docx
WordDocument doc = new WordDocument("document.docx");
// Configure text
Run textRun = new Run(new TextContent("Add text using IronWord"));
textRun.Style = new TextStyle()
{
FontSize = 72,
TextFont = new Font()
{
FontFamily = "Caveat"
},
Color = Color.Red,
IsBold = true,
IsItalic = true,
Underline = new Underline(),
Strike = StrikeValue.Strike,
};
Paragraph paragraph = new Paragraph();
// Add text
paragraph.AddChild(textRun);
// Add paragraph
doc.AddParagraph(paragraph);
// Export docx
doc.SaveAs("save_document.docx");Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums
' Load docx
Dim doc As New WordDocument("document.docx")
' Configure text
Dim textRun As New Run(New TextContent("Add text using IronWord"))
textRun.Style = New TextStyle() With {
.FontSize = 72,
.TextFont = New Font() With {
.FontFamily = "Caveat"
},
.Color = Color.Red,
.IsBold = True,
.IsItalic = True,
.Underline = New Underline(),
.Strike = StrikeValue.Strike
}
Dim paragraph As New Paragraph()
' Add text
paragraph.AddChild(textRun)
' Add paragraph
doc.AddParagraph(paragraph)
' Export docx
doc.SaveAs("save_document.docx")Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums
' Load docx
Dim doc As New WordDocument("document.docx")
' Configure text
Dim textRun As New Run(New TextContent("Add text using IronWord"))
textRun.Style = New TextStyle() With {
.FontSize = 72,
.TextFont = New Font() With {
.FontFamily = "Caveat"
},
.Color = Color.Red,
.IsBold = True,
.IsItalic = True,
.Underline = New Underline(),
.Strike = StrikeValue.Strike
}
Dim paragraph As New Paragraph()
' Add text
paragraph.AddChild(textRun)
' Add paragraph
doc.AddParagraph(paragraph)
' Export docx
doc.SaveAs("save_document.docx")Obtenir la couleur de remplissage du texte
Outre le fait de définir le style, IronWord vous permet d'obtenir la valeur de couleur RGBA des documents existants pour conserver la cohérence dans le style.
using IronWord;
using IronWord.Models;
using System;
// Open existing Word
WordDocument doc = new WordDocument("Accent1TextThemcolor.docx");
TextContent content = doc.Texts[0];
// This will show the R G B A of the themecolor
var filledColor = content.Color;
// Print the filled color variable to the console
Console.WriteLine(filledColor);using IronWord;
using IronWord.Models;
using System;
// Open existing Word
WordDocument doc = new WordDocument("Accent1TextThemcolor.docx");
TextContent content = doc.Texts[0];
// This will show the R G B A of the themecolor
var filledColor = content.Color;
// Print the filled color variable to the console
Console.WriteLine(filledColor);Imports IronWord
Imports IronWord.Models
Imports System
' Open existing Word
Dim doc As New WordDocument("Accent1TextThemcolor.docx")
Dim content As TextContent = doc.Texts(0)
' This will show the R G B A of the themecolor
Dim filledColor = content.Color
' Print the filled color variable to the console
Console.WriteLine(filledColor)Imports IronWord
Imports IronWord.Models
Imports System
' Open existing Word
Dim doc As New WordDocument("Accent1TextThemcolor.docx")
Dim content As TextContent = doc.Texts(0)
' This will show the R G B A of the themecolor
Dim filledColor = content.Color
' Print the filled color variable to the console
Console.WriteLine(filledColor)Pour récupérer des valeurs de couleur, chargez le document en utilisant WordDocument, puis accédez à la collection Texts pour obtenir l'objet TextContent. La propriété Color de TextContent renvoie la valeur RGBA de la couleur existante du texte, vous permettant de maintenir un style cohérent dans votre document.
Intégrer des images
Cette fonctionnalité vous permet d'inclure des images dans le contenu, améliorant ainsi l'attrait visuel global et la puissance communicative du document.
using IronWord;
using IronWord.Models;
// Load docx
WordDocument doc = new WordDocument();
// Configure image
ImageContent image = new ImageContent("image.jpg");
image.Width = 200; // In unit pixel
image.Height = 200; // In unit pixel
TextContent textRun = new TextContent();
// Add image
Paragraph para = new Paragraph(textRun);
para.AddImage(image);
// Add paragraph
doc.AddParagraph(para);
// Export docx
doc.SaveAs("save_document.docx");using IronWord;
using IronWord.Models;
// Load docx
WordDocument doc = new WordDocument();
// Configure image
ImageContent image = new ImageContent("image.jpg");
image.Width = 200; // In unit pixel
image.Height = 200; // In unit pixel
TextContent textRun = new TextContent();
// Add image
Paragraph para = new Paragraph(textRun);
para.AddImage(image);
// Add paragraph
doc.AddParagraph(para);
// Export docx
doc.SaveAs("save_document.docx");Imports IronWord
Imports IronWord.Models
' Load docx
Dim doc As New WordDocument()
' Configure image
Dim image As New ImageContent("image.jpg")
image.Width = 200 ' In unit pixel
image.Height = 200 ' In unit pixel
Dim textRun As New TextContent()
' Add image
Dim para As New Paragraph(textRun)
para.AddImage(image)
' Add paragraph
doc.AddParagraph(para)
' Export docx
doc.SaveAs("save_document.docx")Imports IronWord
Imports IronWord.Models
' Load docx
Dim doc As New WordDocument()
' Configure image
Dim image As New ImageContent("image.jpg")
image.Width = 200 ' In unit pixel
image.Height = 200 ' In unit pixel
Dim textRun As New TextContent()
' Add image
Dim para As New Paragraph(textRun)
para.AddImage(image)
' Add paragraph
doc.AddParagraph(para)
' Export docx
doc.SaveAs("save_document.docx")Ajouter des images
Charger l'image
Le chargement des images est un processus crucial. Cela implique d'intégrer des fichiers image externes au document. La possibilité de charger des images facilite l'inclusion d'éléments visuels pertinents, contribuant ainsi à un document plus attrayant et informatif.
using IronWord;
using IronWord.Models;
// Load docx
WordDocument doc = new WordDocument();
Paragraph paragraph = new Paragraph();
// Add image
paragraph.AddImage("image.jpg");
// Add paragraph
doc.AddParagraph(paragraph);
// Export docx
doc.SaveAs("document.docx");using IronWord;
using IronWord.Models;
// Load docx
WordDocument doc = new WordDocument();
Paragraph paragraph = new Paragraph();
// Add image
paragraph.AddImage("image.jpg");
// Add paragraph
doc.AddParagraph(paragraph);
// Export docx
doc.SaveAs("document.docx");Imports IronWord
Imports IronWord.Models
' Load docx
Private doc As New WordDocument()
Private paragraph As New Paragraph()
' Add image
paragraph.AddImage("image.jpg")
' Add paragraph
doc.AddParagraph(paragraph)
' Export docx
doc.SaveAs("document.docx")Imports IronWord
Imports IronWord.Models
' Load docx
Private doc As New WordDocument()
Private paragraph As New Paragraph()
' Add image
paragraph.AddImage("image.jpg")
' Add paragraph
doc.AddParagraph(paragraph)
' Export docx
doc.SaveAs("document.docx")Configurer l'image
Optimisez les images grâce à des paramètres configurables. Cela inclut la définition des propriétés telles que les dimensions, la position et la distance par rapport aux coins. Une configuration correcte garantit que les images s'affichent de manière visuellement agréable et contextuellement appropriée.
TextWrapBehavior (type ITextWrapBehavior) pour contrôler l'habillage du texte autour de l'image, mais aucune classe publique d'implémentation ou usine n'est actuellement documentée pour construire une valeur - cet exemple est omis en attendant la confirmation de l'équipe produit.using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;
// Load docx
WordDocument doc = new WordDocument();
// Configure image
ImageContent image = new ImageContent("image.jpg");
image.Width = 100;
image.Height = 100;
image.DistanceFromTop = 50;
var position = new ElementPosition();
position.X = 50;
position.Y = 50;
image.Position = position;
Paragraph paragraph = new Paragraph();
// Add image
paragraph.AddImage(image);
// Add paragraph
doc.AddParagraph(paragraph);
// Export docx
doc.SaveAs("document.docx");using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;
// Load docx
WordDocument doc = new WordDocument();
// Configure image
ImageContent image = new ImageContent("image.jpg");
image.Width = 100;
image.Height = 100;
image.DistanceFromTop = 50;
var position = new ElementPosition();
position.X = 50;
position.Y = 50;
image.Position = position;
Paragraph paragraph = new Paragraph();
// Add image
paragraph.AddImage(image);
// Add paragraph
doc.AddParagraph(paragraph);
// Export docx
doc.SaveAs("document.docx");Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums
' Load docx
Dim doc As New WordDocument()
' Configure image
Dim image As New ImageContent("image.jpg")
image.Width = 100
image.Height = 100
image.DistanceFromTop = 50
Dim position As New ElementPosition()
position.X = 50
position.Y = 50
image.Position = position
Dim paragraph As New Paragraph()
' Add image
paragraph.AddImage(image)
' Add paragraph
doc.AddParagraph(paragraph)
' Export docx
doc.SaveAs("document.docx")Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums
' Load docx
Dim doc As New WordDocument()
' Configure image
Dim image As New ImageContent("image.jpg")
image.Width = 100
image.Height = 100
image.DistanceFromTop = 50
Dim position As New ElementPosition()
position.X = 50
position.Y = 50
image.Position = position
Dim paragraph As New Paragraph()
' Add image
paragraph.AddImage(image)
' Add paragraph
doc.AddParagraph(paragraph)
' Export docx
doc.SaveAs("document.docx")Questions fréquemment posées
À quoi sert IronWord dans le développement C# ?
IronWord est une bibliothèque puissante pour les développeurs .NET C# conçue pour aider à créer, lire et éditer des documents Word et DOCX au sein de leurs applications.
Comment puis-je ajouter un texte stylisé à un document Word avec IronWord ?
Vous pouvez ajouter du texte stylisé en créant un objet 'Run' enveloppant 'TextContent', puis appliquer un 'TextStyle' et l'ajouter à un paragraphe en utilisant la méthode 'AddChild' dans IronWord.
Quel est l'objectif de l'objet 'Run' dans IronWord ?
L'objet 'Run' dans IronWord agit comme un conteneur pour 'TextContent' qui permet de styliser le texte, comme définir la taille de la police, la couleur et d'autres attributs.
Comment intégrer une image dans un document avec IronWord ?
Pour intégrer une image, créez un objet 'ImageContent' et ajoutez-le à un paragraphe en utilisant la méthode 'AddImage'. Cela vous permet d'insérer des images dans votre document.
Quelles sont les étapes pour configurer une image dans IronWord ?
Configurer une image implique de définir des propriétés comme les dimensions, la position, et la distance par rapport aux coins, pour s'assurer que l'image s'affiche correctement dans le document.
IronWord peut-il récupérer les valeurs de couleur d'un document Word existant ?
Oui, IronWord peut récupérer les valeurs de couleur RGBA de documents existants via la propriété 'Color' de 'TextContent', aidant à maintenir la cohérence du style.
Quelle méthode IronWord utilise-t-il pour diviser une séquence de texte ?
IronWord utilise la méthode 'Split' pour diviser une séquence de texte en parties plus petites basées sur un délimiteur spécifié, permettant une meilleure organisation et manipulation du contenu textuel.
Pourquoi est-il important de comprendre la hiérarchie des documents dans IronWord ?
Comprendre la hiérarchie des documents (Document → Paragraph → Run → TextContent) est crucial pour gérer efficacement et styliser le contenu dans un document Word avec IronWord.
Comment enregistrer un document Word créé avec IronWord ?
Un document Word créé avec IronWord peut être enregistré en utilisant la méthode 'SaveAs', en spécifiant le nom de fichier et le chemin pour enregistrer le document.
Quelle est la fonction de la méthode 'AddParagraph' dans IronWord ?
La méthode 'AddParagraph' dans IronWord est utilisée pour ajouter des paragraphes entièrement configurés, avec texte et images, à un document Word.
Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes et créer des manuels bien structurés et visuellement attrayants.