a4j:mediaOutput not rendering PDF

落爺英雄遲暮 提交于 2019-12-02 09:07:31

A friend of mine came to me with this problem today and like you I've struggled to come up with a solution. After some time studying servlet I could solve the problem.

Your method should look like:

public void showPdf(OutputStream stream, Object object) throws SQLException, IOException {

    Blob proof = myObject.getPdf(someValue);//DB call to get the pdf

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    ServletOutputStream sout = null;

    response.setContentType("application/pdf");
    //set a constant for a name to avoid cache and duplicate files on server 
    response.setHeader("Content-Disposition","filename=fileName_" + (new Date()).getTime() + ".pdf" );

    response.setHeader("Content-Transfer-Encoding", "binary;");
    response.setHeader("Pragma", " ");
    response.setHeader("Cache-Control", " ");
    response.setHeader("Pragma", "no-cache;");
    response.setDateHeader("Expires", new java.util.Date().getTime());
    //Here you will have to pass to total lengh of bytes
    //as I used a file I called length method
    response.setContentLength(Long.valueOf(  proof.someByteLengthProperty()  ).intValue());

    sout = response.getOutputStream();
    byte[] buf = new byte[4096];
    InputStream is = new FileInputStream(proof.getBinaryStream());
    int c = 0;
    while ((c = is.read(buf, 0, buf.length)) > 0) {
        sout.write(buf, 0, c);
    }
    sout.flush();
    is.close();

}

It seems that only writing out the OutputStream is not enough so you have to create a ServletOutputStream and send it throghout the 'FacesContext' so it can render the output as if it was sending a download stream.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!