Turning a Visualforce page into a Word Document
So 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
</td>
</tr>
<tr>
<td style=”width:80%”>
</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 <span style=’mso-field-code: PAGE ‘></span>
</td>
</tr>
<tr>
<td style=”width:80%; text-align:center”>
</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.
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…
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.
Hi Ryan,Regarding page breaks…
is there a way to put page breaks inside vf page code.
Please respond.
Thanks,
Indrasen
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?
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.
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.
Hi Ryan,
Good Post
Thanks, and as I said above it’s me that wrote the post, not Ryan 🙂
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?
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.
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
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.
I’m glad you got it working Nita!
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?
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;}
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
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.
Hey, can you send me the code for print layout via email? It would be really helpful.
Thanks a lot!
Anshuman,
Unfortunately I’ve never been able to get the print layout part to work…
may i get the code for print view??
Sorry, I was never able to get the print view working unfortunately…
I would like to see your solution for the ‘print view’ problem.
Can you send it to me in an email?
Thank you
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.
I am facing one problem. It is showing footer twice in the last page
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.
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
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.
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.
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.
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
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
Hello Brian
Thanks a lot..
The issue was with the proxy settings of our company network..
Great post..Thanks agn 🙂
Glad you were able to get it working Asna.
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
Samruddhi,
Unfortunately I’ve never been able to get the print layout part to work…
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?
Becky,
The only thing I can suggest is to follow the last update at the bottom of my post. Hope it helps.
Hi Brian,
I have a problem of  .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.
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.
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
Hey sorry i think the code was not printed. Posting it again. Use “ ” instead of ” ” which will give you the same effect.
Add the below meta tag to your visualforce page and it should render without those extraneous characters.
Venkat
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
Hi Brian,
I want the header only for first page.Is it possible to restrict the header only for first page?
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.
good one..
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.
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.
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.
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?
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.
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.
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.
HI
Is is possible to save it in (dot)docx type ?
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?
Any luck with header, footer, and page no when VF is displayed as word?
Works fine when rendered as pdf.
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
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
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())}
Hi Brian,
Can you please provide the sample document that you generated using visualforce and apex code ?
Hey thanks for the info..
How do I put a page border in the MS Word doc generated from the VF Page
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 .
Thanks a lot, is really working.