将内存流合并到一个 iText 文档 [英] Merge memorystreams to one iText document

查看:34
本文介绍了将内存流合并到一个 iText 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个 MemoryStreams 数据要合并,然后打开 pdfDocument,而不创建单个文件.

I have four MemoryStreams of data that I want to merge and then open the pdfDocument, without creating a single file.

可以将它们写到文件中,然后合并它们,但这将是不好的做法,而且还会导致一些问题,所以我想避免这种情况.

It's possible to write them down to files and then merge them but that would be bad practice and that can also cause a few issues so I want to avoid that.

但是,我找不到将 MemoryStreams 与 iText5 for .NET 合并的方法.

However, I can not find a way to merge the MemoryStreams with iText5 for .NET.

现在,我是这样处理文件的:

Right now, this is how I do it with files:

    private static void ConcatenateDocuments()
    {
        var stream = new MemoryStream();

        var readerFrontPage = new PdfReader(Folder + FrontPageName);
        var readerDocA = new PdfReader(Folder + docA);
        var readerDocB = new PdfReader(Folder + DocB);
        var readerAppendix = new PdfReader(Folder + Appendix);
        var pdfCopyFields = new PdfCopyFields(stream);

        pdfCopyFields.AddDocument(readerFrontPage);
        pdfCopyFields.AddDocument(readerDocA );
        pdfCopyFields.AddDocument(readerDocB);
        pdfCopyFields.AddDocument(readerAppendix);
        pdfCopyFields.Close();

        SavePdf(stream, FilenameReport);
    }

因为我需要删除文件的使用,所以我保留了 MemoryStream,因为不同的部分是从不同的资源构建的.所以我引用了这些内存流.

Since I need to remove the use of files, I keep the MemoryStream's as the different parts are built from different resources. So I have references to these memorystreams.

这是怎么做到的?

推荐答案

PDF header signature not found 在这种情况下可以通过设置流的 Position 来修复错误到 0.由于您没有收到错误 Cannot access a closed Stream 我假设您已经正确地将 PdfWriterCloseStream 设置为.

The error PDF header signature not found can be fixed in this case by setting the stream's Position back to 0. Since you're not getting the error Cannot access a closed Stream I'm assuming that you are already correctly setting the PdfWriter's CloseStream to false.

下面是一个面向 iTextSharp 5.1.1.0 的完整工作 C# 2010 WinForm 应用程序,它在 MemoryStreams 中创建三个 PDF 并将它们组合起来.由于我手边没有网络服务器,我将它们写入磁盘.

Below is a full working C# 2010 WinForm app targeting iTextSharp 5.1.1.0 that creates three PDFs in MemoryStreams and combines them. Since I don't have a web server handy I'm writing them to disk.

using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Create three MemoryStreams
            MemoryStream[] streams = { CreateDoc("Page 1"), CreateDoc("Page 2"), CreateDoc("Page 3") };

            //I don't have a web server handy so I'm going to write my final MemoryStream to a byte array and then to disk
            byte[] bytes;

            //Create our final combined MemoryStream
            using (MemoryStream finalStream = new MemoryStream())
            {
                //Create our copy object
                PdfCopyFields copy = new PdfCopyFields(finalStream);

                //Loop through each MemoryStream
                foreach (MemoryStream ms in streams)
                {
                    //Reset the position back to zero
                    ms.Position = 0;
                    //Add it to the copy object
                    copy.AddDocument(new PdfReader(ms));
                    //Clean up
                    ms.Dispose();
                }
                //Close the copy object
                copy.Close();

                //Get the raw bytes to save to disk
                bytes = finalStream.ToArray();
            }

            //Write out the file to the desktop
            string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Combined.pdf");
            using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                fs.Write(bytes, 0, bytes.Length);   
            }

            this.Close();
        }

        /// <summary>
        /// Helper method to create temporary documents
        /// </summary>
        private MemoryStream CreateDoc(string name)
        {
            MemoryStream ms = new MemoryStream();
            using (Document doc = new Document(PageSize.LETTER))
            {
                using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
                {
                    writer.CloseStream = false;
                    doc.Open();
                    doc.Add(new Paragraph(name));
                    doc.Close();
                }
            }
            return ms;
        }
    }
}

这篇关于将内存流合并到一个 iText 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