Skip to main content
Known Participant
December 24, 2018
Question

How to return cfdocument pdf file and server to the user in the browser?

  • December 24, 2018
  • 1 reply
  • 1130 views
I have function that will generate cfdocument pdf file. Then I would like to return the document and server to the browser. Here is example of the function that generates the pdf file.

<cftry> 
     <cfdocument format="PDF" filename="file.pdf" overwrite="Yes">
          <table>
               <tr>
                    <td>Test</td>
               </tr>
          </table>
     </cfdocument> 
     <cfset local.fnResults = {file: //Here I'm not sure what I should return}> 
     <cfcatch type="any">
          <cfset local.fnResults = {status : 400, message : "Error! Something went wrong."}>
     </cfcatch>
</cftry> 
<cfreturn fnResults>

Function above should genrate the file and return PDF in fnResults structure. Then on serve.cfm I have this logic:

<cfset local.Results = genertePDF()>  
<cfif structKeyExists(local.Results, "FILEPATH")>
     <cfheader name="content-disposition" value="attachment;filename=#local.Results["FILENAME"]#"/> 
     <!---Add the file content to the output stream:--->
     <cfcontent file="#local.Results["FILEPATH"]#" type="application/octet-stream" reset="true"/> 
     <!---Exit immediately after adding the file content to avoid corrupting it:--->
     <cfabort/>
<cfif>

You can ignore the structure of RESULTS since I haven't modified everything. My only problem here is to figure out how to return cfdocument content? If anyone knows how to get this to work please let me know. Thank you.

This topic has been closed for replies.

1 reply

BKBK
Community Expert
Community Expert
December 29, 2018

<cffunction name="generatePDF" >

    <!--- Full path of file --->

    <cfset local.fnResults.filePath="#expandpath('.')#\myFile.pdf">

    <cftry>

    <cfdocument format="PDF" overwrite="Yes" filename="#local.fnResults.filePath#" >

          <table>

              <tr>

                    <td>Test</td>

              </tr>

          </table>

    </cfdocument>

  

    <cfcatch type="any">

          <cfset local.fnResults = {status : 400, message : "Error! Something went wrong."}>

    </cfcatch>

    </cftry>

    <cfreturn local.fnResults>

</cffunction>

<cfset local.Results = generatePDF()>

<cfif structKeyExists(local.Results, "FILEPATH")>

    <cfheader name="content-disposition" value="attachment;filename=#local.Results['FILEPATH']#"/>

    <!---Add the file content to the output stream:--->

    <cfcontent file="#local.Results['FILEPATH']#" type="application/octet-stream" reset="true"/>

    <!---Exit immediately after adding the file content to avoid corrupting it:--->

    <cfabort/>

</cfif>