Jitender Kumar
Jitender Kumar

Reputation: 2597

How to add image and text both in header while generating word document using Docx dll?

I am using Docx dll to generage pdf file but not able to add image in header although I can add the image in the content part of the word file. Here is my code for that:

using (Novacode.DocX document = Novacode.DocX.Create(savePath))
    {

        // Add Header and Footer support to this document.
        document.AddHeaders();
        document.AddFooters();

        // Get the default Header for this document.
        Novacode.Header header_default = document.Headers.odd;

        // Add an Image to the docx file
        string imageName = "LOGO.png";
        string url = Request.MapPath("/PDFFolder/" + imageName);

        Novacode.Image img = document.AddImage(url);

        // Insert a Paragraph into the default Header.
        Novacode.Picture pic1 = img.CreatePicture();           
        Novacode.Paragraph p1 = header_default.InsertParagraph();
        header_default.Pictures.Add(pic1);           

        p1.Append("Some more text").Bold();


        // Add a new Paragraph to the document.           
        Novacode.Paragraph p = document.InsertParagraph();

        // Append some text.
        p.Append(textword).Font(new myDrawing.FontFamily("Arial"));

        // Get the default Footer for this document.
        Novacode.Footer footer_default = document.Footers.odd;


        // Insert a Paragraph into the default Footer.
        Novacode.Paragraph p3 = footer_default.InsertParagraph();
        p3.Append("Hello Footer.").Bold();


        // Save the document.
        document.Save();
    }

Any help would be great!!

Upvotes: 4

Views: 8468

Answers (1)

Jitender Kumar
Jitender Kumar

Reputation: 2597

I got the answer of my problem. Actually it seems that Docx dll does not support displaying images in table under header. Although they have given method to display image in table and also shown in their blogs but still I was not able to display the image using table in header section which I can easily accomplish by using paragraph like in given below code:

// Insert pic and text into the default Header.
Novacode.Paragraph p1 = header_default.InsertParagraph();
p1.Direction = Novacode.Direction.LeftToRight;
p1.AppendPicture(pic1);

And it works fine but the problem occurs when you have to display an image with some header text. Because we are not using table to display image so it get difficult to align both image and header text properly. After tried so many solutions and hard work as I did not find any support and solutions, finally I find the solution of my problem. We can align both header image and header text in one line without using a table with given below one line:

p1.Append("Headertext").Bold().Position(30);

With the help of Position() method you can align both header text and header image in one line. Hope this will also help someone :) .

Upvotes: 4

Related Questions