2008-10-20 2 views
1

EDIT : 아래 답변에서 my working code을 참조하십시오.Java Bean에서 JSP로 PDF 파일을 반환

간단히

: 나는 자바 빈의 메소드를 호출하는 JSP 파일이 있습니다. 이 메서드는 PDF 파일을 생성하고 이론적으로 사용자가 다운로드 할 수 있도록 JSP로 반환합니다. 그러나 PDF를로드 할 때 Adobe Reader는 다음 오류를 표시합니다. 파일이 '% PDF-'로 시작하지 않습니다..

세부 사항 : 지금까지 JSP가 메서드를 성공적으로 호출하면 PDF가 만들어지고 JSP에서 사용자에게 완성 된 PDF 파일이 제공됩니다. 그러나 Adobe Reader가 PDF 파일을 열려고하면 오류 메시지가 표시됩니다. 파일이 '% PDF-'로 시작하지 않습니다.. 그냥 좋은 측정을 위해, 나는 그것을 확인할 수 있도록 내 바탕 화면에 PDF를 만드는 방법을 가지고; Windows 내에서 정상적으로 열면 괜찮아 보입니다. 그러면 JSP의 출력이 다른 이유는 무엇입니까?

PDF를 만들려면 Apache FOP을 사용하고 있습니다. 필자는 가장 기본적인 예제 중 하나를 따르고 있습니다. 단, PDF를 로컬 시스템에 저장하는 대신 결과 JSP를 JSP로 전달하는 경우는 예외입니다. 나는 그들의 basic usage patternthis example code을 따라왔다.

<%@ taglib uri="utilTLD" prefix="util" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %> 
<%@ page language="java" session="false" %> 
<%@ page contentType="application/pdf" %> 

<%-- Construct and initialise the PrintReportsBean --%> 
<jsp:useBean id="printReportsBean" scope="request" class="some.package.printreports.PrintReportsBean" /> 
<jsp:setProperty name="printReportsBean" property="*"/> 

<c:set scope="page" var="xml" value="${printReportsBean.download}"/> 

가 여기 내 자바 콩 방법입니다 :

여기 내 JSP 파일의

//earlier in the class... 
private static FopFactory fopFactory = FopFactory.newInstance(); 

public File getDownload() throws UtilException { 

    OutputStream out = null; 
    File pdf = new File("C:\\documents and settings\\me\\Desktop\\HelloWorld.pdf"); 
    File fo = new File("C:\\somedirectory", "HelloWorld.fo"); 

    try { 

     FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); 

     out = new FileOutputStream(pdf); 
     out = new BufferedOutputStream(out); 

     Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); 

     TransformerFactory factory = TransformerFactory.newInstance(); 
     Transformer transformer = factory.newTransformer(); //identity transformer 

     Source src = new StreamSource(fo); 

     Result res = new SAXResult(fop.getDefaultHandler()); 

     transformer.transform(src, res); 

     return pdf; 

    } catch (Exception e) { 

     throw new UtilException("Could not get download. Msg = "+e.getMessage()); 

    } finally { 

     try { 
      out.close(); 
     } catch (IOException io) { 
      throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage()); 
     } 
    } 
} 

나는 이것이 매우 구체적인 문제이지만, 어떤 도움이 많이 주시면 감사하겠습니다 실현!

답변

4

과거에 이런 유형의 기능을 구현 한 방법은 서블릿이 PDF 파일의 내용을 응답으로 스트림으로 작성하도록하는 것입니다. 나에게 소스 코드가 더 이상 없다. (서블릿/JSP 작업을 한 지 1 년이되었지만) 시도해 볼만한 것이있다.

서블릿에서 응답의 출력 스트림을 처리합니다. 응답의 MIME 유형을 "application/pdf"로 변경하고 서블릿에서 사용자가 처리 한 파일을 처리하게하십시오. File 객체를 반환하는 대신 서블릿에서 파일을 출력 스트림에 쓰게하십시오. 파일 I/O의 예를보고 responsefile.write (...)로 outfile.write (...) 행을 대체하면 go로 설정해야합니다. 출력 스트림을 플러시하고 닫은 다음 반환을 수행하면 브라우저가 응답에서 pdf를 가져올 수 있어야합니다.

3

그냥 짐작 하겠지만 JSP 페이지가 반환하는 MIME 유형을 확인 했습니까?

편집 : 당신의 JSP 코드에서 JSP 태그 사이의 줄 바꿈이에서 생을 마감하지 않을 : 나는 실제로 그렇게 신경 끄시 당신은 내가 당신이 그것을 설정 않았다 볼 것이다 게시 된 코드 :

이 EDIT2을 읽으면 출력 스트림? 서버가 반환 한 응답을 버릴 수 있습니까? 필자는 PDF 형식에 대해서는 아무 것도 모르지만 파일의 특정 위치에있는 특정 "마커"문자에 의존합니까? 오류 메시지가 반환되는 것처럼 들립니다.

0

나는 matt b, 아마도 JSP 태그 사이의 공백에 동의합니다.

<%@ page trimDirectiveWhitespaces="true" %> 
+0

trimDirectiveWhitespaces는 매우 유용합니다. 그러나 일부 인터넷 검색은 JSP 2.1 이후에만 나타납니다 (꽤 새로울 것입니다). –

4

확인 지시어를 넣어보십시오, 나는이 작업을 얻었다. 여기에 어떻게 내가 해냈어 :

JSP :

<%@ taglib uri="utilTLD" prefix="util" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %> 
<%@ page language="java" session="false" %> 
<%@ page contentType="application/pdf" %> 

<%-- Construct and initialise the PrintReportsBean --%> 
<jsp:useBean id="printReportsBean" scope="request" class="some.package.PrintReportsBean" /> 
<jsp:setProperty name="printReportsBean" property="*"/> 

<% 
    // get report format as input parameter  
    ServletOutputStream servletOutputStream = response.getOutputStream(); 

    // reset buffer to remove any initial spaces 
    response.resetBuffer(); 

    response.setHeader("Content-disposition", "attachment; filename=HelloWorld.pdf"); 

    // check that user is authorised to download product 
    printReportsBean.getDownload(servletOutputStream); 
%> 

자바 콩 방법 : 자신의 입력을위한 모든 사람에게

//earlier in the class... 
private static FopFactory fopFactory = FopFactory.newInstance(); 

public void getDownload(ServletOutputStream servletOutputStream) throws UtilException { 

    OutputStream outputStream = null; 

    File fo = new File("C:\\some\\path", "HelloWorld.fo"); 

    try { 

     FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); 

     outputStream = new BufferedOutputStream(servletOutputStream); 

     Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, outputStream); 

     TransformerFactory factory = TransformerFactory.newInstance(); 
     Transformer transformer = factory.newTransformer(); //identity transformer 

     Source src = new StreamSource(fo); 

     Result res = new SAXResult(fop.getDefaultHandler()); 

     transformer.transform(src, res); 

    } catch (Exception e) { 

     throw new UtilException("Could not get download. Msg = "+e.getMessage()); 

    } finally { 

     try { 
      outputStream.close(); 
     } catch (IOException io) { 
      throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage()); 
     } 
    } 
} 

감사합니다!

관련 문제