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

Second Byte[] overwrites first Byte[] while merging the PDF

我生成了两个 PDF 字节数组并将这两个数组合并为一个字节数组。现在,当我在 Controller 中通过 ActionMethod 呈现 PDF 时,它仅为 Combine() 方法中传递的第二个 byte[] 生成 PDF。 例如: 1)

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");
        }

如果我写上面的代码,它只用 pdfBytes2 数组数据生成 PDF 并且 pdfBytes1 数组数据被覆盖。

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

 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");
        }

此方法仅使用 pdfBytes1 数组数据生成 PDF。

我的 Combine() 方法代码是:

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;
        }

调试时我可以看到 combinedPdfData 数组包含总字节数,即。 pdfBytes1[] + pdfBytes2[] 但是在打印时它只打印一个数组的数据。请让我知道我哪里做错了。

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

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

您不能只连接 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();