Sharing: combine multiple PDF's into one PDF with an OPEN SOURCE dll

Sharing: combine multiple PDF's into one PDF with an OPEN SOURCE dll

machiel.veldkamp
Collaborator Collaborator
315 Views
2 Replies
Message 1 of 3

Sharing: combine multiple PDF's into one PDF with an OPEN SOURCE dll

machiel.veldkamp
Collaborator
Collaborator

I've been looking for a way to combine multiple PDF's into one PDF with a free or open source method.

 

I've found the PdfSharp dll which is open source and ported it from C# to VBA.

 

Add these references to your code:

AddReference "System.Drawing.dll"
AddReference "PdfSharp.dll"

And use this function to combine the PDF's

Private Shared Sub ConcenatePDFs(ExportLocation As String)
		'Uses PDfSharp.dll to concenate multipe files with multiple pages into one PDFdocument
		'Collect the filenames (C:\....\file.pdf) in a string()
	    Dim files As String() = IO.Directory.GetFiles(ExportLocation)
		
		'Declare the outputdocument as a PDFDocument
		Dim outputDocument As PdfSharp.Pdf.PdfDocument = New PdfSharp.Pdf.PdfDocument()
		
		'Iterate throught the Files()
	    For Each File As String In files
			'add the file to the inputdocument
	        Dim inputDocument As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(File, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import)
			'Count the pages of said document
	        Dim count As Integer = inputDocument.PageCount
	        'For each page, add the pages to the OutputDocument
			For idx As Integer = 0 To count - 1
	            Dim page As PdfSharp.Pdf.PdfPage = inputDocument.Pages(idx)
	            outputDocument.AddPage(page)
	        Next
	    Next
		'Declare the outputFileName
	    Dim filename As String = ExportLocation & "\CombinedPDF.pdf"
	    outputDocument.Save(filename)   
	End Sub

 

Sources:

https://www.pdfsharp.net/wiki/ConcatenateDocuments-sample.ashx

Did you find this reply helpful ? If so please use the Accept as Solution or Kudos button below.

___________________________
0 Likes
316 Views
2 Replies
Replies (2)
Message 2 of 3

Curtis_Waguespack
Consultant
Consultant

@machiel.veldkamp , thanks for this (I'm adding it to my stash), and I'll add a similar ilogic script I had on hand that I probably took from this forum in the past ... just to have them both in one place for anyone that finds this in the future.

 

iLogic / VB.net

 

 

AddReference "C:\Users\Public\global references\itextsharp.dll"
addreference "System.IO"
Class ThisRule

	Shared _Folder_Path As String = String.Empty
	Shared _PDF_Name As String = Nothing
	Shared _GetPDF As String = String.Empty

	Sub Main()

		'set the path of the folder contaiing all of the pdfs
		_Folder_Path = "C:\Temp\PDFs"

		If Not System.IO.Directory.Exists(_Folder_Path) Then
			System.IO.Directory.CreateDirectory(_Folder_Path)
		End If

		'set the name of the new pdf you want to create without the extension
		_PDF_Name = "MyNewPDF"

		'get the PDF result
		Dim OpenPDF As String = CreatePDF(_Folder_Path)

		'open on condition to the result
		Select Case OpenPDF
			Case "FALSE"
				MsgBox("No PDF was generated")
			Case Else
				Process.Start(OpenPDF)
		End Select

	End Sub

	Private Function CreatePDF(_Folder_Path As String)

		Dim bOutputfileAlreadyExists As Boolean = False
		Dim sOutFilePath As String = IO.Path.Combine(_Folder_Path, _PDF_Name & ".pdf")

		'sdet up return for a successful pdf. ret changes to FALSE if any errors occur for qualifying purposes
		Dim ret As String = sOutFilePath

		If IO.File.Exists(sOutFilePath) Then
			Try
				IO.File.Delete(sOutFilePath)
			Catch ex As Exception
				bOutputfileAlreadyExists = True
			End Try
		End If

		Dim iPageCount As Integer = GetPageCount(_Folder_Path)
		If iPageCount > 0 And bOutputfileAlreadyExists = False Then

			Dim oFiles As String() = IO.Directory.GetFiles(_Folder_Path)
			Dim oPdfDoc As New iTextSharp.text.Document()
			Dim oPdfWriter As iTextSharp.text.pdf.PdfWriter = _
			iTextSharp.text.pdf.PdfWriter.GetInstance(oPdfDoc, New IO.FileStream(sOutFilePath, IO.FileMode.Create))

			oPdfDoc.Open()

			System.Array.Sort(Of String)(oFiles)

			For i As Integer = 0 To oFiles.Length - 1
				Dim sFromFilePath As String = oFiles(i)
				Dim oFileInfo As New IO.FileInfo(sFromFilePath)
				Dim sFileType As String = "PDF"
				Dim sExt As String = PadExt(oFileInfo.Extension)

				Try
					AddPdf(sFromFilePath, oPdfDoc, oPdfWriter)
				Catch ex As Exception
					ret = "FALSE"
				End Try
			Next

			Try
				oPdfDoc.Close()
				oPdfWriter.Close()
			Catch ex As Exception

				Try
					IO.File.Delete(sOutFilePath)
				Catch ex2 As Exception
				End Try
			End Try
		End If

		Dim oFolders As String() = IO.Directory.GetDirectories(_Folder_Path)
		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)
			CreatePDF(sChildFolder)
		Next

		Return ret

	End Function

	Private Sub AddPdf(ByVal sInFilePath As String, ByRef oPdfDoc As iTextSharp.text.Document, ByRef oPdfWriter As iTextSharp.text.pdf.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

	Private Function PadExt(ByVal s As String) As String
		s = UCase(s)
		If s.Length > 3 Then
			s = s.Substring(1, 3)
		End If
		Return s
	End Function

	Private Function GetPageCount(ByVal _Folder_Path As String) As Integer
		Dim iRet As Integer = 0
		Dim oFiles As String() = IO.Directory.GetFiles(_Folder_Path)

		For i As Integer = 0 To oFiles.Length - 1
			Dim sFromFilePath As String = oFiles(i)
			Dim oFileInfo As New IO.FileInfo(sFromFilePath)
			Dim sFileType As String = "PDF"
			Dim sExt As String = PadExt(oFileInfo.Extension)

			iRet += 1
		Next

		Return iRet
	End Function

End Class

 

 

 

 

 

EESignature

0 Likes
Message 3 of 3

emanuel.c
Collaborator
Collaborator

Yes, the PdfSharp dll which used to be iTextSharp dll works really well! Since it combines all PDFs in a folder into one PDF, use iLogic to create folders, copy files into said folders and combine all kinds of Drawings.

 

- Since we have separate drawings for the Assembly / Weldments and their respective 'child' components, I use it to compile all these drawings together.

- I use it to 'Compile' drawings based on Material Thicknesses, Stock Sizes, Bent components, Processes (like machining, using a defined iProperty) etc. etc. Very helpful for the shop floor.

 

So amazing and fast too! It takes a few minutes for hundreds of drawings. If it is at all helpful you can take a look at my code here. It is fairly customized for our needs, but here's some ideas.

 

https://forums.autodesk.com/t5/inventor-programming-ilogic/compile-assembly-drawings/m-p/12807805 

 

I think I first saw a post on iTextSharp by @NachoShaw and am very grateful for it.

0 Likes