Cannot create iTextSharp PDF from inside the Controller, but works fine when the same Action is called from View

与世无争的帅哥 提交于 2020-05-17 07:28:26

问题


In my controller, I have an action like this to generate a PDF using iTextSharp:

public FileResult Print(int id)
{
    string fileName = "something.pdf";
    Document document = new Document(PageSize.A4, 18, 18, 36, 36);
    MemoryStream stream = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, stream);
    HeaderFooter.Title = "Something";
    HeaderFooter.Box = "box";
    HeaderFooter tevent = new HeaderFooter();
    writer.SetBoxSize(HeaderFooter.Box, new Rectangle(18, 72, 577, 770));
    writer.PageEvent = tevent;
    document.Open();
    .
    .
    .
    document.Close();
    return File(stream.ToArray(), "application/pdf", fileName);
}

After the document (invoice) is created, I can print it from a view like that: <a href="@Url.Action("Print", new { id = Model.InvoiceID })"> and it works fine. But what I really want is to print it at the end of the creation process before the return, and there the document is not printed (without any error message):

// POST: /Invoice/Create
[HttpPost]
public JsonResult Create(Invoice invoice)
{
    try
    {
        if (ModelState.IsValid)
        {
            .
            .
            .
            unitOfWork.InvoiceRepository.Insert(invoice);
            unitOfWork.Save();
            Print(invoice.invoiceID);
        }
        return Json(new { Success = 1, InvoiceID = invoice.InvoiceID, ex = "" });
    }
    catch {...}
}

I have verified that every step of the Print action is executed but no pdf is returned. What am I doing wrong?

来源:https://stackoverflow.com/questions/61413723/cannot-create-itextsharp-pdf-from-inside-the-controller-but-works-fine-when-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!