簡體   English   中英

如何串聯兩個字節數組

[英]How to concatenate two byte arrays

我使用這種方法合並現有的pdf文檔,並向其中添加新的pdf文檔(在內存中不是物理的)問題我有2個內存流,一個用於合並的pdf,一個到新文檔,然后將其轉換為字節數組,我想連接這些拖曳陣列

public static byte[] merge(List<String> pdf)
{
    MemoryStream copystream;
    MemoryStream ms;
    using (ms = new MemoryStream())
    {
        Document document;
        using (document = new Document())
        {
            using (PdfWriter wri = PdfWriter.GetInstance(document, ms))
            {
                wri.CloseStream = false;
                document.Open();
                document.SetPageSize(iTextSharp.text.PageSize.A4); // for vertical layout

                document.Add(new Paragraph("Hello"));

                document.Close();

                copystream = new MemoryStream();
                Document doc = new Document();
                using (PdfCopy copy = new PdfCopy(doc, copystream))
                {
                    copy.CloseStream = false;
                    copy.Open();
                    doc.Open();

                    // copy.AddPage(PageSize.A4, 0);
                    for (int i = 0; i < pdf.Count; ++i)
                    {
                        PdfReader reader = new PdfReader(pdf[i]);
                        // loop over the pages in that document
                        int n = reader.NumberOfPages;
                        for (int page = 0; page < n;)
                        {
                            copy.AddPage(copy.GetImportedPage(reader, ++page));
                        }
                    }

                    copy.Close();
                    copystream.CopyToAsync(ms);
                    copystream.Close();
                }
            }
        }

        byte[] mergedPdf2 = copystream.ToArray();
        byte[] mergedPdf3 = ms.ToArray();
        byte[] result = new byte[mergedPdf2.Length + mergedPdf3.Length];
        mergedPdf2.CopyTo(result, 0);
        mergedPdf3.CopyTo(result, mergedPdf2.Length);
        return result;
    }
}

byte[]有一個LINQ方法,允許串聯。

a.Concat(b).ToArray();

您必須using System.Linq;添加using System.Linq; 第一。 如果您不想這樣做,可以創建一個方法,例如:

 static byte[] Concat(byte[] a, byte[] b)
 {           
     byte[] output = new byte[a.Length + b.Length];
     for (int i = 0; i < a.Length; i++)
         output[i] = a[i];
     for (int j = 0; j < b.Length; j++)
         output[a.Length+j] = b[j];
     return output;           
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM