Merging Memory Streams to create a http PDF response in c#

后端 未结 1 1926
花落未央
花落未央 2021-01-05 06:57

I am trying to merge 2 crystal reports into single pdf file and I\'m using Itextsharp v5.1.1. But it says the document cannot be opened. It might be corrupted. There are no

相关标签:
1条回答
  • 2021-01-05 07:21

    Here's a simple merge method that copies PDF files into one PDF. I use this method quite often when merging pdfs. Hope it helps.

        public MemoryStream MergePdfForms(List<byte[]> files)
        {
            if (files.Count > 1)
            {
                PdfReader pdfFile;
                Document doc;
                PdfWriter pCopy;
                MemoryStream msOutput = new MemoryStream();
    
                pdfFile = new PdfReader(files[0]);
    
                doc = new Document();
                pCopy = new PdfSmartCopy(doc, msOutput);
    
                doc.Open();
    
                for (int k = 0; k < files.Count; k++)
                {
                    pdfFile = new PdfReader(files[k]);
                    for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)
                    {
                        ((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));
                    }
                    pCopy.FreeReader(pdfFile);
                }
    
                pdfFile.Close();
                pCopy.Close();
                doc.Close();
    
                return msOutput;
            }
            else if (files.Count == 1)
            {
                return new MemoryStream(files[0]);
            }
    
            return null;
        }
    

    Step 4 try:

            rptCS.Close();
            rptCS.Dispose();
            rptAd.Close();
            rptAd.Dispose();
    
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", 
        "attachment; filename=" + 
        "Application of " + FullName.Trim() + ".pdf");
            Response.BinaryWrite(ms.ToArray());
            ApplicationInstance.CompleteRequest();
    
    0 讨论(0)
提交回复
热议问题