Create PDF from Images in C#

In different cases, you may need to create a PDF based on a bunch of images, such as generating PDF from scanned document pages or invoices. For such scenarios, this article covers how to create PDF from the images programmatically using C#.

C# API to Create PDF from Images

For creating the PDF files from images, we’ll use Aspose.PDF for .NET. It is a powerful PDF API that lets you create, modify, and convert PDF files from within your .NET applications. You can either download the API or install it using NuGet.

PM> Install-Package Aspose.Pdf

Steps to Create a PDF File from Images

The following are the steps to create PDF from the images using Aspose.PDF for .NET.

  • First, create a new PDF document.
  • Get the list of the image files’ names in an array.
  • For each image in the list, do the following:
    • Add a new page to the PDF document and set its properties.
    • Load each image file from the list.
    • Add image to the paragraph collection of the page.
  • Finally, save the PDF document.

Create PDF from Images using C#

The following are the steps along with API references to create PDF from images.

The following code sample shows how to create a PDF from images.

// Create a new document
Document doc = new Document();
// Access image files in the folder
string[] fileList = Directory.GetFiles(@"D:/images/");
foreach (String file in fileList)
{
// Add a page to pages collection of document
var page = doc.Pages.Add();
// Load image into stream
FileStream imageStream = new FileStream(file, FileMode.Open);
// Set margins so image will fit, etc.
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Left = 0;
page.PageInfo.Margin.Right = 0;
page.CropBox = new Rectangle(0, 0, 400, 400);
// Create an image object
Image image1 = new Image();
// Add the image into paragraphs collection of the section
page.Paragraphs.Add(image1);
// Set the image file stream
image1.ImageStream = imageStream;
}
// Save resultant PDF file
doc.Save("document.pdf");

Get a Free API License

You can try the API without evaluation limitations by getting a free temporary license.

Conclusion

In this article, you have learned how to create PDF files from images using C#. The step-by-step guide and code sample have shown how to insert each image in a folder to a page in a PDF file. You can explore more about Aspose.PDF for .NET using documentation. In case you would have any queries, feel free to let us know via our forum.

See Also