0

I can generate and download a PDF file successfully if there's only one. However, when I attempt to generate and download multiple PDFs, I encounter an issue. I'm using the same code that works for downloading a single PDF. Instead of downloading the PDFs, they are only stored in the designated location.

Thank you in advance for the help.

Here is my js:

function GeneratePackingSlipAction() {
            var checkedVals = GetSelectedOrders();

            if (checkedVals.length > 0) {
                $.ajax({
                    url: '/Orders/PackingSlipBulkOrders',
                    type: 'POST',
                    data: { selectedOrderIds: checkedVals }
                }).done(function (data) {
                    console.log(data);
                    alert("was heree:" + data.status);
                    if (data.status == true) {
                        var msg = "Generated Packing Slip " + data.successCount + " order(s)";
                        alert(msg);
                        jQuery(this).removeClass("checkedall");
                        jQuery(".SelectOrder").prop("checked", false);
                    }
                });
            }
        }
And the c# controller code:
public ActionResult PackingSlipBulkOrders(long[] selectedOrderIds)
        {
            int successCount = 0;
            int failedCount = 0;

            if (selectedOrderIds.Count() > 0)
            {
                foreach (var id in selectedOrderIds)
                {
                    try
                    {
                        Order order = _orderMgr.GetOrder(id);
                        var result = GenerateExcelPDFBulk(order);
                        successCount++;
                    }
                    catch
                    {
                        failedCount++;
                    }
                }
            }
            return Json(new { status = true, successCount = successCount, failedCount = failedCount });
        }

public bool GenerateExcelPDFBulk(Order order)
        {
            PDFHelperPackingSlip _pdfHelper = new PDFHelperPackingSlip();
            string footerimgpath = Server.MapPath("~/Content/images/dark-logo.png");
            //Create Excel File and Save
            string FileName = "PackingSlip.pdf";
            string fileLocation = Server.MapPath("~/Content/Imports/") + FileName;
            if (System.IO.File.Exists(fileLocation))
            {
                System.IO.File.Delete(fileLocation);
            }
            string filename = _pdfHelper.GeneratePDF(order, fileLocation, footerimgpath);

            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fileLocation));
            Response.TransmitFile(fileLocation);
            Response.Flush();
            Response.Close();
            Response.End();

            return true;
        }
1
  • 2
    A single request can only have one response. If you need to send multiple PDFs, perhaps you should create a zip file. Commented Jun 19, 2024 at 5:25

1 Answer 1

1

You can choose two options,

First Option: generate several requests

or

Second Option: generate a zip file in which all the files are

This is the code you will have to use:

function GeneratePackingSlipAction() {
    var checkedVals = GetSelectedOrders();

    if (checkedVals.length > 0) {
        $.ajax({
            url: '/Orders/PackingSlipBulkOrders',
            type: 'POST',
            data: { selectedOrderIds: checkedVals }
        }).done(function (data) {
            if (data.status === true) {
                var msg = "Generated Packing Slip " + data.successCount + " order(s)";
                alert(msg);
                var link = document.createElement('a');
                link.href = '/Content/Imports/PackingSlips.zip';
                link.download = 'PackingSlips.zip';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } else {
                alert("Failed to generate packing slips.");
            }
        });
    }
}

public ActionResult PackingSlipBulkOrders(long[] selectedOrderIds)
{
    int successCount = 0;
    int failedCount = 0;
    List<string> fileLocations = new List<string>();

    if (selectedOrderIds.Length > 0)
    {
        foreach (var id in selectedOrderIds)
        {
            try
            {
                Order order = _orderMgr.GetOrder(id);
                var fileLocation = GenerateExcelPDFBulk(order);
                if (!string.IsNullOrEmpty(fileLocation))
                {
                    fileLocations.Add(fileLocation);
                    successCount++;
                }
            }
            catch
            {
                failedCount++;
            }
        }
    }

    if (fileLocations.Count > 0)
    {
        string zipFile = CreateZipFile(fileLocations);
        return Json(new { status = true, successCount = successCount, failedCount = failedCount, zipFile });
    }

    return Json(new { status = false, successCount = successCount, failedCount = failedCount });
}

public string GenerateExcelPDFBulk(Order order)
{
    PDFHelperPackingSlip _pdfHelper = new PDFHelperPackingSlip();
    string footerimgpath = Server.MapPath("~/Content/images/dark-logo.png");
    string fileName = $"PackingSlip_{order.OrderId}.pdf";
    string fileLocation = Server.MapPath("~/Content/Imports/") + fileName;

    if (System.IO.File.Exists(fileLocation))
    {
        System.IO.File.Delete(fileLocation);
    }
    _pdfHelper.GeneratePDF(order, fileLocation, footerimgpath);

    return fileLocation;
}

public string CreateZipFile(List<string> fileLocations)
{
    string zipPath = Server.MapPath("~/Content/Imports/PackingSlips.zip");

    if (System.IO.File.Exists(zipPath))
    {
        System.IO.File.Delete(zipPath);
    }

    using (var zip = ZipFile.Open(zipPath, ZipArchiveMode.Create))
    {
        foreach (var file in fileLocations)
        {
            zip.CreateEntryFromFile(file, Path.GetFileName(file));
        }
    }

    return zipPath;
}

This option in my opinion is the most viable, whether you have 1 file or 200 you will download a single zip, another cruder option but perhaps more useful is to make multiple requests to your code depending on how many pdfs you want, thus generating "x" downloads by number of PDFs that you want allowing better individual treatment (but as I said before it is more crude since in the case that you want 200 pdfs you would download the 200 one by one as opposed to a single zip with all the files inside).

If you want me to show you this option too, you just have to ask.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.