Free Support Forum - aspose.com

Insert Images in a Word document using Document Builder

Hi Support,

We are a licensed user of Aspose.Words 6.3.0.0 version. We are trying to insert images to word document using the Document builder classes available in Aspose.Words. On trying to insert Image in the Document we are only able to insert it into the First Page.Can you please help us in the same. Below is the requirement.

1.First page of the Document has to have 2 images.

2.2nd page of the Document is blank.

3.All pages following after the 2nd page need to have a single Image & that should get repeated itself for the rest of the pages.The image here is an small gif line used for OMR purposes by our Client.

Below is the code what we have used:

private void Button1_Click(object sender, System.EventArgs e)

{

string file = "C:\\Inetpub\\wwwroot\\TestDoc\\bin\\Aspose.Words.lic";

Aspose.Words.License license=new Aspose.Words.License();

license.SetLicense(file);

Aspose.Words.Document doc=new Aspose.Words.Document("D:\\NCMMIS\\Templates1\\Templates1\\evc.doc");

DocumentBuilder builder=new DocumentBuilder(doc);

//inserts Image at first Page

builder.InsertImage("D:\\NCMMIS\\Templates1\\Templates1\\evc_files\\image002.gif",RelativeHorizontalPosition.Margin,Convert.ToDouble(TextBox1.Text),RelativeVerticalPosition.Margin,Convert.ToDouble(TextBox2.Text),Convert.ToDouble(TextBox3.Text),Convert.ToDouble(TextBox4.Text), WrapType.None);

//Trying to set the Position to insert images in 3rd and the next pages

builder.InsertImage("D:\\NCMMIS\\Templates1\\Templates1\\evc_files\\image002.gif",RelativeHorizontalPosition.Margin,Convert.ToDouble(TextBox1.Text),RelativeVerticalPosition.Margin,Convert.ToDouble(TextBox2.Text),Convert.ToDouble(TextBox3.Text),Convert.ToDouble(TextBox4.Text), WrapType.None);

doc.Save("D:\\NCMMIS\\Templates1\\Templates1\\evc.doc",SaveFormat.Doc);

}

Also I have attached the sample Document in which we want to do Modifications.We are not creating a new document but using the existing document to place images in that.

Please help us in the above requirement as we need it at the urgent. Waiting for the Reply

Many Thanks in Advance.

Robin.

Hi Robin,

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. I think, in your case, you should insert your images into Header to Footer of your document. Please see the following link to learn how to create Header/Footer programmatically.

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net-and-java/aspose.words.documentbuilder.movetoheaderfooter.html

Hope this helps. Please let me know if you need more assistance, I will be glad to help you.

Best regards.

Hi Alexey,

Thanks for the reply. But this solution doesnt works for me. Its repeating that image from the Ist page to all the pages like a watermark. But my requirment is something else. Let me clarify you again with the below steps:

1. We are having some Word documents which already have a specific format i.e. 1st page is a letter head having address the 2nd page is a blank page and rest of the pages that follow are having some text with the body of the letter.

2. Since it is a specific Letter format . So we need 2 images that I attached at positon in the letter head as I gave in that sample document. We donot require any image on 2nd page as it is desired to be a blank page. From 3rd page onwards we need a single image repeating in all the rest of the pages.

These Images are OMR marks which are using by machines to identify the packaging of the printed letters in envolope. So this above process is defined for the same.

I hope this makes you some more clear.

So is this possible to do using Aspose.Words??

Please let me know if you can help me on the same . Will be waiting for your reply.

Regards,

Robin.

Hi

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thank you for additional information. I understand your requirements. The problem is that MS Word document is flow document and does not contain any information about its layout into lines and pages. So, unfortunately, there is no public API, which allows you to determine where page starts or ends using Aspose.Words.

However, if you reformat your document, you can achieve this by including this image into header or footer. My suggestion is using three sections in your document – one for the first section, one for blank page and one for the rest content in your document. Please let me know if such approach is acceptable for you.

Best regards.

Hi Alexey,

Thanks for your suggestions . I understand that . We were also planning to divide the Document into 3 such sections and apply images where required. But the whole problem is that we are having 40 such Word documents in which we will required to be reformatted and on reformatting can disturb the formatting in the orginal document so our testing team will have to spend a lot of time . These 40 word templates are already being used by users on our live application. So we did not wanted to follow this approach as this will require a tedious amount of time in Altering documents and testing those documents and uploading them again that can create problems for us. So we wanted a better approach for the same. Do you have some other approach to follow. Let me know if you can.

Regards,

Robin.

