C# iTextSharp Merge multiple pdf via byte array

后端 未结 1 1899
予麋鹿
予麋鹿 2020-12-17 02:57

I am new to using iTextSharp and working with Pdf files in general, but I think I\'m on the right track.

I iterate through a list of pdf files, convert them to byt

相关标签:
1条回答
  • 2020-12-17 03:20

    This is pretty much just a C# version of Bruno's code here.

    This is pretty much the simplest, safest and recommended way to merge PDF files. The PdfSmartCopy object is able to detect redundancies in the multiple files which can reduce file size some times. One of the overloads on it accepts a full PdfReader object which can be instantiated however you want.

    public static byte[] concatAndAddContent(List<byte[]> pdfByteContent) {
    
        using (var ms = new MemoryStream()) {
            using (var doc = new Document()) {
                using (var copy = new PdfSmartCopy(doc, ms)) {
                    doc.Open();
    
                    //Loop through each byte array
                    foreach (var p in pdfByteContent) {
    
                        //Create a PdfReader bound to that byte array
                        using (var reader = new PdfReader(p)) {
    
                            //Add the entire document instead of page-by-page
                            copy.AddDocument(reader);
                        }
                    }
    
                    doc.Close();
                }
            }
    
            //Return just before disposing
            return ms.ToArray();
        }
    }
    
    0 讨论(0)
提交回复
热议问题