'//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sub ExtrairePDFDepuisBinEtNettoyer()
Dim col As New Collection
Dim WsH As Object, dossierEmbeddings As Object, items As Object, item As Object, stream As Object
Dim tempo$, chemin$, binPath$, pdfPath$, bytes() As Byte, pdfBytes() As Byte, i&, startPos&, endPos&
Dim appdefaut As PdfAppInfo
tempo = ThisWorkbook.Path & "\tempo.zip" 'chemin du zip
ThisWorkbook.SaveCopyAs tempo 'on sauve une copie temporaire du classeur au format zip directement
Application.Wait Now + TimeValue("0:00:01")
col.Add tempo ' le premier item ce sera le zip complet
Set WsH = CreateObject("Shell.Application") 'c'rée l'object shel application
Set dossierEmbeddings = WsH.Namespace(tempo & "\xl\embeddings") 'le path complet du dossier dans le zip du dossier embbedding
If dossierEmbeddings Is Nothing Then MsgBox "Pas de dossier xl\embeddings": Exit Sub 'on se casse si y a pas
Set items = dossierEmbeddings.items 'collection des items a l'inteieurs du dossier
For Each item In items
If Dir(ThisWorkbook.Path & "\" & item.Name) <> "" Then Kill ThisWorkbook.Path & "\" & item.Name
WsH.Namespace(ThisWorkbook.Path).CopyHere item, 4 'on extrait
col.Add ThisWorkbook.Path & "\" & item.Name 'on ajoute les path a la collection
Next item
DoEvents
Set WsH = Nothing
' Étape 2 : Extraction PDF
For i = 2 To col.Count
binPath = col(i)
pdfPath = Replace(binPath, ".bin", ".pdf")
col.Add pdfPath
If Dir(pdfPath) <> "" Then Kill pdfPath
Set stream = CreateObject("ADODB.Stream")
stream.Type = 1
stream.Open
stream.LoadFromFile binPath
bytes = stream.Read
stream.Close
' Chercher %PDF le debut
startPos = -1
For j = 0 To UBound(bytes) - 3
If Chr(bytes(j)) = "%" And Chr(bytes(j + 1)) = "P" And Chr(bytes(j + 2)) = "D" And Chr(bytes(j + 3)) = "F" Then
startPos = j
Exit For
End If
Next j
' Chercher %%EOF la fin
endPos = -1
For j = UBound(bytes) - 5 To startPos + 4 Step -1
If Chr(bytes(j)) = "%" And Chr(bytes(j + 1)) = "%" And Chr(bytes(j + 2)) = "E" And Chr(bytes(j + 3)) = "O" And Chr(bytes(j + 4)) = "F" Then
endPos = j + 4
Exit For
End If
Next j
' Extraire et écrire le PDF
If startPos >= 0 And endPos > startPos Then
ReDim pdfBytes(endPos - startPos) As Byte
For j = startPos To endPos
pdfBytes(j - startPos) = bytes(j)
Next j
Set stream = CreateObject("ADODB.Stream")
stream.Type = 1
stream.Open
stream.Write pdfBytes
stream.SaveToFile pdfPath, 2
stream.Close
Else
MsgBox "PDF non trouvé dans " & binPath
End If
Next i
'ouvrir les pdfs
appdefaut = GetPdfDefaultExe
MsgBox appdefaut.ExeName
For i = 2 To col.Count
If Right(col(i), 4) = ".pdf" Then Shell """" & appdefaut.ExeName & """ """ & """" & col(i) & """"
Next
' Étape 3 : Nettoyage des fichiers bin
For i = 1 To col.Count
If Right(col(i), 4) <> ".pdf" Then Kill col(i)
Next i
MsgBox "Extraction terminée et fichiers bin supprimés."
End Sub