If you have a full path (from resources folder) to already generated PDF file, you can load in your xhtml:
<object id="pdf_document" type="application/pdf" data="#{youBean.documentPath}?pfdrid_c=true" width="100%" height="500px">Your browser does not support this feature!</object>
Well, if you want to show a pdf content from byte stream returned by webservice, you can use primefaces-extensions's documentViewer
component (that use PDF.js)
So you need, in your bean, load a byte stream and generate a StreamedContent
:
@ManagedBean
@SessionScoped
public class StreamBean implements Serializable {
private static final long serialVersionUID = 1L;
private StreamedContent pdfContent;
public void load() {
try {
// Simulate getting byte[] from external source, like webservice
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classloader.getResourceAsStream("file-sample.pdf");
int byteReaded = 0;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] data = new byte[1024];
while ((byteReaded = inputStream.read(data, 0, data.length)) != -1)
buffer.write(data, 0, byteReaded);
buffer.flush();
byte[] pdfBytes = buffer.toByteArray();
// Create the StreamedContent with readed pdf file
pdfContent = new DefaultStreamedContent(new ByteArrayInputStream(pdfBytes), "application/pdf");
} catch (IOException e) {
// Manage your exception here
e.printStackTrace();
}
}
public StreamedContent getPdfContent() {
return pdfContent;
}
}
Important: don't put @PostConstruct
over load() method, it will be called in preRender event:
<ui:composition template="/your-template.xhtml" ... xmlns:pe="http://primefaces.org/ui/extensions">
<ui:define name="pageBody">
<f:metadata>
<f:event type="preRenderView" listener="#{streamBean.load()}" />
</f:metadata>
<pe:documentViewer height="450" value="#{streamBean.pdfContent}" download="file-sample.pdf" />
</ui:define>
</ui:composition>
Note: be careful with the primefaces and primefaces-extensions versions, in this case i have used:
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.1</version>
</dependency>
<dependency>
<groupId>org.primefaces.extensions</groupId>
<artifactId>primefaces-extensions</artifactId>
<version>6.1.0</version>
</dependency>