Hi

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. I think, you can try using IF fields in this case. For example see the following code:

string imageName = @"Test001\image001.gif";

// Create Document and DocuemntBuilder.

Document doc = new Document();

DocumentBuilder builder = new DocumentBuilder(doc);

// Create shape.

Shape image = new Shape(doc, ShapeType.Image);

image.Width = 37;

image.Height = 5;

image.ImageData.SetImage(imageName);

// Set position of the shape.

image.Left = -45;

image.Top = 516;

image.WrapType = WrapType.Tight;

// Build document.

// Just for testing add few pages.

builder.Writeln("This is the first page. The next page is empty");

builder.InsertBreak(BreakType.PageBreak);

builder.InsertBreak(BreakType.PageBreak);

for (int i = 0; i < 100; i++)

builder.Writeln("This is some contnet isn the document");

builder.CurrentSection.PageSetup.DifferentFirstPageHeaderFooter = true;

// Move DocumentBuilder cursor to the first page header.

builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);

// Here we should insert iamge two times.

builder.InsertNode(image.Clone(true));

// The second image should be moved down.

Shape image1 = (Shape) image.Clone(true);

image1.Top += 12;

builder.InsertNode(image1);

// Move cursor to the primary header of the document.

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

// We will use IF field to display image startign from the 3rd page.

// In our case, IF field code will look like the following:

// { IF "{PAGE}" = "2" "" "" }

// Insert the first part of the IF field

FieldStart start = builder.InsertField("IF \"", null);

// Move DocumentBuilder cursor to the next run after field start.

builder.MoveTo(start.NextSibling.NextSibling);

// Insert PAGE field.

builder.InsertField("PAGE", null);

// Insert operator.

builder.Write("\" = \"2\" \"\" \"");

// Insert false value.

builder.InsertNode(image.Clone(true));

builder.Write("\"");

// Save output document.

doc.Save(@"Test001\out.doc");

MS Word should automatically update IF fields in document header.

Hope this helps.

Best regards.

Hi Alexy,

Your solution pefectly fits if I am creating a new Document. I am clear with code that inserts 2 images in First page. I tried to comment few lines using which you are trying to insert content but didnt worked well with my template already having some content. Can you explain your piece of code with some more clarification i.e which lines should i comment within your code for our templates already having some text & what code is repeating that single image in the rest of the pages . What if i also need to add the same single image in the blank page too can i add that too ??

Many thanks in advance

Regards,

Robin

Hi

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. In my code, I insert two images into the first page header, then I insert IF field into the primary header. IF field code looks like the following:

{ IF "{PAGE}" = "2" "" "" }

So the image is not displayed on the second page of your document.

Could you please attach few documents examples, which you need to process. I will try to adapt the code to your needs.

Best regards.

Hi,

Thanks for the clarfication. Can you tell me what lines to delete from the code so that it starts showing the image in Blank page as well. I tried doing that but no success. Now our client has added this one too to his requirements. That means 2 images in the Header and just 1 image repeating for all the pages including the blank one. Rest i understood the above clarfication mady by you.

Regards,

Robin

Hi <?xml:namespace prefix = st1 ns = "urn:schemas:contacts" />Robin,

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. This makes things much easier, if you need to display one line on all pages including the second. In this case, you do no need to use IF fields. code will look like the following:

string imageName = @"Test001\image001.gif";

// Create Document and DocuemntBuilder.

Document doc = new Document();

DocumentBuilder builder = new DocumentBuilder(doc);

// Create shape.

Shape image = new Shape(doc, ShapeType.Image);

image.Width = 37;

image.Height = 5;

image.ImageData.SetImage(imageName);

// Set position of the shape.

image.Left = -45;

image.Top = 516;

image.WrapType = WrapType.Tight;

// Build document.

// Just for testing add few pages.

builder.Writeln("This is the first page. The next page is empty");

builder.InsertBreak(BreakType.PageBreak);

builder.InsertBreak(BreakType.PageBreak);

for (int i = 0; i < 100; i++)

builder.Writeln("This is some contnet isn the document");

builder.CurrentSection.PageSetup.DifferentFirstPageHeaderFooter = true;

// Move DocumentBuilder cursor to the first page header.

builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);

// Here we should insert image two times.

builder.InsertNode(image.Clone(true));

// The second image should be moved down.

Shape image1 = (Shape) image.Clone(true);

image1.Top += 12;

builder.InsertNode(image1);

// Move cursor to the primary header of the document.

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

builder.InsertNode(image.Clone(true));

// Save output document.

doc.Save(@"Test001\out.doc");

