利用ITextSharp進行多個PDF文件流的合併

  • 1869
  • 0

轉載自闲云博客    個人學習紀錄

請引用iTextSharp的dll和namespace

public static byte[] MergePdfFiles(List<byte[]> pdfInputs)
      {
          using (MemoryStream stream = new MemoryStream())
          {
              Document document = new Document();
              PdfWriter writer = PdfWriter.GetInstance(document, stream);
              document.Open();
              PdfContentByte cb = writer.DirectContent;
              PdfImportedPage newPage;
              PdfReader reader;
              foreach (var p in pdfInputs)
              {
                  reader = new PdfReader(p);
                  int iPageNum = reader.NumberOfPages;
                  for (int i = 1; i <= iPageNum; i++)
                  {
                      document.NewPage();
                      newPage = writer.GetImportedPage(reader, i);
                      cb.AddTemplate(newPage, 0, 0);
                  }
              }
              document.Close();
              writer.Close();
              return stream.ToArray();
          }
      }

代碼,清晰不解釋