解析器错误:在Spring MVC中从Ajax调用Jasper报表时发生。

huangapple go评论73阅读模式
英文:

parsererror when calling jasperreport from ajax in spring mvc

问题

我从jQuery Ajax调用端点以使用Spring MVC生成Jasper报告,并希望在新的浏览器标签中以PDF格式查看生成的报告。问题在于,我得到了报告解析错误,ajax返回了从文本到application/pdf的转换失败错误。如果我从浏览器进行请求调试,我可以看到响应中获取的PDF文本。

以下是调用Spring MVC方法的Ajax代码:

var developerData = {};
developerData["from"] = $("#productivity_dateTimeFrom").val();
developerData["to"] = $("#productivity_dateTimeTo").val();
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: 'Productivity',
    data: JSON.stringify(developerData),
    dataType: 'application/pdf',
    success: function(data) {
        window.open(data.fileUrl);
    },
    error: function(request, status, error) {
        alert(request)
        alert(status)
        alert(error)
    }
});

Spring MVC方法被Ajax调用:

@RequestMapping(value = "/Productivity", method = RequestMethod.POST, produces = "application/pdf")
@ResponseBody
public ResponseEntity<byte[]> runReport(@RequestBody String object) throws IOException, JRException {

    // ... 省略部分代码 ...

    JasperPrint jasperPrint = null;
    try {
        jasperPrint = JasperFillManager.fillReport(jasperReport, params, rep_connection);
    } catch (JRException e) {
        // ... 省略错误处理代码 ...
    }
    
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    
    try {
        JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);
    } catch (JRException e) {
        // ... 省略错误处理代码 ...
    }

    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.APPLICATION_PDF);
    String filename = "report.pdf";

    headers.add("content-disposition", "inline;filename=" + filename);

    return new ResponseEntity<>(outStream.toByteArray(), headers, HttpStatus.OK);

}
英文:

I'm calling endpoint from jquery ajax to generate jasperreport using spring mvc and I want to view generated report as pdf in new browser tab.
The problem is that I'm getting report parsererror with conversion failure from text to application/pdf error returned to ajax ,and if I make debug of the request from browser I see pdf text obtained in response

Here is Ajax code that calls the spring mvc method

var developerData = {};
		developerData[&quot;from&quot;] = $(&quot;#productivity_dateTimeFrom&quot;).val();
		developerData[&quot;to&quot;] = $(&quot;#productivity_dateTimeTo&quot;).val();
		$.ajax({
			type : &quot;POST&quot;,
			contentType : &quot;application/json; charset=utf-8&quot;,
			url : &#39;Productivity&#39;,
			data : JSON.stringify(developerData),
			dataType : &#39;application/pdf&#39;,
			success : function(data) {					
				window.open(data.fileUrl);
			},
			error : function(request,status,error){
				alert(request)
				alert(status)
				alert(error)
			}
		});

Spring mvc method to be called from ajax:

@RequestMapping(value = &quot;/Productivity&quot;, method = RequestMethod.POST, produces =&quot;application/pdf&quot;)
@ResponseBody
public ResponseEntity&lt;byte[]&gt; runReport(@RequestBody String object) throws IOException, JRException {

	db_con db_con = new db_con();
	Resource resource = new ClassPathResource(&quot;Productivity.jasper&quot;);
	InputStream jasperStream = null;
	Gson g = new Gson();
	try {
		jasperStream = resource.getInputStream();
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}

	DateTimeRange p = g.fromJson(object, DateTimeRange.class);
	Map&lt;String, Object&gt; params = new HashMap&lt;String, Object&gt;();
	params.put(&quot;p_from_date&quot;,dateUtils.convertStringToTimestamp(p.getFrom().replace(&quot;T&quot;, &quot; &quot;)+&quot;:00.000&quot;));
	params.put(&quot;p_to_date&quot;,dateUtils.convertStringToTimestamp(p.getTo().replace(&quot;T&quot;, &quot; &quot;)+&quot;:00.000&quot;));
	params.put(&quot;username&quot;, &quot;admin&quot;);
	params.put(&quot;p2&quot;, 1L);
	params.put(&quot;p3&quot;, &quot;All&quot;);
	JasperReport jasperReport = null;

	try {
		jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
	} catch (JRException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	Connection rep_connection = null;

	try {
		rep_connection = db_con.get_connection();
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	JasperPrint jasperPrint = null;
	try {
		jasperPrint = JasperFillManager.fillReport(jasperReport, params, rep_connection);
	} catch (JRException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
	
    try {
		JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);
	} catch (JRException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.APPLICATION_PDF);
    String filename = &quot;report.pdf&quot;;

    headers.add(&quot;content-disposition&quot;, &quot;inline;filename=&quot; + filename);

    return new ResponseEntity&lt;&gt;(outStream.toByteArray(), headers, HttpStatus.OK);

}

答案1

得分: 1

尝试将PDF文件下载为Blob并使用Blob URL来查看它

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: 'Productivity',
    data: JSON.stringify(developerData),
    xhrFields: {
        responseType: 'blob'
    },
    success: function(data) {
        window.open(URL.createObjectURL(data));
    },
    error: function(request, status, error) {
        alert(request)
        alert(status)
        alert(error)
    }
});
英文:

Try downloading the pdf as a blob and using a blob url to view it

    $.ajax({
        type : &quot;POST&quot;,
        contentType : &quot;application/json; charset=utf-8&quot;,
        url : &#39;Productivity&#39;,
        data : JSON.stringify(developerData),
        xhrFields:{
            responseType: &#39;blob&#39;
        },
        success : function(data) {                  
            window.open(URL.createObjectURL(data));
        },
        error : function(request,status,error){
            alert(request)
            alert(status)
            alert(error)
        }
    });

huangapple
  • 本文由 发表于 2020年9月3日 22:44:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63726032.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定