Click here to Skip to main content
15,885,915 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Create PDF from Images using VB.NET

Rate me:
Please Sign up or sign in to vote.
4.75/5 (7 votes)
24 May 2015CC (ASA 3U)2 min read 47.2K   6K   11   4
Create PDF from Image files using VB.NET and PDFSharp library.

Introduction

Hello! This is my first article on Codeproject. I hope you will enjoy this tip. In this tip, I will show you how to convert images to PDF document. Of course, because we're converting from images, the PDF document will not be editable.

Background

I'm a Naruto fan, and I want to download all of the Naruto manga to my PC. Because this manga started from 1997 and I just like Naruto since 2014, I realized that the number of Naruto manga is already a lot. So I started downloading from the first chapter. It was 20 pages and an image file.

I tried many online services to convert images to PDF, but it was limited to 40 pages only. So I started to write my own PDF creator. I have found many apps to do this, but I was interested in creating my own.

Using the Code

Code walkthrough:

  • Create a new blank PDF document.
  • Find all files on a specified directory.
  • Move supported image file paths to new array.
  • On the For...Next loop, add new PDF page with image as the content.
  • Save the PDF document to file.

First, you must create new Windows Forms Application. I'm using .NET Framework 2.0 for maximum compatibility.

Add controls like this:

Also, I added SaveFileDialog, FolderBrowseDialog, and BackgroundWorker.

Second, add reference to PDFSharp library. You can add it from Nuget Package or download it from official website.

Third, this is the core of code. I put this code in bwMakePDF_DoWork event handler.

VB.NET
Using pdf As New PdfDocument
    'Get parameter to process PDF.
    Dim info As WorkerParameters = DirectCast(e.Argument, WorkerParameters)

    'Find all files on source directory (sub-directories not included).
    Dim allFiles = Directory.GetFiles(info.InputDirectory, "*.*", SearchOption.TopDirectoryOnly)

    'Function to find compatible file types.
    'In .NET 4.0, you can use LINQ to do this.
    Dim findMatch = Function(filePath As String)
                        'PDFSharp only supports PNG, BMP, JPG, and GIF.
                        Return filePath.ToLower.EndsWith(".png") Or _
                               filePath.ToLower.EndsWith(".bmp") Or _
                               filePath.ToLower.EndsWith(".jpg") Or _
                               filePath.ToLower.EndsWith(".gif")
                    End Function

    'Find entire array.
    Dim filesToProcess = Array.FindAll(Of String)(allFiles, findMatch)

    'Get file count.
    Dim fileCount As Integer = filesToProcess.Length - 1

    'Add PDF pages.
    For i As Integer = 0 To fileCount
        'Check if operation is cancelled.
        If bwMakePdf.CancellationPending Then
            Exit For
        End If

        'Create new PDF page.
        Dim page = pdf.AddPage()

        'Create XImage object from file.
        Using xImg = PdfSharp.Drawing.XImage.FromFile(filesToProcess(i))
            'Resize page Width and Height to fit image size.
            page.Width = xImg.PixelWidth * 72 / xImg.HorizontalResolution
            page.Height = xImg.PixelHeight * 72 / xImg.HorizontalResolution

            'Draw current image file to page.
            Dim GR = PdfSharp.Drawing.XGraphics.FromPdfPage(page)
            GR.DrawImage(xImg, 0, 0, page.Width, page.Height)
        End Using

        'Report progress.
        bwMakePdf.ReportProgress((i / fileCount) * 100)
    Next

    'Erase all items in array. Memory leaking free...
    Erase filesToProcess

    'Save to PDF file.
    pdf.Save(info.OutputFile)
End Using

Don't forget to rename all controls on your form to fit the above code.

Points of Interest

No more using online services to convert images to PDF. No more using paid apps to create PDF. Just a little application to do this, without any limitation.

History

  • May 23rd, 2015: Initial post

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License


Written By
Software Developer Telkom Indonesia
Indonesia Indonesia
I'm a backend developer, working with .NET, NodeJS, Python

Comments and Discussions

 
QuestionDoes not understand exif data for orientation Pin
meesey10123-Jun-22 1:49
meesey10123-Jun-22 1:49 
PraiseThanks and appreciation Pin
Ali Al-Ali24-Sep-21 8:28
Ali Al-Ali24-Sep-21 8:28 
BugBUG when attach only one file Pin
netsistemas17-Sep-18 7:19
netsistemas17-Sep-18 7:19 
SuggestionVery Good... Pin
MayurDighe27-May-15 3:52
professionalMayurDighe27-May-15 3:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.