所以我试图一次将所有已付款发票下载为 pdf。但是当我下载一张发票时,代码可以工作,但对于多张发票,它返回错误 500。
多张发票代码
public ActionResult ExportAndDownloadAllCROInvoices(int CROID)
{
var listInvoices = new VM_Invoice().FindAllByAttributes(x => x.CreatedForId == CROID && x.CreatedForType == (int)UserTypes.CRO && x.IsPaid == true);
try
{
string folderPath = Server.MapPath("~/PDFInvoices/");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
List<string> filePaths = new List<string>();
foreach (var invoiceModel in listInvoices)
{
string htmlString = string.Empty;
if (invoiceModel.CreatedForType == (int)UserTypes.CRO)
{
htmlString = new VM_Invoice().GetCROInvoiceHtmlTemplate(invoiceModel);
}
byte[] fileBytes = PDFUtilities.ExportInvoicePDF(htmlString);
string fileName = string.Format("Invoice-{0}-{1}.pdf", invoiceModel.InvoiceNo, DateTime.UtcNow.ToString("MMddyyyy"));
string filePath = Path.Combine(folderPath, fileName);
System.IO.File.WriteAllBytes(filePath, fileBytes);
filePaths.Add(filePath);
}
// Create a zip archive containing all PDF invoices
string zipPath = Path.Combine(Server.MapPath("~/PDFInvoices/"), "Invoices.zip");
ZipFile.CreateFromDirectory(folderPath, zipPath);
// Clean up individual PDF files
foreach (var filePath in filePaths)
{
System.IO.File.Delete(filePath);
}
// Return the zip archive as a downloadable file
return File(System.IO.File.ReadAllBytes(zipPath), "application/zip", "Invoices.zip");
}
catch (Exception ex)
{
ViewBag.ErrorMessage = "An error occurred while generating and downloading PDF invoices.";
return RedirectToAction("WorkLogReport", "ControllerName");
}
}
单一发票代码
public ActionResult ExportPDFInvoice(int id)
{
string htmlString = string.Empty;
try
{
VM_Invoice invoiceModel = new VM_Invoice().FindById(id);
if (invoiceModel.CreatedForType == (int)UserTypes.Consumer)
{
htmlString = new VM_Invoice().GetConsumerInvoiceHtmlTemplate(invoiceModel);
}
else
{
htmlString = new VM_Invoice().GetCROInvoiceHtmlTemplate(invoiceModel);
}
byte[] fileBytes = PDFUtilities.ExportInvoicePDF(htmlString);
string fileName = string.Format("Invoice-{0}.pdf", DateTime.UtcNow.ToString("MMddyyyy"));
return File(fileBytes, "application/pdf", fileName);
}
catch (Exception ex)
{
return RedirectToAction("WorkLogReport");
}
}
如果您已经验证您的过程有效,则错误可能是由于 .pdf 文件和 .zip 文件位于同一目录中,因此 ZipFile 类也尝试压缩它正在创建的存档。尝试使用另一个目标 .zip 目录。