我已尝试过数以千计的替代品试图在网页浏览器中显示pdf,这是我的xhtml文件的一部分:
<p:media value="registerController.showFile" width="300" height="450" player="pdf" />
控制器:
@ManagedBean
@SessionScoped
public class RegisterController implements Serializable {
private static final long serialVersionUID = 1L;
StreamedContent showFile;
public StreamedContent getShowFile() {
Path pdfPath = Paths.get("path\\to\\image");
byte[] pdf = null;
try {
pdf = Files.readAllBytes(pdfPath);
} catch (Exception e) {}
ByteArrayInputStream b = new ByteArrayInputStream(pdf);
DefaultStreamedContent d = new DefaultStreamedContent(b, "application/pdf");
return d;
}
public void setPintaArchivo(StreamedContent showFile) {
this.showFile = showFile;
}
}
在控制台的浏览器中我收到404错误,这里有一些我没有成功的推荐:
答案 0 :(得分:-1)
如果您有完整路径(从资源文件夹)到已生成的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)
因此,您需要在bean中加载字节流并生成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
放在load()方法上,它会在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-extensions版本,在这种情况下我使用过:
<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>