尝试在浏览器中查看PDF文件时,PDF呈现为文本内容

时间:2018-07-18 18:37:10

标签: java pdf jsf servlets response

我要下载或在网络浏览器中看到pdf文件时出现错误,该文件以某种方式以文本形式生成。有人遇到这个问题吗?

是我的代码

public void downloadPDF(File ArchivoPDF, String NombrePDF) throws IOException{

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try{
        input = new BufferedInputStream(new FileInputStream(ArchivoPDF),DEFAULT_BUFFER_SIZE);

        response.reset();
        response.setHeader("Content-Type","application/pdf");
        response.setHeader("Content-Length",String.valueOf(ArchivoPDF.length()));
        response.setHeader("Content-Disposition","attachment; filename=\"" + NombrePDF + ".pdf\"");
        output = new BufferedOutputStream(response.getOutputStream(),DEFAULT_BUFFER_SIZE);

        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while((length = input.read(buffer)) > 0){
            output.write(buffer,0,length);
        }

        output.flush();
    } finally{
        close(output);
        close(input);
    }

    facesContext.responseComplete();
}

private static void close(Closeable resource){
    if(resource != null){
        try{
            resource.close();
        } catch(IOException e){
            e.printStackTrace();
        }
    }
}

我的组件commandButton是:

<a4j:commandButton  id="btnGenerarAllPDF" style="width:130px;"
                rendered="#{clsGestionReclamoRealSrv.objComponente.blVerBtnGenerarExpedienteElectronico}"
                value="Generar Expediente"
                onclick="#{rich:component('modCargando')}.show();" 
                action="#{clsGestionReclamoRealSrv.doGenerarAllPDF}"
                oncomplete="#{rich:component('modCargando')}.hide();"
                reRender="frmRegistrarReclamo"/>

并在以下位置调用方法:

File ArchivoPDF = new File(pathFolderArch + String.valueOf(this.getObjReclamo().getNuIdReclamo()) + ".pdf");
if(ArchivoPDF.isFile()){
    ClsUtils.deleteCarpeta(pathFolderTemp);
    downloadPDF(ArchivoPDF,String.valueOf(this.getObjReclamo().getNuIdReclamo()));
} else {
    logger.error("Error al generar el PDF.");
}

结果是浏览器中的文本。

Text replace pdf

他们知道如何解决。

1 个答案:

答案 0 :(得分:0)

我相信设置内容类型的适当方法类似于

response.setContentType("Content-Type","application/pdf");

这可以按预期将文件下载为pdf。要在浏览器中查看文件,请尝试类似

response.setHeader("Content-Disposition", "inline; filename=\"" + NombrePDF + ".pdf\";");