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

PDF Merge

Rate me:
Please Sign up or sign in to vote.
4.87/5 (40 votes)
26 Oct 2014CPOL 128.5K   9.5K   78  
This Windows application lets you merge image and PDF files in a given folder into one PDF file.
Imports iTextSharp.text.pdf
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        cbFileType.SelectedIndex = 0
    End Sub

    Private Sub btnFrom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFrom.Click
        fldFrom.ShowDialog()
        txtFrom.Text = fldFrom.SelectedPath
    End Sub

    Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click

        Dim sFromPath As String = txtFrom.Text
        If Not Directory.Exists(sFromPath) Then
            MsgBox("Folder does not exist")
            Exit Sub
        End If

        txtOutput.Text = ""
        txtOutput.Text += "Starting..." & vbCrLf
        ProccessFolder(sFromPath)
        txtOutput.Text += "Done!"
    End Sub

    Sub ProccessFolder(ByVal sFolderPath As String)

        btnProcess.Enabled = False
        txtOutput.Text += "Processing folder: " & sFolderPath & vbCrLf

        Dim oFolderInfo As New System.IO.DirectoryInfo(sFolderPath)
        Dim sOutFilePath As String = sFolderPath & "\" & oFolderInfo.Name & ".pdf"
        If IO.File.Exists(sOutFilePath) Then
            Try
                IO.File.Delete(sOutFilePath)
            Catch ex As Exception
                txtOutput.Text += sFolderPath & vbTab & ex.Message & vbCrLf
                'Exit Sub
            End Try
        End If

        Dim oFiles As String() = Directory.GetFiles(sFolderPath)
        ProgressBar1.Maximum = oFiles.Length

        Dim oPdfDoc As New iTextSharp.text.Document()
        Dim oPdfWriter As PdfWriter = PdfWriter.GetInstance(oPdfDoc, New FileStream(sOutFilePath, FileMode.Create))
        If txtPassword.Text <> "" Then
            oPdfWriter.SetEncryption(PdfWriter.STRENGTH40BITS, txtPassword.Text, txtPassword.Text, PdfWriter.AllowCopy)
        End If
        oPdfDoc.Open()

        For i As Integer = 0 To oFiles.Length - 1
            Dim sFromFilePath As String = oFiles(i)
            Dim oFileInfo As New FileInfo(sFromFilePath)
            Dim sFileType As String = cbFileType.SelectedItem
            Dim sExt As String = UCase(oFileInfo.Extension).Substring(1, 3)

            Try
                Select Case sFileType
                    Case "All"
                        If sExt = "PDF" Then
                            AddPdf(sFromFilePath, oPdfDoc, oPdfWriter)
                        ElseIf sExt = "JPG" Or sExt = "TIF" Then
                            AddImage(sFromFilePath, oPdfDoc, oPdfWriter)
                        End If

                    Case "PDF"
                        If sExt = "PDF" Then
                            AddPdf(sFromFilePath, oPdfDoc, oPdfWriter)
                        End If

                    Case "JPG", "TIF"
                        If sExt = "JPG" Or sExt = "TIF" Then
                            AddImage(sFromFilePath, oPdfDoc, oPdfWriter)
                        End If

                End Select

            Catch ex As Exception
                txtOutput.Text += sFromFilePath & vbTab & ex.Message & vbCrLf
            End Try

            ProgressBar1.Value = i
        Next

        Try
            oPdfDoc.Close()
            oPdfWriter.Close()
        Catch ex As Exception
            txtOutput.Text += ex.Message & vbCrLf
            Try
                IO.File.Delete(sOutFilePath)
            Catch ex2 As Exception
            End Try
        End Try

        btnProcess.Enabled = True
        ProgressBar1.Value = 0

        Dim oFolders As String() = Directory.GetDirectories(sFolderPath)
        For i As Integer = 0 To oFolders.Length - 1
            Dim sChildFolder As String = oFolders(i)
            Dim iPos As Integer = sChildFolder.LastIndexOf("\")
            Dim sFolderName As String = sChildFolder.Substring(iPos + 1)
            ProccessFolder(sChildFolder)
        Next

    End Sub

    Sub AddPdf(ByVal sInFilePath As String, ByRef oPdfDoc As iTextSharp.text.Document, ByVal oPdfWriter As PdfWriter)

        Dim oDirectContent As iTextSharp.text.pdf.PdfContentByte = oPdfWriter.DirectContent
        Dim oPdfReader As iTextSharp.text.pdf.PdfReader = New iTextSharp.text.pdf.PdfReader(sInFilePath)
        Dim iNumberOfPages As Integer = oPdfReader.NumberOfPages
        Dim iPage As Integer = 0

        Do While (iPage < iNumberOfPages)
            iPage += 1
            oPdfDoc.SetPageSize(oPdfReader.GetPageSizeWithRotation(iPage))
            oPdfDoc.NewPage()

            Dim oPdfImportedPage As iTextSharp.text.pdf.PdfImportedPage = oPdfWriter.GetImportedPage(oPdfReader, iPage)
            Dim iRotation As Integer = oPdfReader.GetPageRotation(iPage)
            If (iRotation = 90) Or (iRotation = 270) Then
                oDirectContent.AddTemplate(oPdfImportedPage, 0, -1.0F, 1.0F, 0, 0, oPdfReader.GetPageSizeWithRotation(iPage).Height)
            Else
                oDirectContent.AddTemplate(oPdfImportedPage, 1.0F, 0, 0, 1.0F, 0, 0)
            End If
        Loop

    End Sub

    Sub AddImage(ByVal sInFilePath As String, ByRef oPdfDoc As iTextSharp.text.Document, ByVal oPdfWriter As PdfWriter)
        Dim oImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(sInFilePath)
        Dim oDirectContent As iTextSharp.text.pdf.PdfContentByte = oPdfWriter.DirectContent

        Dim iWidth As Single = oImage.Width
        Dim iHeight As Single = oImage.Height

        oImage.SetAbsolutePosition(1, 1)
        oPdfDoc.SetPageSize(New iTextSharp.text.Rectangle(iWidth, iHeight))
        oPdfDoc.NewPage()
        oDirectContent.AddImage(oImage)
    End Sub

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Igor is a business intelligence consultant working in Tampa, Florida. He has a BS in Finance from University of South Carolina and Masters in Information Management System from University of South Florida. He also has following professional certifications: MCSD, MCDBA, MCAD.

Comments and Discussions