Skip to content

Turning a Visualforce page into a Word Document

October 8, 2009

Salesforce.comSo I’ve been doing some Salesforce development and using Visualforce I’ve been trying to create a word document.  Sounds simple enough, but if you’ve tried it you know that you run into all sorts of issues.

Salesforce has this great thing with visualforce pages where you can render it as a PDF but, to create a word document you still have to do it the old-fashioned way and set the content type to application/msword, just as you would from a regular html page.

Issue #1 was that the document wouldn’t open with Internet Explorer.  It worked fine in Firefox and Chrome and Safari and [insert new browser here], but in IE it would pop up asking you if you wanted to Open or Save the document.  So far so good.  If you clicked Open it would appear to be doing what its supposed to do but then nothing would happen.  Word didn’t open and you got no error message.  Strange.  If you clicked Save it would give you an error message saying it couldn’t open the page or something.  Crap.

Solution #1.  To solve this problem I’ve discovered that you need to set cache=”true” in the <apex:page> tag.

Issue #2 was that I needed to be able to insert page breaks in the document at certain points and, not knowing exactly what would be in the document until it was actually created made that rather difficult.  I did the usual google search and there were all sorts of answers that sounded good but none of them actually worked…..until I tried one last example.  This one worked perfectly for me.

Solution #2.  To solve this problem I needed to simply add this tag wherever I wanted there to be a page break. <br clear=”all” style=”page-break-before:always” />


Now the only issue that I’m left with is that I can’t get page numbers to be put into the document (SOLVED: see the Update below) and I can’t get it to open in Print View.  I have a solution that is supposed to work, and it does work on a regular html page but not in Visualforce.  The issue I think is that the visualforce page you don’t have the <html> tag in the code to add the proper schemas too.  I will update this if I figure out the issue.

Also, if anyone has any questions as to how to get a footer or header into the word document, or anything else that I may be able to help with please leave a comment and I will do my best to help.

UPDATE (for Ryan):

To put the header and footer into the doc there is no “GOOD” solution that I can find unfortunately.  The best solution I’ve managed to discover still leaves you with an extra “header/footer” on the last page of your document which you have to erase.

You can follow the steps here.  The problem with this hack is that you have to put the header/footer somewhere in your documents body to be able to use it as a header/footer.  I put it at the end of the document on the last page so it’s sort of out-of-the-way.  Now I should mention that I only added a footer, no header but, this is basically the code I used.

CSS:

@page Section1 {
mso-footer:f1;
}
div.Section1 {
page:Section1;
}
p.MsoFooter, li.MsoFooter, div.MsoFooter {
mso-pagination:widow-orphan;
}

HTML/VISUALFORCE:
<div class=”Section1″>
—YOUR REGULAR CONTENT HERE—
<br clear=”all” style=”page-break-before:always” />
<div style=”mso-element:footer”>
<p>
<hr />
<table>
<tr>
<td colspan=”2″ style=”text-align:center;”>
Page&nbsp;
</td>
</tr>
<tr>
<td style=”width:80%”>
&nbsp;
</td>
<td style=”width:20%”>
<img width=”124″ height=”54″ src=”YourImageUrlHere”>
</td>
</tr>
</table>
</p>
</div>
</div>

This has an image in the footer as well, which works for me.  A couple of things about the image url.  I have the image stored in Salesforce as a document (.png) and you have to make sure that the Externally Available Image checkbox is checked.  The url should be something similar to:

https://YOURINSTANCE.salesforce.com/servlet/servlet.ImageServer?id=SOMEID&oid=SOMEID&lastMod=SOMEID

To get the url for your image you can go to the document in salesforce and right-click on the image and select properties.  On the properties page it will have “Address (URL)”, you won’t be able to see the whole address but if you double-click on it, the whole address will be highlighted then you can right-click and select copy which will give you the whole thing.

In regards to saving it, I’m not sure when you are trying to save it that it’s saving as html but, in your apex page tag you can do this:

