Unable to show PDF in p:media generated from streamed content in Primefaces

前端 未结 3 1741
死守一世寂寞
死守一世寂寞 2020-12-01 11:50

I\'m trying to show inline PDF which is opened in new browser window. I have following scenario:

  1. In some ActionListen which is called by ajax I generate PDF
3条回答
  •  有刺的猬
    2020-12-01 12:11

    It is not a browser or primefaces problem, just a funny getter problem.

    The getter is called twice by p:media (or if you refresh page than more times), but only the 1st call gets the correct data. StreamedContent encapsulates an InputStream, which has the property that it will give no bytes if the stream is at the end of the file. First time it is read to its end (data is ok), but every next call will get no data. :)

    javadoc of inputStream.read(): If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

    Solution:

                private StreamedContent streamedContent;
                private InputStream stream;
    
    
                public void somewhere(){
                    byte[] b = ...
                    stream = new ByteArrayInputStream( b );
                    stream.mark(0); //remember to this position!
                    streamedContent = new DefaultStreamedContent(stream, "application/pdf");
                }
    
    
                public StreamedContent getStreamedContent() {
                    if (streamedContent != null)
                        streamedContent.getStream().reset(); //reset stream to the start position!
                    return streamedContent;
                }
    

提交回复
热议问题