简体   繁体   中英

itextsharp merging pdfs an emailing

I am battling with some memorystream logic.

I have a method that receives a list of Id. uses them to pull pdfs from a webserver, and merges them into one pdf.

I want to then email this pdf (working in memory only)

private Stream GetWebReport(string selected_id)
    {          
        var IdLst = selected_id.Split(',').ToList();
        MemoryStream stream = new MemoryStream();
            Document document = new Document();
            PdfCopy pdf = new PdfCopy(document, stream);
            PdfReader reader = null;
            try
            {
                document.Open();


                    foreach (var id in IdLst)
                    {
                        int i = Convert.ToInt32(id);

                        string invoice_url = string.Concat("http://specialurl/", id);
                        var urlpdf = new System.Net.WebClient().OpenRead(invoice_url);
                        reader = new PdfReader(urlpdf);
                        pdf.AddDocument(reader);
                        reader.Close();
                    }


            }
            catch (Exception)
            {

                throw;
            }
            finally
            {

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

            return stream;              

    }

but when I try use the resulting stream for an email var mem = GetWebReport(selected_id);

            mem.Seek(0, SeekOrigin.Begin);
            Attachment att = new Attachment(mem, "Report for you", "application/pdf");

I get told:

System.ObjectDisposedException: 'Cannot access a closed Stream.' 

So I am sure that my itextsharp logic is good (When I use a filestream I get the correct results). I am sure that my logic in passing streams is what is faulty

Use

PdfCopy pdf = new PdfCopy(document, stream);
pdf.CloseStream = false;

This will keep the stream open after closing the pdf to be used elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM