在合并PDF时,第二个字节[]会覆盖第一个字节[]

时间:2017-09-18 21:35:47

标签: c# arrays asp.net-mvc-4 pdf itext

我已生成两个PDF字节数组,并将这两个数组合并为一个字节数组。现在,当我通过Controller中的byte[]呈现PDF时,它仅为Combine()方法中传递的第二个public ActionResult ShowPdf(string id1, string id2) { byte[] pdfBytes1 = CreatePdf1(id1); byte[] pdfBytes2 = CreatePdf2(id2); byte[] combinedPdfData = Combine(pdfBytes1, pdfBytes2); return File(combinedPdfData, "application/pdf"); } 生成PDF。 例如: 1)

pdfBytes2

如果我编写上面的代码,它只使用pdfBytes1数组数据生成PDF,并覆盖 public ActionResult ShowPdf(string id1, string id2) { byte[] pdfBytes1 = CreatePdf1(id1); byte[] pdfBytes2 = CreatePdf2(id2); byte[] combinedPdfData = Combine(pdfBytes2, pdfBytes1); return File(combinedPdfData, "application/pdf"); } 数组数据。

2)现在如果改变顺序并写下:

pdfBytes1

此方法仅使用public static byte[] Combine(byte[] first, byte[] second) { byte[] ret = new byte[first.Length + second.Length]; Buffer.BlockCopy(first, 0, ret, 0, first.Length); Buffer.BlockCopy(second, 0, ret, first.Length, second.Length); return ret; } 数组数据生成PDF。

我的Combine()方法代码是:

combinedPdfData

调试时我可以看到pdfBytes1[] + pdfBytes2[]数组包含总字节数。 ... foreach (var file in directory.GetFiles("*")) { fileCount++; Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}"); System.IO.StreamReader file = new System.IO.StreamReader(filepath + @"\" + file.ToString()); while(!file.EndOfStream) { int passwordBatchCount = 0; List<Password> entitysBatch = new List<Password>(); while ((string line = file.ReadLine()) != null && passwordBatchCount < BATCH_SIZE) { entitysBatch.Add(new Password { password = line }); passwordBatchCount++; } collection.InsertManyAsync(entitysBatch); } file.Close(); } } ... 但在打印时只打印一个数组的数据。请告诉我我在哪里做错了。

2 个答案:

答案 0 :(得分:2)

您认为可以通过连接字节来连接两个pdf文件,这是错误的。

您需要使用pdf创作库来读取这两个旧文档并将它们合并到一个新文档中。

答案 1 :(得分:2)

您不能连接2个PDF字节数组,并期望结果是有效的PDF文档。您需要一个库来创建一个新的PDF(output),并将原始PDF连接到一个新的有效PDF中。

在iText 5(旧版iText)中,代码如下所示:

Document doc = new Document();
PdfCopy copy = new PdfCopy(document, output);
document.Open();
PdfReader reader1 = new PdfReader(pdfBytes1);
copy.AddDocument(reader1);
PdfReader reader2 = new PdfReader(pdfBytes2);
copy.AddDocument(reader2);
reader1.Close();
reader2.Close();
document.Close(); 

在iText 7(iText的新版本;推荐)中,代码如下所示:

PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
merger.Merge(firstSourcePdf, 1, firstSourcePdf.GetNumberOfPages());
//Add pages from the second pdf document
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.Merge(secondSourcePdf, 1, secondSourcePdf.GetNumberOfPages());
firstSourcePdf.Close();
secondSourcePdf.Close();
pdf.Close();
相关问题