简体   繁体   中英

How to MERGE both PDFs and Images via IText7 in C#/.NET Core

Scenario is user will send multiple files of combination of both pdf and images (.png, .jpg/jpeg etc.).

Files are received as parameter of type: List<IFormFile>

I've searched for this solution over various forms. However, haven't found clear way. Therefore, after R&D for some time, I did applied and constructs below method, hope will help you enough.

private async Task <ActionResult> MergeMultipleFileIntoASinglePdfAsync(List <IFormFile> files) {
  using(var writerMemoryStream = new MemoryStream()) {
    using(var writer = new PdfWriter(writerMemoryStream)) {
      using(var mergedDocument = new PdfDocument(writer)) {
        using(Document document = new Document(mergedDocument)) {
          for (int i = 0; i < files.Count; i++) {
            string inputFileExtension = System.IO.Path.GetExtension(files[i].FileName).ToLower().Trim('.');

            using var fileStream = files[i].OpenReadStream();
            byte[] fileByte = new byte[files[i].Length];
            await fileStream.ReadAsync(fileByte.AsMemory(0, (int) files[i].Length));

            if (inputFileExtension == "pdf") {
              var merger = new PdfMerger(mergedDocument);

              using(var copyFromMemoryStream = new MemoryStream(fileByte)) {
                using(var reader = new PdfReader(copyFromMemoryStream)) {
                  using(var copyFromDocument = new PdfDocument(reader)) {
                    merger.Merge(copyFromDocument, 1, copyFromDocument.GetNumberOfPages());
                  }
                }
              }
            } else if (inputFileExtension == "png" || inputFileExtension == "jpg" ||
              inputFileExtension == "jpeg" || inputFileExtension == "gif" ||
              inputFileExtension == "tiff") {
              image = new Image(ImageDataFactory.Create(fileByte));
              image.ScaleToFit(PageSize.A4.GetWidth(), PageSize.A4.GetHeight());
              image.SetFixedPosition(i + 1, 0, 30 f);

              document.SetMargins(0, 0, 0, 0);
              document.Add(image);
            } else {
              return StatusCode(StatusCodes.Status403Forbidden, "Format Unsupported!");
            }
          }
        }
      }
    }

    return File(writerMemoryStream.ToArray(), "application/pdf", "merged_file.pdf");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM