无法访问已关闭的文件.net MVC?

时间:2017-05-25 17:58:05

标签: c# asp.net-mvc itext

想要使用itextsharp向现有pdf添加文字 到目前为止,我已经完成了。我的代码=>

    public FileStreamResult DownloadCertificate(string UserId)
    {
        //get user info using UserId from database
        //UserDetail UserDetail = db.UserDetails.Where(x => x.UserId == UserId).FirstOrDefault();
        string oldFile = Server.MapPath("~/Content/img/tsms/Certificate/Certificate-of-Completion-Award-Template-Blue.pdf");
        string newFile = Server.MapPath("~/Content/img/tsms/Certificate/newFile.pdf");
        // open the reader
        PdfReader reader = new PdfReader(oldFile);
        Rectangle size = reader.GetPageSizeWithRotation(1);
        Document document = new Document(size);
        // open the writer
        FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
        PdfWriter writer = PdfWriter.GetInstance(document, fs);
        document.Open();
        // the pdf content
        PdfContentByte cb = writer.DirectContent;
        // select the font properties
        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.SetColorFill(BaseColor.DARK_GRAY);
        cb.SetFontAndSize(bf, 8);
        // write the text in the pdf content
        cb.BeginText();
        string text = "Some random blablablabla...";
        // put the alignment and coordinates here
        cb.ShowTextAligned(1, text, 520, 640, 0);
        cb.EndText();
        // write the text in the pdf content
        cb.BeginText();
        text = "Other random blabla...";
        // put the alignment and coordinates here
        cb.ShowTextAligned(2, text, 100, 200, 0);
        cb.EndText();
        // create the new page and add it to the pdf
        PdfImportedPage page = writer.GetImportedPage(reader, 1);
        cb.AddTemplate(page, 0, 0);
        // close the streams and voilá the file should be changed :)
        document.Close();
        fs.Close();
        writer.Close();
        reader.Close();
        return new FileStreamResult(fs, "application/pdf");
    }

问题是当我尝试访问方法浏览器时显示我的错误如下=> enter image description here

我不知道为什么它会给我这种错误。

我试图找到解决方案。我发现.... FileStream "cannot access closed file"

但这对我来说还不够。

我还尝试更改代码中的某些行。下面=>

  // close the streams and voilá the file should be changed :)
  document.Close();
  //fs.Close();
  //writer.Close();
  //reader.Close();
  return new FileStreamResult(fs, "application/pdf");

但这种改变对我没有帮助。我在代码中做错了什么。(我也可以为用户提供下载模式。)

1 个答案:

答案 0 :(得分:0)

在我看来,这是FileStream的一个问题。我的有根据的猜测是document.Close();的呼叫也在关闭FileStream

您可以尝试不重复使用相同的流,而是打开一个新的只读(顺便说一下,它也将重置其位置)并将其用于结果。