We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Unable to download generated PDF when controller action is called from Ajax.

Hi,

I'm trying to generate a PDF file from a web page using PDF Control.

Suppose we have tho buttons on the web page:

BUTTON 1:

                    <button type='Button'
                            style='height: 30px;' name='GenerateQuoteDocument'
                            id='GenerateQuoteDocument' onclick=" location.rel='nofollow' href = '@Url.Action("GenerateQuoteDocument", "Quote", new {QuoteId = Model.QuoteId})' ">
                        Compila Documento Offerta
                    </button>
                    <button type='Button'
                            style='height: 30px;' name='GenerateQuoteDocumentWithLetter'
                            id='GenerateQuoteDocumentWithLetter' onclick="GenerateQuoteDocumentWithLetterClick()">
                        Compila Documento Offerta con Lettera Presentazione
                    </button>

The second button calls the following javascript function:

    function GenerateQuoteDocumentWithLetterClick() {
        debugger;

        $.ajax({
            url: '@Url.Action("GenerateQuoteDocumentWithLetter", "Quote")',
            type: 'POST',
            async: false,
            contentType: 'application/json;',
            data: JSON.stringify({ QuoteId: @Model.QuoteId, TxtSpett: $("#txt_spett").val(), TxtData: $("#txt_data").val(), TxtText1: $("#txt_aca").val(), TxtText2: $("#txt_serv").val()}),
            success: function (valid)
            {
                if(valid) {
                } else {

                }
            }
        });
    }

The controller methods are these:

ACTION 1

        public ActionResult GenerateQuoteDocument(int QuoteId)
        {
            bool result = false;

            Quote quote = db.Quotes.Include(c => c.Customer).Include(s => s.Site).Include(st => st.ServiceType).Include(sr => sr.Service).Include(p => p.QuoteEquipments).FirstOrDefault(i => i.QuoteId == QuoteId);
            if (quote != null)
            {
                string dataPath = DefaultResolveApplicationDataPath(quote.Service.ServiceCode + ".pdf");
                Stream file1 = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                PdfLoadedDocument docpdf = new PdfLoadedDocument(file1);
                PdfLoadedForm form = docpdf.Form;

                var txt_aree = form.Fields["AREE"] as PdfLoadedTextBoxField;
                if (txt_aree != null)
                    txt_aree.Text = quote.ServiceArea;

                var txt_numapp = form.Fields["NUMAPP"] as PdfLoadedTextBoxField;
                if (txt_numapp != null)
                {
                    txt_numapp.Text = "" + (quote.NumInt ?? 0);
                }

...
                docpdf.Form.Flatten = true;
                return docpdf.ExportAsActionResult("Off_" + quote.QuoteCode + ".pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
            }
            else
            {
                return RedirectToAction("Edit", "Quote", QuoteId);
            }
        }

ACTION 2

        [HttpPost]
        public ActionResult GenerateQuoteDocumentWithLetter(int QuoteId, string TxtSpett, DateTime TxtData, string TxtText1, string TxtText2)
        {
            var DOC_REPOSITORY_FOLDER = db.Settings.FirstOrDefault(c => c.SettingCode.Equals("DOC_REPOSITORY_FOLDER")).SettingVal;

            bool result = false;

            Quote quote = db.Quotes.Include(c => c.Customer).Include(s => s.Site).Include(st => st.ServiceType).Include(sr => sr.Service).Include(p => p.QuoteEquipments).FirstOrDefault(i => i.QuoteId == QuoteId);
            if (quote != null)
            {
               //GENERATE PDF 1
                string dataPathLP = DefaultResolveApplicationDataPath("LP.pdf");
                Stream fileLP = new FileStream(dataPathLP, FileMode.Open, FileAccess.Read, FileShare.Read);
                PdfLoadedDocument docpdfLP = new PdfLoadedDocument(fileLP);
                PdfLoadedForm formLP = docpdfLP.Form;
...
                var docnameLP = ControllerContext.HttpContext.Server.MapPath(@"~/") + DOC_REPOSITORY_FOLDER + @"\LP_" + quote.QuoteCode + ".pdf";
                docpdfLP.Form.Flatten = true;
                docpdfLP.Save(docnameLP);
                docpdfLP.Close();

                //GENERATE PDF 2
                string dataPath = DefaultResolveApplicationDataPath(quote.Service.ServiceCode + ".pdf");
                Stream file1 = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                PdfLoadedDocument docpdf = new PdfLoadedDocument(file1);
                PdfLoadedForm form = docpdf.Form;
...
                var docname = ControllerContext.HttpContext.Server.MapPath(@"~/") + DOC_REPOSITORY_FOLDER + @"\OFF_" + quote.QuoteCode + ".pdf";
                docpdf.Form.Flatten = true;
                docpdf.Save(docname);
                docpdfLP.Close();

                //MERGE 2 PDFs
                PdfDocument finalDoc = new PdfDocument();

                // Creates a string array of source files to be merged.
                string[] source = { docnameLP, docname };

                // Merges PDFDocument.
                PdfDocument.Merge(finalDoc, source);

                var PDFLPdocname = ControllerContext.HttpContext.Server.MapPath(@"~/") + DOC_REPOSITORY_FOLDER + @"\LPOFF_" + quote.QuoteCode + ".pdf";
                //Saves the final document
                finalDoc.Save(PDFLPdocname);

                //Closes the document
                finalDoc.Close(true);

                return docpdf.ExportAsActionResult(PDFLPdocname, HttpContext.ApplicationInstance.Response, HttpReadType.Save);
            }
            else
            {
                return RedirectToAction("Edit", "Quote", QuoteId);
            }
        }

Ok. When I call ACTION 1 everything is ok, that is PDF is created and downloaded and page is not reloaded.
Instead, when I call ACTION 2, the PDF is correctly created and saved, but the result is not downloaded and the view is reloaded, loosing the fields values used as parameters in the ajax call.

Is there a workaround for this problem?

Thanks

1 Reply

PV Prakash Viswanathan Syncfusion Team May 18, 2017 07:22 AM UTC

Hi Claudio, 
 
Thanks for contacting Syncfusion support. 
 
We could not directly download PDF document from Ajax call due to limitations in JavaScript, as a workaround we can save the pdf document in the disk and then load the document in iframe to download it 
 
Please refer below KB link to download the PDF document from Ajax Call. 
 
Refer the sample from the KB link, when click the Export button in the sample, PDF document will be created and downloaded, and page will not be reloaded.  
 
Please let us know if you need any further assistance on this. 
 
Regards, 
Prakash V 


Loader.
Live Chat Icon For mobile
Up arrow icon