How to Create Word, PDF or Excel Files with Salesforce Data

One of challenges in any software application is being able to export data into different documents using templates for various purposes.

An example of this is using such templates to create custom documents such as Fax sheets, Quotes, Invoices, Forms that are required to be filled out by a person in traditional ways.

Visualforce pages allow us to generate such documents combined with Salesfoce data. The documents can be formatted in number of types such as PDF, Excel, Word, HTML or XML.

In this example I will show how easy it is to generate PDF documents using Visualforce pages adn with adding little bit of your coding skills you can easily create other formats as well (of course with certain limitations).

In order to be able to create PDF pages in Salesforce you meed to know the following:
  • When using the Page tag, you should set the "showHeader" attribute to "false". By doing this you are telling to Visualforce to do not render any Salesforce header or even HTML tags.
    So think about a normal HTML page, which has tags such as "html", "head" and "body" none of these tags are added to your page automatically anymore. So we should add them to the page ourselves when creating PDF files.
  • Also note that HTML form elements or Apex input controls can not be included into your document.
  • The other important thing is styling, in order to make your PDF file look professional you need to apply styling skills and add CSS classes to your Visualforce page.
  • And the last point is to set your "Page" attribute called "renderAs" to "pdf".
Below is a sample PDF generate code with no content:



<apex:page showHeader="false" renderAs="pdf">
<head>
</head>
<body>
</body>
</apex:page>



The next step is to add some styling/formatting options as well as planning for your content.

By applying CSS into you can define a few CSS classes that formats your PDF document the way you need.

However, the following are important features you may want to benefit from, such as the ability to set the PDF file pages orientation (Landscape or portrait), allow page numbers or additional descriptions in PDF file's header or footer, etc.

Some of these examples are shown below:


<apex:page showHeader="false" renderAs="pdf">
<head>
<style type="text/css">
@page
{

/* Landscape orientation */
size:landscape;

/* Put page numbers in the bottom right corner of each
page in the pdf document. */
@bottom-right {
content: "Page " counter(page);
}
}

body {
font-family: Arial Unicode MS;
font-size:9pt;
}


td {
font-size:11pt;
font-family:Tahoma;
}

/* you can even define custom classes that utilize your static resources */
.checkbox
{
width: 19px;
height: 16px;
background-image:url({!URLFOR($Resource.Checkbox)});
background-repeat: no-repeat;
}
</head>
<body>
</body>
</apex:page>



If your requirement is to create Word or Excel files the process would be the same only following changes are required:
  • Remove "renderAs" attribute
  • Add a new attribute to the page tag: "ContentType":
    - For Word: contentType="application/msword"
    - For Excel: contentType="application/x-excel"
  • And finally a little bit of tweaking of your style will take care of the job

