• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2165
  • Last Modified:

Merge 2 or more PDF documents into one using VB.NET

I am using the attached code that I found

Open in new window

on one of the tech sites to Merge 2 or more PDF documents. But the result document is getting corrupted for some reason. My source PDF files and fine. I have tested them. But once this Merge function is called, the combined PDF is getting corrupted. Please advise.
  • 3
  • 2
  • 2
2 Solutions
Maybe you can try this:

Regards Kristof
Angel02Author Commented:
I tried to convert this code into VB.NET using my regular link

But it does not successfully convert. Can you please provide VB.NET code?
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Angel02Author Commented:
Is spire.PDF free to download? It looks like it needs to be purchased.
I was looking for code using itextsharp.
Alan WarrenApplications DeveloperCommented:
Getting a few issues with this line:
While (i < numPagesCurrentPDF) i += 1 If (pdfWriter IsNot Nothing) Then Dim page As PdfImportedPage = pdfWriter.GetImportedPage(reader, i) pdfWriter.AddPage(page) End If End While Dim formContent As PRAcroForm = reader.AcroForm If (formContent IsNot Nothing And pdfWriter IsNot Nothing) Then pdfWriter.CopyAcroForm(reader) FileNum += 1 If (master.Count > 0 And pdfWriter IsNot Nothing) Then pdfWriter.Outlines = master

Open in new window

        pdfWriter.Outlines = master

        ' missing end if here

Open in new window

Alan WarrenApplications DeveloperCommented:
Hi Angel02,
Got it working on my localhost, not tried it on production yet.
Had to modify the code a bit, anyhow, take a look:
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    'Destination file name
    Dim TimeStamp As String = DateAndTime.Now.ToString
    TimeStamp = TimeStamp.Replace("/", "")
    TimeStamp = TimeStamp.Replace(" ", "")
    TimeStamp = TimeStamp.Replace(":", "")
    Dim destinationFile As String = Server.MapPath("~/the-files-folder/") & TimeStamp & ".pdf"
    'Source file name 1
    Dim SourceFile1 As String = Server.MapPath("~/the-files-folder/Document1.pdf")

    'Source file name 2
    Dim SourceFile2 As String = Server.MapPath("~/the-files-folder/Document2.pdf")
    Dim sourceFiles() As String = {SourceFile1, SourceFile2}
    Dim ret As Boolean = False
    ret = pdfmerge.MergeFiles(destinationFile, sourceFiles)
    If ret = True Then
      Dim s As String = "<iframe id='pdf-merge-preview' frameborder='0' height='800px' src='./the-files-folder/" & TimeStamp & ".pdf' width='800px'></iframe>"
    End If
  End Sub

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">

Open in new window

And the Class:
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Public Class pdfmerge

  Public Shared Function MergeFiles(ByVal destinationFile As String, ByVal sourceFiles() As String) As Boolean
    Dim pageOffset As Integer = 0
    Dim master As ArrayList = New ArrayList()
    Dim FileNum As Integer = 0
    Dim outputPDFDocument As Document = Nothing
    Dim pdfWriter As PdfCopy = Nothing
    Dim blResult As Boolean = False
    Dim reader As PdfReader = Nothing
    Dim numPagesCurrentPDF As Integer = 0
    Dim bookmarks As ArrayList = New ArrayList()
    Dim page As PdfImportedPage = Nothing
    Dim formContent As PRAcroForm = Nothing

    Dim SourceFilesCount As Integer = 0
    Dim PagesToAdd As Integer = 0

    For SourceFilesCount = 0 To sourceFiles.Length - 1
      reader = New PdfReader(sourceFiles(SourceFilesCount))
      numPagesCurrentPDF = reader.NumberOfPages
      bookmarks = SimpleBookmark.GetBookmark(reader)

      If (bookmarks IsNot Nothing) Then
        If (pageOffset <> 0) Then SimpleBookmark.ShiftPageNumbers(bookmarks, pageOffset, Nothing)
      End If

      pageOffset += numPagesCurrentPDF

      If (SourceFilesCount = 0) Then

        ' step 1: creation of a document-object
        outputPDFDocument = New Document(reader.GetPageSizeWithRotation(1))

        ' step 2: we create a writer that listens to the document
        ' Encountered Exception: System.UnauthorizedAccessException was unhandled by user code
        ' Gave iis_iusrs full control of the ~/the-files-folder/ folder, bit over the top, but sure to suffice

        ' second time though the loop
        ' encountered error: The process cannot access the file 'C:\inetpub\wwwroot\session-test\the-files-folder\output.pdf' because it is being used by another process.
        ' Modified script to only open the pdfWriter the first time through the loop

        If pdfWriter Is Nothing Then
          pdfWriter = New PdfCopy(outputPDFDocument, New FileStream(destinationFile, FileMode.Create))

          ' step 3: we open the output document
        End If

      End If

      ' step 4: we add pages to the output file
      For PagesToAdd = 1 To numPagesCurrentPDF
        If (pdfWriter IsNot Nothing) Then
          page = pdfWriter.GetImportedPage(reader, PagesToAdd)
        End If
      formContent = reader.AcroForm
      If (formContent IsNot Nothing And pdfWriter IsNot Nothing) Then
        SourceFilesCount += 1
        If (master.Count > 0 And pdfWriter IsNot Nothing) Then
          ' huh?
        End If
        pdfWriter.Outlines = master

      End If


    ' step 5: we close the document
    If (outputPDFDocument IsNot Nothing) Then
      blResult = True
    End If

    Return blResult

  End Function

  Private Function CountPageNo(ByVal strFileName As String) As Integer
    ' we create a reader for a certain document
    Dim reader As PdfReader = New PdfReader(strFileName)
    ' we retrieve the total number of pages
    Return reader.NumberOfPages
  End Function
End Class

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now