Question

With the following code I am getting bad output like this:

%PDF-1.4 %���� 4 0 obj <>stream x�3P0T�5T0P034�ɹ\�\N!\�f ��f !)\�!\�\� %@(Dɹ �i� .� h�@]z��PF��� endstream endobj 6 0 obj <>/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]>>/MediaBox[0 0 612 792]/Rotate 90>> endobj 7 0 obj <>stream x��} xU������;d"7!�tor���a�H.! HDfLh� 2�AEE E"8K�� A�%Dhj�:b�D����T�Z�U$��>��pEѶ�����$���=k������DA ��g�E�}[2^�!�9'�Zp���_R��/��=��Y�W����ߝ]7��P�S#J*E���7)�����>�������f����͟9�����3t�g�?cɂ������!�o���y����Z���;�R*�渗R�|J!2>>f�:������O����6z@̡h=.�@�i5�)�Jѯ�t�"'ME���ǁ��D��L�h���^@ڳ� �KI"�����J��k%�P �q4�։3�����W�@:�.����4�1n0i��G�EQ��������ƛ�9n�[�mqC�CD- Hy-� �4]�ߡ�t1ڠ�zA���^G��T�R�4B��*���l�@{E1Rf;��1���:���[��v�i���"���q���Rw:�i��~�����bp�.u����O���

instead of pdf. Here is the code:

URL url = new URL(urlStr)
URLConnection connection = url.openConnection();
response.contentType = 'application/pdf'
response.setHeader("Content-Disposition","Attachment; filename=gdoc.pdf")
def bytes = connection.getInputStream().getBytes()
response.getOutputStream().write(bytes)
response.outputStream.flush()
response.outputStream.close()

/*
  //writing to a pdf file works perfectly
  def outputStream =  new FileOutputStream(new File("gdoc/abc.pdf"));
  outputStream.write(bytes)
  outputStream.close()
*/

How to get the actual pdf output in browser.

Was it helpful?

Solution

Are you trying the response inside a iframe? If so, first try directly opening the output in a new window and see if it opens.

If its opening try mapping your controller to something like abc.pdf so that the url you point to becomes /something/abc.pdf.

OTHER TIPS

This assumes you are inside a controller, the return null at the end of the controller method ensure that Grails doesn't try and render anything. Also, using Apache commons to copy the contents will prevent you from having to download the entire file into memory before sending it in the response. This is modified from production code where I do something quite similar. Grails version(s) 1.3.7 and 2.0.4.

URL url = new URL(urlStr)

response.setContentType("application/pdf")
response.setHeader("Content-disposition", "attachment;filename=gdoc.pdf")

// this will actually buffer/stream the file in 8k chunks instead of reading the entire file into memory.
org.apache.commons.io.IOUtils.copy(url.openStream(), response.outputStream)
response.outputStream.flush()
response.outputStream.close()

// make sure Grails doesn't render anything for the request.
return null

I resolved my problem doing the below code:

Controller:

    def bytes = SendHttpService.executeGetBinary("http://app.com",  
                                                  "/pdf/", params)
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setHeader("Content-Disposition", "inline; filename=\"relatorioGerencial.pdf\"");
    response.setContentType("application/pdf");
    response.setContentLength(bytes.length);
    ServletOutputStream ouputStream = response.getOutputStream();
    ouputStream.write(bytes,0,bytes.length);
    ouputStream.flush();
    ouputStream.close();

Here, send the request to return stream like the first example, note that the contentType is binary

    def executePostBinary = { String httpUrl, String dataBody, String path, query = null, method = Method.POST->

    def http = new HTTPBuilder()
    try{
        http.request( httpUrl , method , ContentType.BINARY ) { req ->

            uri.path = path
            uri.query = trataQuery(query)
            headers.'User-Agent' = "Mozilla/5.0 Firefox/3.0.4"
            headers.Accept = ContentType.BINARY
            if(method==groovyx.net.http.Method.POST && dataBody!=null){
                body = dataBody
            }

            response.success = { resp, inputStream  ->
                inputStream.bytes

            }

            response.'404' = {
                'Not found'
            }
        }
    }catch(HttpResponseException e){
        println "Error "+e
        println "Error Code "+e.statusCode
        return false
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top