80 comments:

  1. Sam,Thanks for the Post. I have a question. Is it possible convert it to poweroint output?
    Say if we have powerpoint template stored in SF and want to get the formated out put in the stored template. Is this something possible in SF?

    ReplyDelete
  2. Hi Vipin,
    I have not tried setting the content type to Powerpoint and see how Ms. Powerpoint behaves!

    But I would say it worth a shot.
    Good luck!

    ReplyDelete
    Replies
    1. hi Sam,When I generate MS-doc using COntentType, how can I make it read only? how to set the property for the file?

      Thanks in advance

      Delete
  3. Would be cool to see an example of returning an HTML table that got turned into Excel rows and columns.

    Good post!

    ReplyDelete
  4. HI Sam,
    Thanks a lot ! It works for XLS. but I have one question regarding PDF out put, could you get Tahoma in the PDF output as given in your sample code. I have tested all the font names in my Windows machine, but only few were supported. Is there any customization to add more fonts is it kind of legal issue ?

    ReplyDelete
  5. Hi,

    Nice and simple example, thanks. One issue:
    You need to close the style tag.
    Thanks Again

    ReplyDelete
  6. How do we support pagination in PDF file generated I mean what if I want to generate PDF of a VF age which have Header, Footer & a PageTable with multiple pages of Data can I generate PDF for Each page of PageTable with same header & footer ?

    - Varun

    ReplyDelete
  7. Sam, ALWAYS Thanks for the All Post :)

    ReplyDelete
  8. Have you been able to create multiple Excel Worksheets?

    ReplyDelete
    Replies
    1. Has any one been able to multiple workbooks?

      Delete
  9. I tried generating excel sheet , but i always get this unable to download from cs1.salesoforce.com error!!
    Did anyone else come across this error?

    ReplyDelete
  10. Set the "cache" property to true on the apex page tag. This problem only happens in IE.

    ReplyDelete
  11. yes ... cache="true" should be set for IE8+ support, when you want to show File Save dialog ... I've noticed IE7 and below works fine without this attribute but IE8 requires this.

    ReplyDelete
  12. Nice short summary!

    What I have working:
    PDF output with pagination, headers, page count and tables from list data.

    What I'd like to do:
    1. Export to Word and maintain the layout and tables (the CSS formatting seems to be lost when using the documenttype="application/msword" attribute.

    2. Increase the total page count (e.g. counter(pages)) by a predefined amount for all pages, accounting for pages I'll append later. I can replace the counter(pages) with a merge field; the trouble is I don't know how many total pages are in the PDF ahead of time.

    Ideas appreciated!

    ReplyDelete
  13. image shows up on vf page..but when it is displayed as word..the image is not displayed on ms word.

    Please suggest some workaround or something that i may be missing?


    ~Sumita

    ReplyDelete
  14. Hi, its me sumita again,
    actually i got the image working. you just have to put the file in the documents folder, and call it in vf along with the doc id and org id.

    eg.


    ~Sumita

    ReplyDelete
    Replies
    1. Can you please post the syntax for displaying the image in VF please?

      Delete
    2. Sumita, can you please post the syntax for how you got the image to display? thanks! Fred

      Delete
  15. I am unable to get Header and Footer in Word Doc using the above style. How can I achieve this?

    ReplyDelete
  16. Hi Sam I have a question, I am able to export data into excel but while doing so my visual force page goes blank, it would be nice to keep the visual force as same or perhaps redirect it, i tried both none worked. Any idea?

    ReplyDelete
  17. Unfortunately I have no solutions for that. I think Salesforce.com should provide a solution for this.

    ReplyDelete
  18. Thanks a lot Sir for the quick reply, I always follow your blogs and learn a lot from those. Thanks again.

    ReplyDelete
  19. Is there a way to get a handle on the created word document and save it as an attachment to a particular record.

    ReplyDelete
  20. Is there a way to generate multiple worksheets in one excel file using apex and visualforce

    ReplyDelete
  21. I noticed when I export my table to an excel contentType, the first row is the header section as expected/desired but the next row is the footer section followed by the data. An idea why the footer is the second row and how to fix it so the footer is the last row in the excel spreadsheet?

    example:




    AM Agency Plan

    Total Plans ({!agencyPlanTotal.TotalPlans})

    ReplyDelete
  22. Hi, has anyone successfully make the header/footer/pagination work in word?

    ReplyDelete
  23. How can i get rid of the tabstyling?

    ReplyDelete
  24. My Word document shows blank by using this
    Instead pdf is working properly

    ReplyDelete
  25. Hi,
    i have a doubt, If we have one MSWORD document and i can save that document in documents object. Now i want that document which is in documents object in to visual force page as pdf document. I am trying to display that document but it is displayed in encoding format. How can i dispaly in normal format.

    could u please explain me.

    ReplyDelete
  26. Hi,
    how to get the document from documents object and displayed in visual force page and generate as pdf document. could you please explain me

    ReplyDelete
  27. Hi ,
    I tried to create renderAs "PDF" using Arabic font . But issue is , words are displaying like this .

    For Example: " Test " as "tseT" . When I write somthing like this in arabic . Also, renderAs "HTML" works fine in the case for arabic font .

    I believe, this is the limitation at this point for using renderas PDF with arabic Fonts .

    ReplyDelete
  28. Do you know how to format the html so that it comes out as rows and columns in excel?, I tried a simple html table, but it just prints out the html contents

    ReplyDelete
  29. Is it possible to specify file name when rendering a pdf using renderAsPDF?

    ReplyDelete
  30. Hey Sam
    I need to make the PDf generated from VisualForce page not editable lets say it will be displayed as image , for security reasons I don't wanna users be able to copy data from the generated PDF.
    Thanks in advance

    If you can mail me the answer it will be great
    aadel@cloudconceptgroup.com

    ReplyDelete
  31. Hi There,

    Is there a way i can make certain fields read only in the rendered excel ?

    Thanks!
    Anand

    ReplyDelete
  32. Hi Sam,
    Is there any way we could fill-in a uploaded PDF with named fields?
    Transfer the values from SF and map them to fields on the PDF?

    Can this be done?

    Thank you so much.

    ReplyDelete
  33. I looked for such solution myself and never found one. So far the best way is to build the HTML and pass it to SF to convert it to PDF.

    ReplyDelete
  34. I have 1 task can you please guide me what step should I follow.
    Create a PDF fillable form

    2) Add a Submit button to the form - when clicked, it should perform 2 tasks:

    + Update a record in Salesforce
    + Attach the PDF as a flat file in Salesforce
    3) Create an HTML page

    ReplyDelete
  35. Now I have already done PDF Fill able form and submit button and I created HTML page also where I embebed this PDF.
    How can I communicate with my PDF form to SalesForce Records.
    Please guide me.

    ReplyDelete
  36. I don't actually follow what you are trying to achieve?

    ReplyDelete
  37. Thanks for your reply.My task is to communicate Sales force data with my HTML form.

    ReplyDelete
  38. Use a visualforce page as shown in this sample.

    ReplyDelete
    Replies
    1. I have a similar requirement. A PDF with a submit button which will be mailed to different parties. As I understand it, with a PDF submit, I could submit a post or go for Soap. If I post, what is there on a salesforce SITE to catch it ? PHP no problem, but Salesforce? I'm thinking it has to be Soap. Any insight or other ideas ?

      Delete
  39. hi. I have a blob data. I want to send that blob to pdf and save in static resource as dynamically using apex r vf.
    Please help me on it.
    kichepuri@gmail.com to mail me also.
    kishorec@virtusa.com

    ReplyDelete
  40. hi, I have send the blob data to a pdf dynamically.That file should be save in static resources.

    ReplyDelete
  41. Is possible to specify the actual file extension? For example, if I render a VisualForce page as "application/x-excel", then the "Save As" dialog box shows up but it'll only say "MyVisualForcePageTest" as the filename. I'd have to change it to "MyVisualForcePageTest.xls".

    ReplyDelete
  42. I have to take the .csv or .xls as input and convert as pdf blob then that pdf data has to save in documents obect as file path.
    Once the file is created then that path has to send mail to the user.
    Please help for this. i am facing the issue while sending the blob pdf to document object.
    Please mail me kichepuri@gmail.com

    ReplyDelete
    Replies
    1. Hi, you can find your answer here :
      http://dhawalsaiya-salesforce.blogspot.com/2012/01/upload-csv-file-and-save-it-as-pdf-file.html

      Delete
  43. Is there any way to generate PDF from standard report excel file? To elaborate further, excel file of standard report would be input and that file needs to convert into PDF format. So that user can convert excel report files into PDF format.

    Thanks,
    Devendra S

    ReplyDelete
  44. I have a same question which Devendra has. Can we give report results as input and get a PDF or Excel file?
    In the joined reports there is no Export option. So I am thinking whether can we develop something to get a PDF or excel file from reports.

    ReplyDelete
  45. Can we create multiple sheets in an excel from a vf page?

    ReplyDelete
  46. No you can't. What Sam is describing here is extremely useful if you want to get away without any third party tools. However it is not really creating an MS Word or Excel file. It is just creating an HTML file and makes sure it will be opened by MS Office on the user's computer by adding the contentType field to the HTTP header.
    If you want to create a real MS Office file you should look into document generators like www.cloudgizmos.com

    ReplyDelete
  47. Hi All,

    I'm new to Salesforce, so I'm not sure if I'm missing something simple, but I'm hoping someone can help.

    I'm trying to modify a page that ends up creating a formatted PDF document for the current record. The source page I'm modifying contains HTML, with Salesforce field "tags" in certain areas to display data specific to the current record.

    My problem is that the data output to the PDF document does not contain the formatting (ex: Currency with 2 decimal places) that is specified for the particular field. Is there some easy setting I can set to allow this to happen? If not, can you recommend how to display this data with the proper format?

    Thanks!

    ReplyDelete
  48. Is there a way to capture data from the event object in salesforce and show it as PDF. Can u please throw some light on it?

    Thanks,
    T

    ReplyDelete
  49. Hi Sam

    We are creating PDF quotations with salesforce .Our products are displayed in a table format per product within the quote. The table would typically contain specs , price and pics of the product. If there are multiple products per quote, some of these tables get chopped in half and spread out over two pages. Is there anyway to say that if a table will get chopped of that the entire table will be sent to the next page. Using page breaks after each table would mean that each product / table would be on a single page - not visually appealing. Any suggestions?
    Thanks

    ReplyDelete
    Replies
    1. <#div style="page-break-inside:avoid;">
      The stuff inside this div will move to a fresh page if it's too long to fit on the remainder of the current page.
      <#/div>

      Remove the hash symbols - it won't let me post div html here.

      Bankie

      Delete
    2. you can use it in your CSS class:
      @media print
      {
      table { page-break-inside:auto }
      tr { page-break-inside:avoid; page-break-after:auto;}
      thead { display:table-header-group }
      }

      Delete
  50. hi sam
    i have to created Joined format report?there is no option for export to excel?then how to export the data to excel?please help to me

    muruganm82@gmail.com

    ReplyDelete
  51. 1.How to export attachments in bulk in their original format.

    2. Export reports in PDF format

    ReplyDelete
  52. Hi Sam,
    Is it possible to show values from my Apex variable (available in the associated Apex controller) as a footer content in @bottom-right in CSS file.
    I was trying this in the CSS and it did not work as expected

    @bottom-left {
    content: "Test String " {!SampleApexVariable_pdf}
    }
    Any suggestion?

    ReplyDelete
    Replies
    1. Got it. The CSS has to be an inline CSS in the VF page
      AND it should be

      @bottom-left {
      content: "Test String {!SampleApexVariable_pdf}"
      }

      Sanjeev Mehta
      sanjumeh@gmail.com

      Delete
  53. i got the similar problem to break a PDF page , i have a quote with line items table, when the line items are more, the table is automatically going to second page. Is there a way to get the Table column headings on the second page?

    ReplyDelete
    Replies
    1. I have a similar problem, tried a lot to get in one section both quoteline items and introduction part but in vain. it looks very unprofessional sending quote with first page blank and table on second page. Any solution to this issue, much much appreciated please.

      Delete
  54. Hi Sam,

    Thanks for the wonderful posts.
    I am trying to create a pdf attachment without creating a VF page, but I am unable to do that.I can create doc, txt and excel files but not pdf when i am using 'application/pdf'. Is this not possible to create a pdf without using VF page?

    Thanks,
    Haider

    ReplyDelete
  55. Can you create multiple excel files with one call to this page or can the button call multiple pages to create multiple files? Lets say I wanted to have it create a file for contacts and a file for accounts with one click of the button.

    ReplyDelete
    Replies
    1. The only solutions I have found is posted here: http://neerajgupta999.blogspot.in/2012/06/multisheet-excel-from-apex.html

      However, I've been unable to make it work the way I want. If you have any feedback on this I would love it!

      Delete
    2. James,
      With a custom controller, you could definitely do what you describe without any problems at all. The buttom simply initiates the controller which accesses the data that's called from the current screen. If it can't be queried using the data that's available from the current screen, then you'd have a problem doing what you describe.

      Delete
  56. Can anyone show an example on how to render as an XML?

    ReplyDelete
  57. Hi,

    how you can go through the backdoor to add your related-list on the top of the page?

    Thanks,
    Steffi

    ReplyDelete
  58. Hi Sam, Assuming I create a PDF document using RenderAs, I then display that to my users and they can download and save the document.

    However, I cannot find a way to push a filename that I generate in my controller out to the browser in such a way that when the user hits Save As, the name I give will be displayed.

    Imagine a VF page called "Account Report", it's not so useful if all the PDF files have the same default save name... The user has to remember the Account data he wants to use to save the file.

    I've tried adding the "Content-Disposition: attachment; filename=abc.pdf" to the headers, and VF doesn't muck with it, but Chrome seems to ignore it.

    Any thoughts?

    Thanks, Steve.

    ReplyDelete
    Replies
    1. If putting it in the header or footer doesn't work, then combine several relevant fields at the top or bottom of the page to create a report name and date of some kind.

      Delete
  59. Hi Sam,

    I have used toPdf() method of Blob object in an apex class that is triggered with a custom button. But pdf content can not be displayed Turkish character. What can I do?

    ReplyDelete
  60. I am trying to save data in excel using visual force page but its not showing the cells ... how to get the data in cells .. I mean i need it in exact format as we see default excel sheet

    ReplyDelete
  61. Hi,

    Nice post.Following your post I have custom object with the RichText Fields created on it.So when user click on the button generate doc.Word file gets generated with data taken from the fields.Everything is fine,Except that content is displaying some characters Such as


    “OBD Social Media Challenge”

    How do I get rid of such characters any idea on that?.

    ReplyDelete
  62. Great Article!

    Question though - is it possible to generate the PDF into a drawing template? The idea being, for example, to create building plans based on information in SF, and have the specific measurements be generated onto the building-drawing template.

    ReplyDelete
  63. I have page with google visualization api charts i want to render it as pdf , I have tried with render as pdf But charts are not showing can you please suggest me how to do this its urgent for me.

    ReplyDelete
  64. Hi, I would like to ask if any of you created a PDF and a document attached inside the PDC i.e. word, excel etc.

    Any help will be very much appreciated. Thanks!

    ReplyDelete
  65. Any luck with header, footer, and page no. when VF is rendered as word doc? Looks like it is printing HTML version as doc.

    It works fine with pdf version.

    ReplyDelete
  66. Hi,

    I would like to ask, I am rendering vf page to pdf and I am using map in that. In VF it have no problem but in pdf its not showing.

    Can u please help on that.

    ReplyDelete