Solved

Merging PDFs with VB.NET

Posted on 2016-10-20
10
40 Views
Last Modified: 2016-10-20
I am trying to append PDFs to a master PDF and my code is replacing the master PDF with the one I want to attached to it.  I need someone to look at my code and tell me what I'm doing wrong.

Many thanks!


Dim jfFile As String = "K:\ConfigMgmt\PDF\POAM\JSCForm\JF2016_10_20.pdf"

        Dim merged As Boolean = True

        Using Stream As New FileStream(jfFile, FileMode.Create)

            Dim document As New Document()
            Dim pdf As New PdfCopy(document, Stream)
            Dim reader As PdfReader = Nothing
            Try
                document.Open()

                Dim getPDF = (From id In d.tblPOAMdetails _
                             Where id.closedDate Is Nothing _
                             And id.nasacsspno = "XXXXX" _
                             Order By id.UPI Ascending _
                             Select id.poamLink).ToList

                For Each file As String In getPDF
                    reader = New PdfReader(file)
                    pdf.AddDocument(reader)
                    reader.Close()
                Next
            Catch generatedExceptionName As Exception
                merged = False
                If reader IsNot Nothing Then
                    reader.Close()
                End If
            Finally
                If document IsNot Nothing Then
                    document.Close()
                End If
            End Try
        End Using
0
Comment
Question by:Karen Wilson
  • 6
  • 4
10 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41852576
Hi Karen;

Try changing this line of code
Using Stream As New FileStream(jfFile, FileMode.Create)

Open in new window

to this
Using Stream As New FileStream(jfFile, FileMode.Append)

Open in new window

FileMode.Create over writes the original file.
0
 

Author Comment

by:Karen Wilson
ID: 41852608
The same thing happened.  I forgot to note that I had done that previously as well and reverted it back to create.
0
 

Author Comment

by:Karen Wilson
ID: 41852610
Also, the master PDF is in landscape while the attachments are in portrait.  Could that be causing a problem?
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41852647
Hi Karen;

I have looked at the code again and nothing else sticks out at me. What library are you using? If I can download it from NuGet I will try and test on my computer.
0
 

Author Comment

by:Karen Wilson
ID: 41852651
I am using iTextSharp.  I know, it's crazy!
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:Karen Wilson
ID: 41852654
Here is what I am importing as well.

Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.pdf.parser

Thanks for your help.
0
 

Author Comment

by:Karen Wilson
ID: 41852665
I can get this code to work.

Dim bytes As Byte() = File.ReadAllBytes("K:\ConfigMgmt\PDF\POAM\JSCForm\JF2016_10_20.pdf")

        Dim blackFont As Font = FontFactory.GetFont("Arial", 9, Font.Bold, BaseColor.BLACK)

        Using stream As New MemoryStream()

            Dim reader As New PdfReader(bytes)

            Using stamper As New PdfStamper(reader, stream)

                Dim pages As Integer = reader.NumberOfPages

                For i As Integer = 1 To pages
                    ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, New Phrase("JSC Form 1218 " & i.ToString(), blackFont), 568.0F, 15.0F, 0)
                Next

            End Using

            bytes = stream.ToArray()

        End Using

        File.WriteAllBytes("K:\ConfigMgmt\PDF\POAM\JSCForm\JF2016_10_20.pdf", bytes)
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 41852802
Hi Karen;

I tried to lookup the documentation on PdfCopy.AddDocument but it seems to be missing from there documentation. I have found a workaround. By inserting the main document into the list of PDF's to be copied from your query fixes the problem. I do not know if it is a problem or not because it may require an empty document to write to. I have commented two lines in your code for you to change/add.
'' Added _New to the end of the file name so that it creates an empty file wher to copy all the PDF files to.
Dim jfFile As String = "K:\ConfigMgmt\PDF\POAM\JSCForm\JF2016_10_20_New.pdf"

Dim merged As Boolean = True

Using Stream As New FileStream(jfFile, FileMode.Create)

    Dim document As New Document()
    Dim pdf As New PdfCopy(document, Stream)
    Dim reader As PdfReader = Nothing
    Try
        document.Open()

        Dim getPDF = (From id In d.tblPOAMdetails
                      Where id.closedDate Is Nothing _
                      And id.nasacsspno = "XXXXX"
                      Order By id.UPI Ascending
                      Select id.poamLink).ToList

        '' Add the main document into the list as the first document to be
        '' copied into the empty file created above
        getPDF.Insert(0, "K:\ConfigMgmt\PDF\POAM\JSCForm\JF2016_10_20.pdf")

        For Each file As String In getPDF
            reader = New PdfReader(file)
            pdf.AddDocument(reader)
            reader.Close()
        Next
    Catch generatedExceptionName As Exception
        merged = False
        If reader IsNot Nothing Then
            reader.Close()
        End If
    Finally
        If document IsNot Nothing Then
            document.Close()
        End If
    End Try
End Using

Open in new window

0
 

Author Closing Comment

by:Karen Wilson
ID: 41852824
Thanks Fernando!

That did it!!  I will work my code to remove the "original" one and rename the new one and I am good to go.  Thanks so much for your time.  It was making me bonkers!
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41852836
Not a problem Karen, always glad to help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

PaperPort is a popular document imaging/management product from Nuance Communications (http://www.nuance.com/). It is in widespread use by both individuals (http://www.nuance.com/for-individuals/by-product/paperport/index.htm) and businesses (http:/…
This article focuses on how to remove password security from multiple PDF files by Adobe Acrobat program. Sometimes it is essential to access the stored data items and to print, edit as well as copy content from Portable Document Format files in abs…
In this third video of the Xpdf series, we discuss and demonstrate the PDFtoText utility, which converts PDF files into plain text files. Download and install the software.: You may have already downloaded and installed the Xpdf tools while watching…
In this video, we show how to convert an image-only PDF file into a PDF Searchable Image file, that is, a file with both the image (typically from scanning) and text, which is created in an automated fashion with Optical Character Recognition (OCR) …

861 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now