How to return cfdocument pdf file and server to the user in the browser?
Copy link to clipboard
Copied
<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.
Copy link to clipboard
Copied
<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>