Hope this helps.

Best regards.

Hi Alexey,

Thanks for the replies. Your code works well when you create a new document through document builder. I comment out those lines which u made to insert page breaks & insert content. I tried to apply your code on our templates. But i am not sure why it is leaving the 3rd page without any image. Then I also tried adding content on the blank page. Then it inserted the image on the 3rd page but didnt insert the same on the 2nd page. It did insert on the 3rd page moved some content of 3rd page to 4th page and also inserted the image there. Please help me out to resolve the same. I am attaching both test documents i.e. test1.doc with 2nd page as empty and test2.doc non -empty 2nd page. Please let me know if it displays the images consistenly for both the documents.

Regards,

Robin.

Hi <?xml:namespace prefix = st1 ns = "urn:schemas:contacts" />Robin

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thank you for additional information. This occurs because there are few sections in your documents. Please try using the code below:

// Create document.

Document doc = new Document(@"Test001\test2.doc");

// Create shape.

Shape image = new Shape(doc, ShapeType.Image);

image.Width = 37;

image.Height = 5;

image.ImageData.SetImage(@"C:\Temp\image001.gif");

// Set position of the shape.

image.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;

image.RelativeVerticalPosition = RelativeVerticalPosition.Page;

image.Left = 10;

image.Top = 516;

image.WrapType = WrapType.None;

// Create paragraph, where we insert an image.

Paragraph watermarkPara = new Paragraph(doc);

watermarkPara.ParagraphBreakFont.Size = 1;

watermarkPara.AppendChild(image);

// Insert the watermark into all headers of each document section.

foreach (Section sect in doc.Sections)

{

// There could be up to three different headers in each section, since we want

// the watermark to appear on all pages, insert into all headers.

InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);

InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);

InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);

// Insert into the first page header of the first section one more image.

if (sect.Equals(doc.FirstSection))

{

sect.PageSetup.DifferentFirstPageHeaderFooter = true;

// The second image should be moved down.

Shape image1 = (Shape)image.Clone(true);

image1.Top += 12;

sect.HeadersFooters[HeaderFooterType.HeaderFirst].FirstParagraph.AppendChild(image1);

}

}

// Save output document.

doc.Save(@"Test001\out.doc");

================================================================================

private static void InsertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooterType headerType)

{

HeaderFooter header = sect.HeadersFooters[headerType];

if (header == null)

{

// There is no header of the specified type in the current section, create it.

header = new HeaderFooter(sect.Document, headerType);

sect.HeadersFooters.Add(header);

}

// Insert a clone of the image into the header.

header.AppendChild(watermarkPara.Clone(true));

}

Hope this helps.

Best regards.

Hi Alexey,

Thank you for your continous support to us. Just tried with the new piece of code. But it has now stopped displaying images on the header page i.e. the new code for adding 2 images on the header is not working. I also commented 2 lines for the code,then only it started showing me the image on the rest of the pages ,intially this was not showing me any image on all the pages.

image.RelativeHorizontalPosition=RelativeHorizontalPosition.Page;<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

image.RelativeVerticalPosition = RelativeVerticalPosition.Page;

Please look this at your end and let me know if you get a solution for this.

Regards,

Robin.

Hi

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. I checked my code one more time and it works fine on my side. Please make sure you use exactly the same code as I provided.

// Create shape.

Shape image = new Shape(doc, ShapeType.Image);

image.Width = 37;

image.Height = 5;

image.ImageData.SetImage(@"C:\Temp\image001.gif");

// Set position of the shape.

image.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;

image.RelativeVerticalPosition = RelativeVerticalPosition.Page;

image.Left = 10;

image.Top = 516;

image.WrapType = WrapType.None;

Please double check the highlighted line of code. Also, please attach the problematic document here for testing.

Best regards.

Hi Alexey,

Thanks you it is working fine. I was having the code as image.left=-45. That is why i was not able to see. But the problem now is the 2 images that are in the header are aligned left 10 pixels to the page. But for the rest of the pages that are having header at the top have the alignment different from those. Please use test2.doc to replicate the same. The single image in rest of the pages with content should be exactly aligned with those in the header first page.

Thank you,

Robin.

Hi <?xml:namespace prefix = st1 ns = "urn:schemas:contacts" />Robin,

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. The problem occurs because you removed the following two lines of code:

image.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;

image.RelativeVerticalPosition = RelativeVerticalPosition.Page;

Best regards.

Hi Alexey,

Thank you for your replies and continous support and I appreciate the fact that you helped us till we finally got a solution .

Thanks once again.

With Best Regards,

Robin