What could be causing my site's PDF generation process to block other AJAX processes?

I am working on an MVC3 application that needs to generate extensive reports regularly. Users can select their criteria and request the report, which currently opens in a new tab/window using the Javascript window.open() method. However, while the report is being generated, the user is unable to interact with the site as everything waits for the report to finish processing. The code snippet responsible for generating the report is as follows:

private FileStreamResult doSpecReport(List<int> idProjItems)
{
    PdfDocument outputDocument = new PdfDocument(); // to be returned to the user
    foreach(var id in idProjItems)
    {
        var item = _entities.ProjectEquipmentItems.First(f => f.idProjectEquipmentItem == id);
        var cutsheetPath = item.CutSheet;
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        dictionary.Add("p_idEquipmentItem", id.ToString());
        var fs = GetReportHtml("NameOfReport", dictionary); // Returns FileStreamResult from crystal

        var inputDocument1 = CompatiblePdfReader.Open(fs.FileStream); // add the report to the output doc
        int count = inputDocument1.PageCount;
        for(int idx = 0; idx < count; idx++) 
        {
            PdfPage page = inputDocument1.Pages[idx];
            outputDocument.AddPage(page);
        }

        if (!string.IsNullOrEmpty(cutsheetPath))
        {
            cutsheetPath = Path.Combine(Server.MapPath("~/Files/CutSheetFiles/"), cutsheetPath);
            if (File.Exists(cutsheetPath))
            {
                var inputDocument2 = CompatiblePdfReader.Open(cutsheetPath);//, PdfDocumentOpenMode.Import);
                count = inputDocument2.PageCount;
                for(int idx = 0; idx < count; idx++)
                {
                    PdfPage page = inputDocument2.Pages[idx];
                    outputDocument.AddPage(page);
                }
            }
        }
    }

    var ms = new MemoryStream();
    outputDocument.Save(ms, false);
    ms.Position = 0;

    return new FileStreamResult(ms, "application/pdf")
    {
        FileDownloadName = "Report.pdf"
    };
}

I'm uncertain about any mistakes in my approach, and I find it puzzling why this process consumes all of the browser's resources. Any insights or assistance would be greatly appreciated.

Update: Here is one version of the code calling the doSpecReport function. The success section appears to be malfunctioning.

$.ajax({
    url: url,
    data: qdata,
    type: "POST",
    success: function (result) { // this doesn't actually work.
        var obj = $('<object type="application/pdf" width="100%" height="100%" border="2"></object>');
        obj.attr('data', 'data:application/pdf;base64,' + result);
        $(".mask").hide();
        $('#divContainer').append(obj);
    }
});

Answer №1

In order to display a PDF on the web using HTML, you need to create a temporary file location on the server side to store the PDF file and then provide the URL to access it. It is not possible to directly set HTML Document contents with a binary PDF file. Instead, generate the report, save it in a temporary location, and share the URL link in the response.

Assume that the function doSpecReport creates a temporary PDF file named 'mypdf.pdf'. After generating the PDF, include it in the success block as an object with data attribute like this example

<object width="400" height="500" type="application/pdf" data="/mypdf.pdf?#zoom=85&scrollbar=0&toolbar=0&navpanes=0" id="pdf_content">
</object>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to add a vanilla JavaScript keyup event listener to an Angular md-autocomplete input by utilizing the DOM id?

I am working with an angular md-autocomplete setup that looks like this: <md-autocomplete md-input-id="myid" ...> </md-autocomplete> My goal is to add an event listener like this: document.getElementById("myid") .addEventListener ...

Enhance user input with Struts 2 autocompletion feature

<ajax:autocompleter name="cityName" list="list" size="1" label="Select City" listValue="cityName" listKey="id" autoComplete="true"></ajax:autocompleter> I encountered an issue while implementing Struts 2 with AJAX, as the autocomplete fun ...

Leverage JavaScript to run a snippet of PHP code directly (without utilizing a separate PHP file)

