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

1

2

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>

Sunwise answered 19/1, 2023 at 6:47 Comment(0)
S
2

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.

Required NuGet packages:

  1. https://www.nuget.org/packages/itext7

    If you install version less than 8.0 than you also need below package, otherwise you don't need it. https://www.nuget.org/packages/itext7.bouncy-castle-adapter

  2. https://www.nuget.org/packages/Magick.NET-Q16-AnyCPU

===========================================================

public ActionResult MergeClientFilesIntoSinglePdf([FromForm] List<IFormFile> files)
    {
        if (files.Count > 0)
        {
            var writerMemoryStream = CreateMergeMultipleFiles(files);

            return File(writerMemoryStream.ToArray(), "application/pdf", "merged_file.pdf");
        }
        else
        {
            var responseData = new ApiResponseSuccess<Dictionary<string, string>>
            {
                data = null,
                status = "Error",
                statusCode = StatusCodes.Status204NoContent,
                message = "No File Found!"
            };

            return Ok(responseData);
        }
    }




private readonly List<string> _supportedImgExtensions = new() { "jpg", "jpeg", "png", "gif", "tif", "tiff", "svg", "bmp", "webp" };

private MemoryStream CreateMergeMultipleFiles(List<IFormFile> files)
    {
        try
        {
            using var writerMemoryStream = new MemoryStream();
            using var writer = new PdfWriter(writerMemoryStream);
            using var mergedDocument = new PdfDocument(writer);
            using var document = new Document(mergedDocument);

            var merger = new PdfMerger(mergedDocument);
            var imageExtensions = new HashSet<string>(_supportedImgExtensions, StringComparer.OrdinalIgnoreCase);

            files.ForEach(file =>
            {
                string inputFileExtension = Path.GetExtension(file.FileName).ToLower().Trim('.');
                using var fileStream = file.OpenReadStream();

                if (inputFileExtension == "pdf")
                {
                    using var reader = new PdfReader(fileStream);
                    reader.SetUnethicalReading(true);   // Obsolete the permissions by owner

                    using var copyFromDocument = new PdfDocument(reader);

                    merger.Merge(copyFromDocument, 1, copyFromDocument.GetNumberOfPages());
                }
                else if (imageExtensions.Contains(inputFileExtension))
                {
                    using var magickImage = new MagickImage(fileStream);
                    magickImage.Format = MagickFormat.Jpeg;
                    magickImage.Quality = 20;   // Images resolution adjusted

                    var image = new Image(ImageDataFactory.Create(magickImage.ToByteArray()));
                    image.SetWidth(mergedDocument.GetDefaultPageSize().GetWidth() - 50);
                    image.SetAutoScaleHeight(true);

                    if (mergedDocument.GetNumberOfPages() > 0)  // Add page break after the first image
                    {
                        document.Add(new AreaBreak(AreaBreakType.LAST_PAGE));
                        document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
                    }

                    document.Add(image);
                }
            });

            return writerMemoryStream;
        }
        catch
        {
            throw;
        }
    }
Sunwise answered 19/1, 2023 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.