This post it’s a reply to a question I got from a previous
post that shows how to work with Word templates from C# code. If you haven’t
read it, I recommend to do so because I’m not going into details here. But
basically it was about how to create a Word document from a template and
perform same text manipulation.
So, the question from Marcel Kieboom was
“Do you know if it would be also possible to replace one of the words with an image which is locally stored?”
“Do you know if it would be also possible to replace one of the words with an image which is locally stored?”
The answer
is yes, and this is how you can do that.
Based on the same convention I had used in the previous
post, I should have a template like this:
What I’m trying to do here is replace the text [angus-young]
for an actual pic of Angus. The technique I’m using it’s pretty common on web
sites and basically consist in have an image with a matching name for each
keyword I want to replace and then create the image path dynamically.
This is the C# code to do that.
* When I execute the find operation I’m using the flag
WdReplace.wdReplaceNone. This is important because otherwise we will messed up
the current selection and the image will be inserted in the wrong place.
Once you run the code, you will be creating a document
called foo.docx inside the bin/debug/docs folder which should look something
like this:
You can grab the code from github. And as usual, questions are
more than welcome. Please ping me if you have any trouble using this code.
Nice post. As I searched online, I got alternative method by using Spire.Doc, more details - Replace Images with Texts in Word in C# This post gives a opposite effect but the same subject.
ReplyDeleteSounds interesting. I'll check it out. Thanks!
DeleteHi. Can you help me?
ReplyDeleteIf instead of using a image from a file I used a bitmap created before?
Thanks. ;)
Hi, MWalker. In that case I'll try to save the bitmap to a file in a tmp folder and use the code as is. When it comes to office interop, the close you play to the VBA way, the better. ;)
DeleteHope this helps.
My objective was to save processing time. I am dealing with very large structures and it consumes a lot of time save to the hard drive.
ReplyDeleteHmmmm, well; In that case I would investigate OpenXML SDK. Although I really dislike it, it might be the right choise for you needs.
DeleteAnother option would be using multiple process, but ofcourse, it wouldn't reduce the time to process each file, it'll just lower the processing time of a whole batch at a cost of more processing power. If you can afford power consumption, you should give it a try to this alternative, otherwise, as far as I know, OpenXML it is.
(Sorry for the late response, I was on vacation).
Than you. ;)
DeleteFor now I will save the images then load them. Thank you.
One more doubt, when using the "Microsoft Word 14.0 Object Library" I get a warning in doc.Close() and app.Quit().
Regards,
Sure, no problem. Just replace doc.Close() with ((_Document)doc).Close() and app.Quit() with ((_Application)app).Quit()
Delete(If you are using R# you will get a suggestions saying the cast is redundant, if you remove it, you will get the csc warnings back. Pick one ;))
Hi once again.
DeleteCan you tell me the reason why windows ask me if I want to save the *dotx file everytime I run this code?
Thank you! ;)
This comment has been removed by the author.
ReplyDeleteYour post is really helpful for me.
ReplyDeleteBut how can i replace single keyword for multiple times in single document?
It should work right out of the box. Are you getting any errors or something?
DeleteNo i am not getting error but i don't know how can i replace single keyword for multiple times in single document.
DeleteJust wrap the code with an infinite loop and check at the end of the loop if there are more occurrences of the "target word" (so to speak), if not, then exit.
DeleteI tried this code and it worked for me:
while(true) {
//for each keyword you want to replace.
//************************************************
var keyword = "angus-young";
Console.WriteLine("Replacing keyword: {0} ...", keyword);
var sel = app.Selection;
sel.Find.Text = string.Format("[{0}]", keyword);
// sel.Find.Forward = true;
// sel.Find.Wrap = WdFindWrap.wdFindContinue;
sel.Find.Execute(Replace: WdReplace.wdReplaceNone);
sel.Range.Select();
//This code inserts the image
var imgPath = Path.GetFullPath(string.Format(@"Img\{0}.jpg", keyword));
sel.InlineShapes.AddPicture(
FileName: imgPath,
LinkToFile: false,
SaveWithDocument: true);
//************************************************
//IMPORTANT! =================================================
//Do we have any other occurrence?
if (!sel.Find.Execute(Replace: WdReplace.wdReplaceNone))
break; //We haven't. Exit.
//IMPORTANT! =================================================
}
//finally, save the doc.
doc.SaveAs(Path.GetFullPath(@"Docs\foo.docx"));
doc.Close();
how can i set image size
ReplyDeleteHi Pankaj, sorry for a late reply. As I commented to other readers, the best way to do it, is to start the macro recorder, do whatever you need by hand, and then peek at the VBA code that the wizard generates for you. I'll try it myself if I have a Windows box at hand, but unfortunately I'm on the mac these days.
DeleteHow to change text inside Headers and footers ?
ReplyDeleteHi Samuel, It's been a long time since I had to work with office so my memory it's a little blurry on this... But what I usually use to do, was to start the macro recorder in word and peek at the generated VBA code. From there, is usually just a copy paste thing. You shouldn't have much trouble with that. (I'll try it myself if I've a Windows box at hand, but these days I'm working on the mac)...
Deletehow can page number add in table spire.doc c#
ReplyDelete