I am looking for a way to integrate PHP into my web page using JavaScript and AJAX. I want the PHP file to be included and executed as if it is part of the native page, allowing me to utilize features like GET requests. <div id="firstAjaxDiv">Defaul ...

Outputting the highest value in the array to the console screen

It seems like there's a silly mistake I'm overlooking. I want to display a message in the console window and also show the maximum value from an array on the same line. When I execute the code without the console message, everything works perfec ...

Stop automated web crawlers from crawling through JavaScript links

To enable remote jQuery templating, I have embedded some links in JavaScript. For example: <script type="text/javascript"> var catalog = {}; catalog['key1'] = 'somepath/template_1.html'; catalog['key2'] = 'anotherp ...

Is there a way to automatically load Moment.JS within Compound.JS?

Is it possible to make Moment accessible worldwide using the Compound framework with its module auto-loading feature? How can "moment" be included in the autoload array and used within the application? ...

Unexpected behavior occurs in ReactNative when the keyboard pushes the content away, causing issues with KeyBoardAvoidingView

Currently, I am working on integrating a small input form in react-native. However, I have encountered an issue where when I open the keyboard, it disrupts the layout and content of the form. I attempted using KeyBoardAvoidingView and ScrollView in vario ...

Sending an AJAX request with an unpredictable quantity of parameters

I built a form for my website that pulls questions from a database based on certain variables. This means the number of questions available is unknown. The code snippet for displaying these questions looks like this: HTML <ol class="questions"> ...

How to Make a Zigzag Formation in three.js?

I have been working on developing a 3D tool and was in need of a zigzag structure. I managed to create it by iterating a function that produces 'V' multiple times, but now I am looking for a way to achieve the same effect using a single geometry ...

Sort the array by the elements in a separate array

Here is a filters array with three values: serviceCode1, serviceCode2, and serviceCode3. ['serviceCode1', 'serviceCode2', 'serviceCode3'] I have another array with approximately 78 records that I want to filter based on the a ...

HTML element not refreshing properly following AJAX request

I have a script that adds and removes entries from a table by utilizing ajax to call a php script. However, instead of reloading the div containing the table upon success, it currently only clears the div. Below is the javascript code being used: $(docum ...

Creating a Social Media Platform with JavaScript, Bootstrap, JQuery, PHP, and Mysqil

I am currently in the process of developing a social networking platform that will have similar features as Instagram. Users will be able to log in, create posts, leave comments, like content, share posts, and send data to a server for storage or display p ...

Expanding content based on height using React

I have successfully implemented the show more/show less feature. However, my issue is that I would like it to be based on the number of lines or screen height rather than the number of characters. This is because the current setup may look awkward on certa ...

Obtaining the checked element's value within a for loop

I'm currently trying to retrieve and send each value of the checked elements to PHP. However, I am only able to obtain the first value of one checked item. Here is the code snippet: $("#conf").click(function(){ var count = $("input:checked").len ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

When CSS is modified by inserting an extra div, it causes the positioning of other elements to shift towards

I'm currently working on adapting a method to make elements "sticky" for older browsers as discussed in this particular article. The basic idea involves implementing some JavaScript code that listens for scroll events. Upon detection of such an event ...

Using Bootstrap 4 navtabs alongside accordions to utilize the show.bs and hide.bs functionalities

Is there a method to activate the "Maintab 2 Content" and display the accordion content for "Collapsible Group Item #2" when clicking on the "Button for Maintab 2"? I am trying to implement similar functionality on other tabs as well, but I'm struggli ...

Is it possible to update the event parameters with every click?

Is there a way to dynamically add a Select box for selecting a condition each time the "add" button is clicked? For example, when the add button is clicked, I would like the following elements to be continuously added: https://i.stack.imgur.com/6bad2.png ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

Retrieving dynamic data from a database using AJAX and PHP and storing them as variables

I am currently working on a project that involves populating a list through a database and then navigating to a nested page within the current page using AJAX and PHP. The issue I am facing seems to be related to PHP rather than AJAX, as I have already imp ...