Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Merging PDFs with VB.NET

Posted on 2016-10-20
10
Medium Priority
?
75 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 64

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
Technology Partners: 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!

 
LVL 64

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
 

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 64

Accepted Solution

by:
Fernando Soto earned 2000 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 64

Expert Comment

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

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

The ability to edit PDF documents can be useful, however it may not be a straight forward process. Many non-technical people don't realise that a PDF document is basically an image rather than a text file, even if it contains nothing but text. If…
Update 21-May-2015: I temporarily removed the source code and the code snippets to make major changes to the program. Regards, Joe INTRODUCTION This Article is a follow-up to the Article entitled How To Rename-Move a Batch of PDF Files Based o…
Sometimes we receive PDF files that are in the wrong orientation. They may be sideways or even upside down. This most commonly happens with scanned or faxed documents. It is possible to rotate the view of these PDFs with the free Adobe Reader produc…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

722 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