如果你有一個完整的路徑(從資源文件夾)已經生成的PDF文件,你可以在你的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>
好,如果您想顯示webservice返回的字節流中的pdf內容,則可以使用primefaces-extensions的documentViewer
組件(使用PDF.js)
所以,你需要在你的豆,裝入一個字節流,併產生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;
}
}
重要:不要把@PostConstruct
過載()方法時,它會被稱爲在PreRender事件:
<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>
注:小心與primefaces和primefaces的擴展版本,在這種情況下,我已經使用:
<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>
這是正確的,從來沒有我需要消費一個Web服務,返回一個包含pdf文檔的字節數組。 –
@OliverSoria好的,但你需要在你的問題中指定源(不是文件)。希望答案更新對您有所幫助 –