This example uses DocX to write the text “Hello World” into an Image embedded inside a .docx document.
Note: Make sure the document Input.docx exists and that it contains an Image.
Below is an example Input.docx and Output.docx
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using Novacode;
- using System.Drawing;
- using System.Threading.Tasks;
- using System.IO;
- using System.Diagnostics;
- using System.Drawing.Imaging;
- namespace testDocX
- {
- class Program
- {
- static void Main(string[] args)
- {
- // Open the document Input.docx.
- using (DocX document = DocX.Load("Input.docx"))
- {
- // Make sure this document has at least one Image.
- if (document.Images.Count() > 0)
- {
- Novacode.Image img = document.Images[0];
- CoolExample(img, "Hello World");
- }
- else
- Console.WriteLine("The provided document contains no Images.");
- // Save this document as Output.docx.
- document.SaveAs("Output.docx");
- }
- }
- // Write the given string into this Image.
- private static void CoolExample(Novacode.Image img, string str)
- {
- // Write "Hello World" into this Image.
- Bitmap b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
- /*
- * Get the Graphics object for this Bitmap.
- * The Graphics object provides functions for drawing.
- */
- Graphics g = Graphics.FromImage(b);
- // Draw the string "Hello World".
- g.DrawString
- (
- str,
- new Font("Tahoma", 20),
- Brushes.Blue,
- new PointF(0, 0)
- );
- // Save this Bitmap back into the document using a Create\Write stream.
- b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
- }
- }
- }

Hi, i appreciate DocX library, it saved my ... day many times. Your samples has given me very good directions many times, and this is one of those days.
ReplyDeleteI see the blog is 2 years silent and i though... no more ? You left docx/dotnet/programming ?
Or you transferred to another link i don't know ?
However, thanks for your posts, even 2 year later they're very very useful