0

I'm using jQuery to submit my form to a servlet, in which produces PDF stream using iText.

private void service(HttpServletRequest request, HttpServletResponse response)
{
    String oid = "something";
    BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    Font font = new Font(bf, 12, Font.BOLD, BaseColor.BLUE);
    Document document = new Document(PageSize.A4, 20, 20, 20, 20);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
    document.open();

    Paragraph paragraph = new Paragraph(oid, font);
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(paragraph);
    document.close();
    pdfWriter.close();

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "inline;filename=" + oid + ".pdf");
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); 
    response.setHeader("Pragma", "No-cache");

    response.setContentLength(baos.size());
    ServletOutputStream sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
}

My question is, in my FORM.submit function, how can I convert the "responseData" into PDF and open it in a new tab/window instead of current JSP page?

$("#myform").submit(function() {
    $.ajax ({
        url: "MyServlet",
        type: "POST",
        data: values
    }) .done (function(responseData) {
    // alert(responseData);  // alert response from servlet, it's raw data of that PDF
    // HOW TO 'convert' RESPONSE TO PDF AND OPEN IT IN A NEW TAB/WINDOW ??
    });
    return false;
});

Any suggestion will be appreciated. Thanks!

1 Answers1

1

You cannot do what you're asking for in the done function of your ajax function call.

Javascript in the browser is unable to prompt or force a file download. Although responseData might contain the raw bytes for the PDF, there's no way to show it there. What you should do is have a URL you can hit that sets the Content-Type to whatever PDF is and streams the bytes to the response directly. In javascript, you can then point it to open new tab/window by hitting the previous URL.

You can set the location of the browser with

window.href.location = newLocation;

Take a look here for tricks.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724