如何在JSF上显示pdf

时间:2018-08-21 10:26:02

标签: jsf primefaces

嗨,我的代码如下:

public StreamedContent getTempPdfFile() throws IOException {
    File testPdfFile = new File("D:\\AFC150_20180819_0103.pdf");
    streamedContent = new DefaultStreamedContent(new FileInputStream(testPdfFile), "application/pdf",
            "AFC150_20180819_0103.pdf");
    return streamedContent;
}
<h:panelGrid columns="1" cellpadding="5">
    <p:media value="#{realReport.tempPdfFile}" player="pdf" width="1000px" height="300px">
        <f:param name="id"  />
    </p:media>
</h:panelGrid>

但是PDF文件没有显示在页面上。

2 个答案:

答案 0 :(得分:0)

这是我的示例,希望对您有所帮助,代码具有内联和附件:

void sendBackPDFToClient()
{
        //File temp = File.createTempFile(fileName, ".pdf");
        File testPdfFile = new File("D:\AFC150_20180819_0103.pdf");
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();

        ec.responseReset(); 
        ec.setResponseContentType("application/pdf"); 
        ec.setResponseContentLength((int)testPdfFile.length()); 

        //Inline
        //ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + testPdfFile.getName() + "\""); 

        //Attach for Browser
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + testPdfFile.getName() + "\""); 

        OutputStream output = ec.getResponseOutputStream();
        Files.copy(testPdfFile.toPath(), output);
        fc.responseComplete();


}

答案 1 :(得分:0)

您是否尝试过PrimeFaces Extensions的Document Viewer组件?

我认为它比p:media更易于使用,并提供更多功能,包括从URL,流或资源加载它的能力。这个基本的示例向您展示了如何使用这三种类型。

JAVA:

protected void Page_Load(object sender, EventArgs e)
{
    FileUpload1.Attributes.Add("onchange", "__doPostBack('" + LinkButton1.UniqueID + "','')");
}

XHTML:

public StreamedContent getTempPdfFile() throws IOException {
     File testPdfFile = Paths.get("D:\\AFC150_20180819_0103.pdf").toFile();
     return new DefaultStreamedContent(new FileInputStream(testPdfFile), "application/pdf",
                "AFC150_20180819_0103");
}