我使用此方法合并现有的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;
}
}
答案 0 :(得分:4)
在byte[]
中有一个允许连接的LINQ方法。
a.Concat(b).ToArray();
您必须先添加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;
}