C# Append PDF file to MemoryStream - Cannot access a closed Stream

早过忘川 提交于 2019-12-24 02:14:35

问题


Is it possible to append an existing PDF file to a dynamically created PDF using iTextSharp? I have attempted as per my code below using PdfCopy, but I am getting a Cannot access a closed Stream error.

I've seen examples merging actual PDF files together, but I am not storing the finished PDFs, simply outputting the MemoryStream to a FilestreamResult:

private readonly float _spacingBefore = 3f;

private readonly float _spacingAfter = 3f;

private readonly float _totalWidth = PageSize.A4.Width - 80;

public MemoryStream CreateMemoryStream()
{
    var document = new Document(PageSize.A4, 25, 25, 30, 30);

    var workStream = new MemoryStream();

    PdfWriter.GetInstance(document, workStream);

    var pdfCopy = new PdfCopy(document, workStream);

    document.Open();

    var pdfPTable = new PdfPTable(1)
    {
        TotalWidth = _totalWidth,
        LockedWidth = true,
        SpacingBefore = _spacingBefore,
        SpacingAfter = _spacingAfter
    };

    float[] widths = { 272f };

    pdfPTable.SetWidths(widths);

    var image = Image.GetInstance(HttpContext.Current.Server.MapPath("\\Images\\Logo.png"));
    image.ScaleToFit(125f, 125f);
    image.Alignment = Image.RIGHT_ALIGN;

    var pdfPCell = new PdfPCell(image)
    {
        Border = 0,
        HorizontalAlignment = Element.ALIGN_RIGHT
    };

    pdfPTable.AddCell(pdfPCell);

    document.Add(pdfPTable);

    pdfCopy.AddDocument(new PdfReader(HttpContext.Current.Server.MapPath("/Documents/Test.pdf")));

    if (document != null)
    {
        document.Close();
    }

    var file = workStream.ToArray();

    var memoryStream = new MemoryStream();
    memoryStream.Write(file, 0, file.Length);
    memoryStream.Position = 0;

    return memoryStream;
}

public FileStreamResult Pdf(int id)
{
    var memoryStream = CreateMemoryStream();

    HttpContext.Response.AddHeader("content-disposition", "inline; filename=" + id + ".pdf");

    return File(memoryStream, "application/pdf");
}

I've also tried the following instead of pdfCopy.AddDocument(new PdfReader(HttpContext.Current.Server.MapPath("/Documents/Test.pdf")));

var pdfReader = new PdfReader(HttpContext.Current.Server.MapPath("/Documents/Test.pdf"));

var numberOfPages = pdfReader.NumberOfPages;

for (var i = 0; i < numberOfPages;)
{
    pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, ++i));
}

No matter what approach I still get a Cannot access a closed Stream error.

Any help would be much appreciated :-)


回答1:


Below is a solution to my issue, I hope it proves useful to others:

public MemoryStream CreateMemoryStream()
{
    byte[] dynamicPdfBytes;

    using (var dynamicPDfMemoryStream = new MemoryStream())
    {
        using (var document = new Document(PageSize.A4, 25, 25, 30, 30))
        {
            PdfWriter.GetInstance(document, dynamicPDfMemoryStream);

            document.Open();

            var pdfPTable = new PdfPTable(1)
            {
                TotalWidth = _totalWidth,
                LockedWidth = true,
                SpacingBefore = _spacingBefore,
                SpacingAfter = _spacingAfter
            };

            float[] widths = { 272f };

            pdfPTable.SetWidths(widths);

            var image = Image.GetInstance(HttpContext.Current.Server.MapPath("/Images/logo.png"));
            image.ScaleToFit(125f, 125f);
            image.Alignment = Image.RIGHT_ALIGN;

            var pdfPCell = new PdfPCell(image)
            {
                Border = 0,
                HorizontalAlignment = Element.ALIGN_RIGHT
            };

            pdfPTable.AddCell(pdfPCell);

            document.Add(pdfPTable);
        }

        dynamicPdfBytes = dynamicPDfMemoryStream.ToArray();
    }

    byte[] pdfBytes;

    using (var pdfReader = new PdfReader(HttpContext.Current.Server.MapPath("/Documents/Test.pdf")))
    {
        using (var pdfMemoryStream = new MemoryStream())
        {
            var pdfStamper = new PdfStamper(pdfReader, pdfMemoryStream);

            var acroFields = pdfStamper.AcroFields;
            acroFields.SetField("TestField", "This is a test");
            pdfStamper.FormFlattening = true;
            pdfStamper.Close();

            pdfBytes = pdfMemoryStream.ToArray();
        }
    }

    var files = new List<byte[]> { dynamicPdfBytes, pdfBytes };

    byte[] array;

    using (var arrayMemoryStream = new MemoryStream())
    {
        var document = new Document(PageSize.A4, 25, 25, 30, 30);

        var pdfWriter = PdfWriter.GetInstance(document, arrayMemoryStream);

        document.Open();

        var directContent = pdfWriter.DirectContent;

        foreach (var bytes in files)
        {
            var pdfReader = new PdfReader(bytes);

            var numberOfPages = pdfReader.NumberOfPages;

            for (var i = 1; i <= numberOfPages; i++)
            {
                document.NewPage();

                var page = pdfWriter.GetImportedPage(pdfReader, i);

                directContent.AddTemplate(page, 0, 0);
            }
        }

        document.Close();

        array = arrayMemoryStream.ToArray();
    }

    var memoryStream = new MemoryStream();
    memoryStream.Write(array, 0, array.Length);
    memoryStream.Position = 0;

    return memoryStream;
}


来源:https://stackoverflow.com/questions/50170423/c-sharp-append-pdf-file-to-memorystream-cannot-access-a-closed-stream

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