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.
Using pdf As New PdfDocument
Dim info As WorkerParameters = DirectCast(e.Argument, WorkerParameters)
Dim allFiles = Directory.GetFiles(info.InputDirectory, "*.*", SearchOption.TopDirectoryOnly)
Dim findMatch = Function(filePath As String)
Return filePath.ToLower.EndsWith(".png") Or _
filePath.ToLower.EndsWith(".bmp") Or _
filePath.ToLower.EndsWith(".jpg") Or _
filePath.ToLower.EndsWith(".gif")
End Function
Dim filesToProcess = Array.FindAll(Of String)(allFiles, findMatch)
Dim fileCount As Integer = filesToProcess.Length - 1
For i As Integer = 0 To fileCount
If bwMakePdf.CancellationPending Then
Exit For
End If
Dim page = pdf.AddPage()
Using xImg = PdfSharp.Drawing.XImage.FromFile(filesToProcess(i))
page.Width = xImg.PixelWidth * 72 / xImg.HorizontalResolution
page.Height = xImg.PixelHeight * 72 / xImg.HorizontalResolution
Dim GR = PdfSharp.Drawing.XGraphics.FromPdfPage(page)
GR.DrawImage(xImg, 0, 0, page.Width, page.Height)
End Using
bwMakePdf.ReportProgress((i / fileCount) * 100)
Next
Erase filesToProcess
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