<apex:page contentType=”application/msword#YourDocName.doc” />

This will set the document name to whatever you want and the type to .doc, so when you save the doc it should be saving as a .doc type.

UPDATE:

I’ve finally managed, after some time away from it, to get the page numbers to work in the footer.

<div style=”mso-element:footer”>
<p>
<hr />
<table>
<tr>
<td colspan=”2″ style=”text-align:center;”>
Page&nbsp;<span style=’mso-field-code: PAGE ‘></span>
</td>
</tr>
<tr>
<td style=”width:80%; text-align:center”>
&nbsp;
</td>
<td style=”width:20%”>
<img width=”124″ height=”54″ src=”YOUR IMAGE URL”>
</td>
</tr>
</table>
</p>
</div>

Previously, from code I saw on another site, I was putting <span style=’mso-field-code:” PAGE “‘></span> when it should have just been <span style=’mso-field-code: PAGE ‘></span> without the double quotes.

64 Comments leave one →
  1. Ryan permalink
    November 12, 2009 1:48 am

    How did you get header or footer into the word output?

    I can succesfully get my page breaks.. but headers/footers just don’t work. I’m using the CSS @page directive to try – which is probably the problem.

    Images don’t seem to work either – and everytime I try to save the document – it saves as HTML…

    • November 12, 2009 10:44 am

      Ryan,

      Thanks for reading, I tried to answer your questions in the update at the end of the original post. Please let me know if you have any more questions.

    • Indrasen permalink
      March 3, 2010 1:34 am

      Hi Ryan,Regarding page breaks…
      is there a way to put page breaks inside vf page code.
      Please respond.

      Thanks,
      Indrasen

      • March 3, 2010 9:21 am

        Indrasen,

        It’s Brian actually. Is it just a regular visualforce page or are you sending the visualforce page to word, or rendering it as a pdf?

      • Indrasen permalink
        May 17, 2010 6:21 am

        Hi Brain,
        the page break statement

        in my vf page for word output is not working.
        can you please suggest where i am doing work.

        • May 17, 2010 9:57 am

          Indrasen,

          All you should need to do is put this piece of code wherever you want a page break (with the opening and closing tags of course).

          br clear=”all” style=”page-break-before:always”

          If that isn’t working you may be missing something else that’s required for it to work. Such as using the schemas in an html tag directly following the apex:page tag (with the opening and closing tags of course):

          html xmlns:v=”urn:schemas-microsoft-com:vml” xmlns:o=”urn:schemas-microsoft-com:office:office” xmlns:w=”urn:schemas-microsoft-com:office:word” xmlns:m=”http://schemas.microsoft.com/office/2004/12/omml” xmlns=”http://www.w3.org/TR/REC-html40″

          Really I need more info to offer any more help than that.

  2. Indraesn permalink
    February 15, 2010 7:05 am

    Hi Ryan,
    Good Post

    • March 3, 2010 9:24 am

      Thanks, and as I said above it’s me that wrote the post, not Ryan 🙂

  3. Nita permalink
    May 17, 2010 10:11 am

    I was trying to create word document,show how image that I am placing in visual force page is not displaying in word document. It render as cross mark instead of picture.

    any help with this problem?

    • May 17, 2010 10:15 am

      Where is the image that you are trying to use stored?

      If the image is stored in Salesforce please read over the section right before my last update that starts with “This has an image in the footer as well, which works for me…”

      Let me know if that helps.

      • Nita permalink
        May 17, 2010 10:26 am

        Here is my code, Logo i stored in salesforce.

        Could you please let me know where I am doing wrong? if I am not rendering this page as word,then simple visual force page render logo. but in word, it shows cross mark.

        MONTHLY PARTNERSHIP SUMMARY

        Congratulations
        This is your new Page

      • Nita permalink
        May 17, 2010 10:50 am

        I tried as save image as document instead of static resouce as you mentioned in your post and it worked for me.

        Thank you very much.

        • May 17, 2010 12:27 pm

          I’m glad you got it working Nita!

          • Nita permalink
            May 19, 2010 4:10 pm

            Hi ,

            I was trying add multiple JPG image in word document now its showing all image as cross-mark.

            If I add one image,works fine. However, if more than one different image, all shows as cross mark.

            Could you please guide me how to solve this problem?

  4. June 30, 2010 7:21 pm

    Great blog post! Here is how you can get the page to open in ‘print’ view (added right after tag):

    Print
    100

    Here is an example to setup the page margins:

    @page WordSection1
    {size:8.5in 11.0in;
    margin:.44in 1.25in .7in 1.25in;
    mso-header-margin:.5in;
    mso-footer-margin:.5in;
    mso-paper-source:0;}

    div.WordSection1
    {page:WordSection1;}

    • June 30, 2010 7:24 pm

      Looks like my comment got cut off (probably because ‘xml’). Send me an email and I’ll send you the code:
      2nd attempt:

      Print
      100

      • June 30, 2010 7:29 pm

        Thanks a lot for the Print View fix. Very nice of you. Unfortunately the comments won’t let you put HTML in them so it won’t show up. I’ll send you an email and then if you send me the code I’ll add it to the post so that others can use it as well.

      • Anshuman permalink
        January 21, 2011 4:45 am

        Hey, can you send me the code for print layout via email? It would be really helpful.

        Thanks a lot!

        • March 18, 2011 11:19 am

          Anshuman,

          Unfortunately I’ve never been able to get the print layout part to work…

      • Isay permalink
        December 21, 2011 6:27 pm

        may i get the code for print view??

        • February 14, 2012 8:48 am

          Sorry, I was never able to get the print view working unfortunately…

    • October 28, 2010 6:13 am

      I would like to see your solution for the ‘print view’ problem.
      Can you send it to me in an email?
      Thank you

      • October 28, 2010 9:47 am

        Ilse,

        One of the other commentors, Tanner, provided some code that was supposed to make opening the word doc in “Print View” work properly. However the code didn’t work for me. So as of yet I haven’t been able to get that one last part working. The code does work when you’re doing it from outside of Salesforce (in a regular html page) but, for some reason when done through Salesforce it doesn’t function properly. I will be sure to update this post if I do manage to get it working at some point, it’s the last part that is left outstanding right now.

  5. July 6, 2010 7:12 am

    I am facing one problem. It is showing footer twice in the last page

    • July 7, 2010 9:26 am

      Unfortunately Sy, I haven’t been able to find a way to get around that. In order to create the footer it needs to be taken from somewhere in the content of the page. Thus it will show up twice somewhere. At least doing it on the last page you know where to look to remove it.

  6. Asna permalink
    December 8, 2010 9:18 am

    Hello Brian

    I am facing issues with inserting image with Word doc.
    I have simply followed ur suggestion.
    But it is not working for me.
    I wonder something which works for everyone else is not working for me.

    I will share my code if required.
    can you please figure it out?
    I have desperately tried lot of solution with no luck
    Please help me out

    Thanks

    • December 8, 2010 9:30 am

      Asna,

      Without knowing more all I can do is repeat what I said in the article with respect to adding images (see below). Be sure you save the image as a document and that you check the “Externally Available” checkbox. Save it in a publicly accessible folder (not My Personal Documents), then get the FULL url by right clicking on the image and going to the properties.

      Have the image stored in Salesforce as a document (.png) and you have to make sure that the Externally Available Image checkbox is checked. The url should be something similar to:

      https://YOURINSTANCE.salesforce.com/servlet/servlet.ImageServer?id=SOMEID&oid=SOMEID&lastMod=SOMEID

      To get the url for your image you can go to the document in salesforce and right-click on the image and select properties. On the properties page it will have “Address (URL)”, you won’t be able to see the whole address but if you double-click on it, the whole address will be highlighted then you can right-click and select copy which will give you the whole thing.

  7. Pranav permalink
    December 15, 2010 3:47 am

    Hi Brian,

    The word document I’m generating from Salesforce always opens in Web Layout intead of opening in print layout. Is there any solution to open it in print layout only.

    I see some text alignment issue when a document is generated as word compared to document generated as PDF.

    Thanks.

    • December 17, 2010 9:24 am

      Hi Pranav,

      Unfortunately I haven’t been able to figure out a way to open the document in Print Layout when creating it from Salesforce. I can do it when creating a word doc from a regular HTML page but, the same code doesn’t work when coming from a Visualforce Page. Sorry I couldn’t help.

      • Pranav permalink
        December 17, 2010 11:52 am

        Hi Brian,

        Thanks for reply..

        I’m also working on Salesforce office connector. Using mail merge feature, I’m trying to generate a word document. The only issue I’m facing is getting data from a related lists of an object.


        Pranav

  8. asna permalink
    December 16, 2010 3:19 am

    Hello Brian

    I am all at sea still.
    Could you please share the complete VF page you rendered as Word.I will copy paste and make necessary modifications .

    Thanks a lot
    Asna

  9. asna permalink
    December 17, 2010 1:48 am

    Hello Brian

    Thanks a lot..
    The issue was with the proxy settings of our company network..
    Great post..Thanks agn 🙂

  10. Samruddhi permalink
    February 11, 2011 12:25 am

    I would like to know your solution for opening the word doc in print view.
    Can you send it to me in an email?
    Thanks

    • March 18, 2011 11:21 am

      Samruddhi,

      Unfortunately I’ve never been able to get the print layout part to work…

  11. March 7, 2011 12:23 pm

    Hi Brian. A really useful post but I just cannot get the page numbers to display. Is there a key part to this feature that I’m likely to have missed?

    • March 18, 2011 11:23 am

      Becky,

      The only thing I can suggest is to follow the last update at the bottom of my post. Hope it helps.

  12. Nithin A permalink
    March 9, 2011 3:49 pm

    Hi Brian,
    I have a problem of &nbsp.In the word doc it shows me A^ instead of a space.Do you have any idea about it?And how do the page numbers come.I am not clear on that part.

    • March 18, 2011 11:26 am

      Nithin,

      I’m not sure about the nbsp part, I haven’t seen that before. For the page numbers I can only suggest that you follow the instructions for the last update I made at the bottom of the post. Hope that helps you out.

      • Parin permalink
        April 24, 2012 5:13 am

        Hi Nitin,
        You can use instead of   which will give you the same effect.
        Use below site for all the ascii codes:- http://www.ascii.cl/htmlcodes.htm

        • Parin permalink
          April 24, 2012 5:14 am

          Hey sorry i think the code was not printed. Posting it again. Use “ ” instead of ” ” which will give you the same effect.

      • January 21, 2014 9:34 am

        Add the below meta tag to your visualforce page and it should render without those extraneous characters.

        Venkat

        • January 21, 2014 9:36 am

          It looks like this blog is blocking html code:

          meta http-equiv=”Content-Type” content=”text/html;charset=utf-8″

          Put the above in html angle brackets just like any other html tag.

          Venkat

  13. Nithin A permalink
    March 10, 2011 1:07 pm

    Hi Brian,
    I want the header only for first page.Is it possible to restrict the header only for first page?

    • March 18, 2011 11:27 am

      Nithin,

      I think the purpose of the header is so that it shows up on every page. I’m not sure how you would go about putting it on only one page, sorry.

  14. Sravan Villa permalink
    December 6, 2011 2:02 pm

    good one..

  15. Soumali permalink
    February 14, 2012 7:38 am

    Hi Brian,
    Did you get the solution for opening the word document in print layout instead of web layout? Please let me know if you got it.

    I have another issue, I want to save the file as word document, but whenever I’m clicking on save, its saving the file as a web document. How can I solve this problem? I’ve already tried using .doc in the content type, but its not working.

    • February 14, 2012 8:55 am

      Soumali,

      No, I was never able to get the solution for opening it in print layout.

      As far as I know, the only thing you have to do to save it as a word doc is to make sure your content type at the top looks like the following:

      contentType=”application/msword#YourDocName.doc”

      Please note the section above that’s related to IE if you are using that as well. Hope that helps.

      • Soumali permalink
        February 16, 2012 1:48 am

        Hi Brian

        Thanks for your reply.

        I have already tried that in the content type, but it is not working for me. Is there is any other way by which I can fix that.

  16. Manan permalink
    April 3, 2012 11:54 am

    Hi,
    I have a VF page which displays Google Map. I want to render it in PDF. But when it renders as PDF, it can’t display Google map. So how can I display google map in either PDF or MS-Word format?

  17. Parin permalink
    April 24, 2012 5:20 am

    Hi Brian,
    I have managed to overcome the problem of repeating header and footer in the generated ms word file. Please let me know how i can post it. You can contact me on parindagade@rediffmail.com.

  18. lisa permalink
    June 11, 2012 4:06 pm

    Hi,

    Thanks for the article. I was able to put in the page numbers, but for some reason on the last page of my document after the last bit of text it displays “Page of” besides the Page 5 of 5 at the bottom. Am I missing something?

    Thanks.

  19. June 19, 2012 7:20 am

    HI Brian ,

    Is it possible to use images from Static Resources instead of storing it in document ?
    I need to use it because of we will be creating managed package and it is not feasible to use hard coded URL.

  20. June 27, 2012 2:00 am

    HI
    Is is possible to save it in (dot)docx type ?

  21. August 7, 2012 1:25 am

    When I convert the VF page result as word document, all double byte language characters(like Chinese, Japanese chars)are displaying as junk chars. Do you have any solution for rendering the document in Unicode?

  22. May 9, 2013 7:23 pm

    Any luck with header, footer, and page no when VF is displayed as word?

    Works fine when rendered as pdf.

  23. Krishna permalink
    July 5, 2013 8:29 pm

    Hi Brian,

    I am trying export into word document, however checkbox image is not working as expected I tried by placing and by storing the checkbox image into document tab, and refering it in tag still it is not working.
    Could you please help me on this.

    Regards
    Krishna

  24. Rohit permalink
    July 9, 2013 11:19 am

    Hi Brian,

    I am unable to get the header working, not sure if I am missing something here. Even the header gets displayed as a normal text. Below is my code, its not complete though:

    @page Section1 {mso-Header:f1;}
    div.Section1{page:Section1;}
    p.MsoHeader, li.MsoHeader, div.MsoHeader{
    mso-pagination:widow-orphan;
    }

    Test Header 4

    {!MONTH(TODAY())}/{!DAY(TODAY())}/{!YEAR(TODAY())}

    Thanks,
    Rohit

    • Rohit permalink
      July 9, 2013 11:44 am

      p.MsoHeader, li.MsoHeader, div.MsoHeader{
      margin:0in;
      margin-top:.0001pt;
      mso-pagination:widow-orphan;
      tab-stops:center 3.0in right 6.0in;
      }
      @page Section1 {mso-Header:f1;}
      div.Section1{page:Section1;}

      Test Header 4

      {!MONTH(TODAY())}/{!DAY(TODAY())}/{!YEAR(TODAY())}

  25. Amit permalink
    September 3, 2013 8:41 am

    Hi Brian,

    Can you please provide the sample document that you generated using visualforce and apex code ?

  26. Pooja Somaiya permalink
    September 28, 2014 5:53 am

    Hey thanks for the info..
    How do I put a page border in the MS Word doc generated from the VF Page

  27. Manoj permalink
    January 13, 2015 6:15 am

    Hi Brian,

    How to use image ,I am using both document URL and static resource but not able to view the image .It is showing only the url .Please suggest .

  28. Vikram Sharma permalink
    April 16, 2019 7:47 am

    Thanks a lot, is really working.

Trackbacks

  1. How to make the Reports like Excel, PDF, Word, CSV using Visualforce

Leave a reply to Indrasen Cancel reply