c# - 返回内存流 - 提供损坏的 PDF 文件或 "cannot accessed a closed stream"

标签 c# pdf stream itextsharp

我有一个 Web 服务,它调用以下方法。我想返回一个内存流,它是一个 PDF 文件。

现在,问题是 PDF 文件因以下代码而损坏。我认为这是因为文件没有被关闭。但是,如果我关闭它们,我会收到经典错误“无法访问已关闭的流”。

当我之前通过文件流保存它时,PDF 文件没有损坏。

所以我的小问题是:如何解决它并取回未损坏的 PDF 文件? :-)

我的代码:

public Stream Generate(GiftModel model)
{
    var template = HttpContext.Current.Server.MapPath(TemplatePath);

    // Magic code which creates a new PDF file from the stream of the other
    PdfReader reader = new PdfReader(template);
    Rectangle size = reader.GetPageSizeWithRotation(1);
    Document document = new Document(size);

    MemoryStream fs = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, fs);
    document.Open();

    // Two products on every page
    int bookNumber = 0;
    int pagesWeNeed = (int)Math.Ceiling(((double)model.Books.Count / (double)2));
    for (var i = 0; i < pagesWeNeed; i++)
    {
        PdfContentByte cb = writer.DirectContent;

        // Creates a new page
        PdfImportedPage page = writer.GetImportedPage(reader, 1);
        cb.AddTemplate(page, 0, 0);

        // Add text strings
        DrawGreetingMessages(model.FromName, model.ReceiverName, model.GiftMessage, cb);

        // Draw the books
        DrawBooksOnPage(model.Books.Skip(bookNumber).Take(2).ToList(), cb);

        // Draw boring shit
        DrawFormalities(true, model.GiftLink, cb);

        bookNumber += 2;
    }

    // Close off our streams because we can
    //document.Close();
    //writer.Close();
    reader.Close();

    fs.Position = 0;
    return fs;
}

最佳答案

流的重用可能会出现问题,尤其是当您使用抽象并且不太清楚它对您的流做了什么时。正因为如此,我通常建议永远不要让流自己四处传递。如果可以,请尝试只传递原始底层字节数组本身。但是,如果需要传递流,那么我建议仍然在最后处理原始字节数组,然后将其包装在新的第二个流中。试试下面的代码,看看它是否有效。

public Stream Generate(GiftModel model)
{
    //We'll dump our PDF into these when done
    Byte[] bytes;

    using (var ms = new MemoryStream())
    {
        using (var doc = new Document())
        {
            using (var writer = PdfWriter.GetInstance(doc, ms))
            {
                doc.Open();
                doc.Add(new Paragraph("Hello"));
                doc.Close();
            }
        }
        //Finalize the contents of the stream into an array
        bytes = ms.ToArray();
    }
    //Return a new stream wrapped around our array
    return new MemoryStream(bytes);
}

关于c# - 返回内存流 - 提供损坏的 PDF 文件或 "cannot accessed a closed stream",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20287587/

相关文章:

javascript - 可靠地呈现在网页上加载时打开打印对话框的 PDF

java - 如何使用java播放asx文件/流

c# - 为什么 WeakReference 在析构函数中没用?

c# - app.UseHsts() 和 app.UseExceptionHandler() 有什么区别?

c++ - 从模板创建用于在 Qt 中打印的 PDF 文档

ios - 如何在 iphone sdk 中获取 Vfr Reader for Pdf 的目录?

c# - 为什么我将流作为 System.IO.UnmanagedMemoryStream?

linux - 使用 sed 显示 C 风格注释和 C++ 注释

c# - .NET 2.0 是 .NET 1.1 的彻底改变?

c# - DllImport 与 ComImport