How to display pdf on JSF

☆樱花仙子☆ 提交于 2019-12-24 08:08:01

问题


Hi my code is as follows:

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>

But the PDF file is not getting displayed on the page.


回答1:


Here is my sample, hope it helps, the code has the inline and attachment:

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();


}



回答2:


Have you tried the Document Viewer component of PrimeFaces Extensions?

I think its much easier to use than p:media and offers more features including ability to load it from a URL, a Stream, or a Resource. That basic example shows you how to do it with all 3 types.

JAVA:

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");
}

XHTML:

<pe:documentViewer height="500" width="1000" value="#{realReport.tempPdfFile}"/>


来源:https://stackoverflow.com/questions/51946617/how-to-display-pdf-on-jsf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!