简体   繁体   中英

Return PDF from Controller called via jQuery AJAX

I found some answers about using a controller to create a PDF from EvoPDF however none seem to deal with the controller being called via jQuery AJAX.

I have a simple jQuery function that sends data to a controller much like many others in my app:

$.ajax({
    url: "/AnnualFees/showStatement",
    cache: false,
    data: {
        authKey: memberData.authKey,
        entityId: memberData.entityId,
        barNumber: memberData.barNumber,
        statementHTML: encodeURIComponent($("#statementBody").html())
    },
    method: "POST",
    success: function (data) {
    },
});

I followed all the samples and have this code. I can change it to save the PDF and confirm that the PDF is being generated.

public ActionResult getStatementPDF(string statementHTML)
{
    //initialize the PdfConvert object
    PdfConverter pdfConverter = new PdfConverter();

    // set the license key - required
    pdfConverter.LicenseKey = "uzUmNCcnNCYsIjQgOiQ0JyU6JSY6LS0tLQ==";

    StringBuilder PDFBody = new StringBuilder();
    PDFBody.Append("<!DOCTYPE html>");
    PDFBody.Append("<html lang=\"en\">");
    PDFBody.Append("<head>");
    PDFBody.Append("    <meta charset=\"utf - 8\">");
    PDFBody.Append("    <title>Statement</title>");
    PDFBody.Append("</head>");
    PDFBody.Append("");
    PDFBody.Append("<body>");
    PDFBody.Append("Hello world.");
    PDFBody.Append("</body>");
    PDFBody.Append("</html>");

    byte[] outPdfBuffer = pdfConverter.GetPdfBytesFromHtmlString(PDFBody.ToString());

    // Send the PDF file to browser
    FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
    fileResult.FileDownloadName = "Statement.pdf";

    return fileResult;
}

I can confirm their are no errors and that a 200 success is returned with the right application/pdf type and about the same size as on disk. However, no PDF ever appears, nothing opens in the browser.

You need to handle the data onSuccess in the ajax call, you can do something like this to open the file, you may want to use FileSaverJS ( https://github.com/eligrey/FileSaver.js/ ) if you want to save the file

success: function (data) {

    var file = new Blob([data], { type: 'application/pdf' });
    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM