Private Function Extract_Embedded_PDFs() As String
Dim FSO As Object
Dim ShellApp As Object
Dim workingFolder As String
Dim unzippedFolder As Variant
Dim PDFsFolder As Variant
Dim workbookZipFile As Variant
Dim i As Long
Dim oleObjectFileName As String, oleObjectFile As String
Dim embeddedPDFfile As String
'Extract embedded PDFs in this workbook and return a string containing the .pdf files separated by "|"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set ShellApp = CreateObject("Shell.Application")
'Define the working folder. This will contain this workbook, saved as a .zip file, an Unzipped subfolder in which the embedded object .bin files will
'be unzipped and a PDFs subfolder in which the embedded PDFs will be saved
workingFolder = Environ("temp") & "\Workbook"
unzippedFolder = workingFolder & "\Unzipped"
PDFsFolder = workingFolder & "\PDFs"
workbookZipFile = workingFolder & "\Workbook.zip"
'Create the folders
If FSO.FolderExists(workingFolder) Then FSO.DeleteFolder workingFolder
FSO.CreateFolder workingFolder
FSO.CreateFolder unzippedFolder
FSO.CreateFolder PDFsFolder
'Make copy of this workbook as a .zip file
ActiveWorkbook.SaveCopyAs workbookZipFile
'Unzip embedded objects (.bin files) and create .pdf files
Extract_Embedded_PDFs = ""
For i = 1 To ShellApp.Namespace(workbookZipFile).items.Count
oleObjectFileName = "oleObject" & i & ".bin"
ShellApp.Namespace(unzippedFolder).CopyHere ShellApp.Namespace(workbookZipFile).items.Item("xl\embeddings\" & oleObjectFileName)
oleObjectFile = unzippedFolder & "\" & oleObjectFileName
If Not FSO.FileExists(oleObjectFile) Then Exit For
embeddedPDFfile = PDFsFolder & "\PDF_" & Format(i, "00") & ".pdf"
If Create_PDF_From_Bin(oleObjectFile, embeddedPDFfile) Then
Extract_Embedded_PDFs = Extract_Embedded_PDFs & embeddedPDFfile & "|"
End If
Next
'Clean up
FSO.DeleteFolder unzippedFolder
FSO.DeleteFile workbookZipFile, True
End Function
Private Function Create_PDF_From_Bin(binFile As String, PDFfile As String) As Boolean
Dim hFile As Integer
Dim contents As String
Dim PDF As String
Dim i As Long, j As Long
'Determine whether the specified .bin file contains a PDF and, if so, save the PDF bytes as the specified .pdf file and return True. Otherwise return False
Create_PDF_From_Bin = False
hFile = FreeFile
Open binFile For Binary Access Read As #hFile
contents = String(LOF(hFile), vbNullChar)
Get #hFile, , contents
Close #hFile
i = InStrB(1, contents, "%PDF")
If i > 0 Then
'This .bin file contains a PDF, so save the PDF bytes as a .pdf file
j = InStrB(1, contents, "%%EOF" & vbLf)
If j = 0 Then j = InStrB(1, contents, "%%EOF")
PDF = MidB(contents, i, j - i + 12)
Open PDFfile For Binary Access Write As #hFile
Put #hFile, , PDF
Close #hFile
Create_PDF_From_Bin = True
End If
End Function