如何使用RESTful/ajax/js在UI上显示PDF,使用来自UI的表单输入

How to show PDF on UI using RESTful/ajax/js using form input from UI?

本文关键字:UI 输入 表单 显示 ajax RESTful 何使用 js PDF      更新时间:2023-09-26

我正在尝试使用javascript和ajax显示RESTful服务UI的PDF报告。它可以很好地处理单个输入,但对于使用UI中的表单的多个输入,我后来将其更改为JSON对象,它没有以正确的格式显示PDF。我已经使用POSTMAN检查了服务,它运行良好(下载PDF)。

下面是用JAVA编写的服务代码。

 @POST
  @Path("/CustomizedReport")
  @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  @Produces("application/pdf")
  public Response getCustomizedReport(SubscriberCriteriaTool sct) throws ParseException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    new CustomizedReport().aaGeneratePdf(outputStream, sct);
    byte[] bytes = outputStream.toByteArray();
    DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
    ResponseBuilder response = Response.ok(dataSource);
    response.header("Content-Disposition", "inline; filename=CustomizedReport.pdf");
    return response.build();
  }

下面是javascript中的函数。

function generateCustomizedReport() {
    console.log('generateCustomizedReport');
    $.ajax({
        type : 'POST',
        contentType : 'application/json',
        url : 'http://localhost:8080/Morpheus/api/reports/CustomizedReport',
        data : formToJSONReport(),
        success : function(response) { 
                    document.write(response);
        },
        error : function(error, status) {
            window.alert("Problem retrieving PDF.'nThe error status is: " + error);
        }
    });
}

下面是将表单更改为JSON的函数。现在它是硬编码的,但计划在工作后从UI中获取输入。这与我在POSTMAN上检查的字符串完全相同,它给出了正确的结果(下载PDF)。

function formToJSONReport() {
    return JSON.stringify({
        "fromDate" : "10/01/2014",
        "rateCenter" : "HUNTINGTON",
        "status" : "SUCCESSFUL",
        "toDate" : "11/01/2014",
        "group" : "Third"
    });
}

这是我在UI上得到的PDF文本(无法发布快照,因为我是stackoverflow的新手)。

%PDF-1.4%����1 0 obj<>流动����ExifII*��Ducky7���http://ns.adobe.com/xap/1.0/��!Adobed�B�M@D]��� ##########

提前感谢:-)

您的响应是文件流字节,我们无法通过将字节直接写入文档来显示文件,但我们可以使用iframe或新窗口下载具有指定内容类型的流(此处为application/pdf)(或另一个技术人员通过以iframe为目标或_blank附加表单,即响应将在新窗口新窗口中打开)。

尝试将您的成功函数更改为以下

    success : function(response) {
            //This double pass request Technic is to download the file stream via iframe.
            $("<iframe>").attr("src", 'http://localhost:8080/Morpheus/api/reports/CustomizedReport')
            //.hide()//hide it while download
            .appendTo("body");
            //OR you can try with popup window
            //window.open('http://localhost:8080/Morpheus/api/reports/CustomizedReport')
    }

通常我们在控制器中写两个动作

  1. 对于Validate Request并返回带有有效令牌的响应(某些密钥和时间戳的加密值)
  2. 通过iframe(或新窗口)获取文件,该文件具有在第一个请求成功(或完成)回调的响应中接收的上述有效令牌