[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2012-09-04
7
Medium Priority
?
1,628 Views
Last Modified: 2012-09-12
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.
MergeFiles.txt
0
Comment
Question by:Angel02
  • 3
  • 2
  • 2
7 Comments
 
LVL 2

Expert Comment

by:kristof1104
ID: 38365643
Maybe you can try this:
http://www.codeproject.com/Articles/28283/Simple-NET-PDF-Merger

Regards Kristof
0
 

Author Comment

by:Angel02
ID: 38365745
I tried to convert this code into VB.NET using my regular link
http://www.developerfusion.com/tools/convert/csharp-to-vb/

But it does not successfully convert. Can you please provide VB.NET code?
0
 
LVL 2

Expert Comment

by:kristof1104
ID: 38365756
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:Angel02
ID: 38365790
Is spire.PDF free to download? It looks like it needs to be purchased.
I was looking for code using itextsharp.
0
 
LVL 2

Assisted Solution

by:kristof1104
kristof1104 earned 400 total points
ID: 38365831
0
 
LVL 26

Expert Comment

by:Alan Warren
ID: 38366694
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
0
 
LVL 26

Accepted Solution

by:
Alan Warren earned 1600 total points
ID: 38366945
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>"
      Response.Write(s)
    End If
    
    
    
  End Sub
</script>

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

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))
      reader.ConsolidateNamedDestinations()
      numPagesCurrentPDF = reader.NumberOfPages
      bookmarks = SimpleBookmark.GetBookmark(reader)

      If (bookmarks IsNot Nothing) Then
        If (pageOffset <> 0) Then SimpleBookmark.ShiftPageNumbers(bookmarks, pageOffset, Nothing)
        master.AddRange(bookmarks)
      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
          outputPDFDocument.Open()
        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)
          pdfWriter.AddPage(page)
        End If
      Next
      
      formContent = reader.AcroForm
      If (formContent IsNot Nothing And pdfWriter IsNot Nothing) Then
        pdfWriter.CopyAcroForm(reader)
        SourceFilesCount += 1
        If (master.Count > 0 And pdfWriter IsNot Nothing) Then
          ' huh?
        End If
        pdfWriter.Outlines = master

      End If

    Next

    ' step 5: we close the document
    If (outputPDFDocument IsNot Nothing) Then
      outputPDFDocument.Close()
      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

Alan
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Integration Management Part 2
Suggested Courses
Course of the Month19 days, 13 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question