2013-10-01 36 views
0

我用javascript和jquery使用Phonegap。我创建了一个java servlet,它返回一个pdf文件。我可以在浏览器中正确解析文件,但无法使用Phonegap。用Javascript和Servlet显示PDF

我的代码是这样的(JavaScript的):

$.ajax({ 
    type: "GET", 
    url: "http://x.x.x.x:xxxx/MyApp/PDF", 
    success: function(data, textStatus, request) { 
     alert("pdf OK"); 
     window.open(data, "_system"); 
    }, 
    error: function(data, textStatus, request) { 
     alert("pdr error"); 
    } 

而这里的servlet(这工作得很好,从浏览器):

protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { 
try { 
     // Create PDF (this works fine) 
    String ruta = getServletContext().getRealPath(reportTemplateUrl); 
    InputStream resourceAsStream = new FileInputStream(ruta); 
    jasperDesign = JRXmlLoader.load(resourceAsStream); 
    jasperReport = JasperCompileManager.compileReport(jasperDesign); 
    jasperPrint = JasperFillManager.fillReport(jasperReport, null, new JRBeanCollectionDataSource(findReportData(name))); 

    File pdf = new File("output.pdf"); 
    JasperExportManager.exportReportToPdfStream(jasperPrint, new FileOutputStream(pdf)); 

    // Send PDF 
    response.setContentType("application/pdf"); 
    response.addHeader("Content-Disposition", "attachment; filename=output.pdf"); 
    response.setContentLength((int) pdf.length()); 
    InputStream fileInputStream = new FileInputStream(pdf); 
    OutputStream responseOutputStream = response.getOutputStream(); 
    int bytes; 
    while ((bytes = fileInputStream.read()) != -1) { 
     responseOutputStream.write(bytes); 
    } 
    System.out.println("CREATED!"); 

} catch (JRException e) { 
    e.printStackTrace(); 
} 

此代码是在iPad上运行与PhoneGap的总是我得到OK警报。从iPad的浏览器中,我可以下载并阅读pdf(我把URL作为普通页面放在浏览器中),一切正常。

我认为这个问题是“数据”,从JavaScript,我不知道我是否需要先保存文件或者怎么做才能表现出来......

是的,我需要使用一个servlet和一个Ajax,PDF是动态的。我不介意用内部或外部浏览器打开它,但我需要看到它。

谢谢! :)

+0

你不能表现出与JavaScript –

+0

一个PDF,我可以得到的文件,并与外部浏览器中打开它?这可能是我的一个解决方案... – LuisSM

+0

你需要包括一个负载的科尔多瓦javascript SDK文件来获得_system的东西工作 - window.open(href,'_system','_blank'); –

回答

0

好吧,我解决了这个做JavaScript的一个GET调用一个新的浏览器中打开的网址:

window.open("http://.../PDF?id=id&name=name&...", "_blank"); 

没有Ajax。

谢谢大家