How to Convert Image to PDF in ASP.NET Core

Converting images to PDFs is critical in a wide variety of contexts in our day-to-day lives. In order to archive legal, medical, industrial, and academic documents, scanned images are converted into PDF documents. Images are converted to PDF documents and digitally signed to ensure their originality and fidelity. This type of conversion is also used for processing optical character recognition.

The Syncfusion PDF library has extended support to convert images to PDFs for the ASP.NET Core platform. In this blog, I am going to walk you through this feature, covering the following details:

Converting PNG and JPEG images to PDF

To convert PNG and JPEG images to PDF, create and set up an ASP.NET Core project and refer the project to the Syncfusion PDF assemblies on NuGet.

Add the following code in Index.cshtml to select multiple images.

<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="ConvertToPDF">
    <div class="form-group">
        <div class="col-md-10">
            <p><h4>Select one or more images:</h4></p>
            <input type="file" name="files" multiple accept="image/*">
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-10">
            <br />
            <input type="submit" value="Convert to PDF">
        </div>
    </div>
</form>

This markup renders in a browser as shown in the following figure.Selecting Images for Conversion

Selecting Images for Conversion

Add a new action method ConvertToPDF in HomeContoller.cs as provided in the following code snippet.

[HttpPost]
public IActionResult ConvertToPDF(IList files)
{
    //Creating the new PDF document
    PdfDocument document = new PdfDocument();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            MemoryStream file = new MemoryStream();
            formFile.CopyTo(file);
            //Loading the image
            PdfImage image = PdfImage.FromStream(file);
            //Adding new page
            PdfPage page = page = document.Pages.Add();

            //Drawing image to the PDF page
            page.Graphics.DrawImage(image, new PointF(0, 0));
            file.Dispose();
        }
    }
    //Saving the PDF to the MemoryStream
    MemoryStream stream = new MemoryStream();

    document.Save(stream);

    //Set the position as '0'.
    stream.Position = 0;

    //Download the PDF document in the browser
    FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");

    fileStreamResult.FileDownloadName = "ImageToPDF.pdf";

    return fileStreamResult;
}

By executing this example, you will get the PDF document shown in the following image.Image Converted to PDF

Image Converted to PDF

Converting multi-frame TIFF images to PDF

TIFF images usually have multiple frames in a single file. To draw each frame in a page of a PDF document, you need to iterate each frame individually.

To handle TIFF images, add a reference to Syncfusion.Pdf.Imaging.Net.Core NuGet package in your .NET Core project.

The following code sample draws a multi-frame TIFF image to a PDF document.

if (formFile.ContentType == "image/tiff")
{
    //Get the image stream and draw frame by frame
    PdfTiffImage tiffImage = new PdfTiffImage(file);

    int frameCount = tiffImage.FrameCount;
    for (int i = 0; i < frameCount; i++)
    {
        //Add pages to the document
        var page = document.Pages.Add();
        //Getting page size to fit the image within the page
        SizeF pageSize = page.GetClientSize();
        //Selecting frame in TIFF
        tiffImage.ActiveFrame = i;
        //Draw TIFF frame
        page.Graphics.DrawImage(tiffImage, 0, 0, pageSize.Width, pageSize.Height);
   }
}

By executing this example, you will get the PDF document shown in the following image.Multi-frame TIFF Image Converted to PDF

Multi-frame TIFF Image Converted to PDF

Changing the PDF page size to match the image size

The default size of a page in a PDF document is A4 (210 × 297 mm). You can set a custom size for a PDF document using the PageSettings property of PdfDocument. Here we are going to set the page size to be the same as the image size.

//Creating the new PDF document
PdfDocument document = new PdfDocument();

//Setting page margin to 0
document.PageSettings.Margins.All = 0;

foreach (var formFile in files)
{
    if (formFile.Length > 0)
    {
        MemoryStream file = new MemoryStream();
        formFile.CopyTo(file);

        //Loading the image
        PdfImage image = PdfImage.FromStream(file);
        //Setting same page size as image
        PdfSection section = document.Sections.Add();
        section.PageSettings.Width = image.PhysicalDimension.Width;
        section.PageSettings.Height = image.PhysicalDimension.Height;
        PdfPage page = section.Pages.Add();

        //Drawing image to the PDF page
        page.Graphics.DrawImage(image, new PointF(0, 0),new SizeF(page.Size.Width,page.Size.Height));

        file.Dispose();
    }
}
//Saving the PDF to the MemoryStream
MemoryStream stream = new MemoryStream();

document.Save(stream);

//Set the position as '0'.
stream.Position = 0;

//Download the PDF document in the browser
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");

fileStreamResult.FileDownloadName = "ImageToPDF.pdf";

return fileStreamResult;

By executing this code, you will get the PDF document shown in the following image.PDF Document Size with Same Size as Original Image

PDF Document Size with Same Size as Original Image

Applying transparency and rotation to images

You can add transparency and rotation to images using the SetTransparency and RotateTransform methods of PdfGraphics.

This is illustrated in the following code example.

//Loading the image
PdfImage image = PdfImage.FromStream(file);
//Adding new page
PdfPage page = page = document.Pages.Add();

//Apply transparency
page.Graphics.SetTransparency(0.5f);

//Rotate the coordinate system
page.Graphics.RotateTransform(-45);
//Drawing image to the PDF page
page.Graphics.DrawImage(image, new PointF(0, 0));

Conclusion

As you can see, the Syncfusion .NET Core PDF library provides an easy way to convert JPEG, PNG, and multi-frame TIFF images to PDF documents. With this, you can provide image-to-PDF conversion as an ASP.NET Core web service or web application.

Please check out the sample in this GitHub repository for a hands-on experience of the image-to-PDF conversion feature. Also, take a moment to peruse the documentation, where you’ll find other options and features, all with accompanying code examples.

If you have any questions or require clarifications about these features, please let us know in the comments section below. You can also contact us through our support forum, Direct-Trac, or Feedback Portal. We are happy to assist you!

Tags:

Share this post:

Related Posts

Leave a comment