Public Function ExtractPDF(BLOBField As DAO.Field2, FilePath As String) As String
Dim b() As Byte
Dim i As Long
Dim j As Long
Dim k As Long
Dim m As Long
Dim PDFStartMarker(4) As Byte
Dim PDFEndMarker(8) As Byte
Dim PDFEndMarkerUnix(7) As Byte
Dim PDFStartBytePosition As Long
Dim PDFEndBytePosition As Long
Dim FileNumber As Long
Dim OutputArray() As Byte
Dim FileSize As Long
ReDim b(1)
'PDFStartMarker (%PDF) defines the beginning of the PDF
PDFStartMarker(0) = 37
PDFStartMarker(1) = 80
PDFStartMarker(2) = 68
PDFStartMarker(3) = 70
'PDFENDMarker (%%EOF) defines the end of the PDF Windows
PDFEndMarker(0) = Val("&H25")
PDFEndMarker(1) = Val("&H25")
PDFEndMarker(2) = Val("&H45")
PDFEndMarker(3) = Val("&H4F")
PDFEndMarker(4) = Val("&H46")
PDFEndMarker(5) = Val("&H0D")
PDFEndMarker(6) = Val("&H0A")
PDFEndMarker(7) = Val("&H00")
'PDFENDMarker (%%EOF) defines the end of the PDF Unix
PDFEndMarkerUnix(0) = Val("&H25")
PDFEndMarkerUnix(1) = Val("&H25")
PDFEndMarkerUnix(2) = Val("&H45")
PDFEndMarkerUnix(3) = Val("&H4F")
PDFEndMarkerUnix(4) = Val("&H46")
PDFEndMarkerUnix(5) = Val("&H0A")
PDFEndMarkerUnix(6) = Val("&H00")
j = 0
k = 0
m = 0
'Scan throught the BLOB to find the beginning and end of the PDF
For i = 0 To BLOBField.FieldSize - 1
'Finding beginning
b = BLOBField.GetChunk(i, 1)
If b(0) = PDFStartMarker(j) Then
If j = 3 Then
PDFStartBytePosition = i - j
j = 0
Else
j = j + 1
End If
Else
j = 0
End If
'Finding end UNIX
If b(0) = PDFEndMarkerUnix(m) Then
If m = 6 Then
PDFEndBytePosition = i
Exit For
m = 0
Else
m = m + 1
End If
Else
m = 0
End If
'Finding end windows
If b(0) = PDFEndMarker(k) Then
If k = 7 Then
PDFEndBytePosition = i
Exit For
k = 0
Else
k = k + 1
End If
Else
k = 0
End If
Next i
If PDFStartBytePosition = 0 Then
ExtractPDF = "Start position not found"
Exit Function
End If
If PDFEndBytePosition = 0 Then
ExtractPDF = "End position not found"
Exit Function
End If
FileSize = PDFEndBytePosition - PDFStartBytePosition + 1
ReDim OutputArray(FileSize)
OutputArray = BLOBField.GetChunk(PDFStartBytePosition, FileSize)
' Remove any existing destination file.
FileNumber = FreeFile
Open FilePath For Output As FileNumber
Close FileNumber
' Open the destination file and output the PDF
Open FilePath For Binary As FileNumber
Put FileNumber, , OutputArray
Close FileNumber
End Function