Generating PDF from Base64 Byte Array in VBA

心不动则不痛 提交于 2019-12-11 08:37:56

问题


I have the following JSON response from a webservice method which will return byte[] in PDF format:

JVBERi0xLjQKJeLjz9MKMSAwI......nVq2P63zkirBH1z9aW3pDxn6F7q9TFV==

The return value is a byte() array. I been trying for a few days trying to use the function available in one of the questions posted in "Generating PDF from Base64 string in VBA" to generate PDF from the above Base64 Byte array, but I couldn't.

What I have done is that based on the return byte array from the webservice method, I save it as a byte array variable name b64testByte. Subsequently, I then proceed to call 2 methods in my program, namely encodeBase64 first, and followed by DecodeBase64. The PDF file is generated. However, when I try to open the file, there is an error which reads "Error: the document is damaged and cannot be repaired. Adobe Reader could not open because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)."

Dim b64testByte() As Byte
b64testByte = xmlhttp.responseText 

Dim B64String As String
B64String = encodeBase64(b64testByte)


    Dim FilePath As String
    FilePath = "D:\label.pdf"
    Open FilePath For Binary Access Write As #1
    Put #1, 1, DecodeBase64(B64String)
    Close #1


Private Function DecodeBase64(ByVal strData As String) As Byte()
    Dim objXML As Object 'MSXML2.DOMDocument
    Dim objNode As Object 'MSXML2.IXMLDOMElement
    'get dom document
    Set objXML = CreateObject("MSXML2.DOMDocument")
    'create node with type of base 64 and decode
    Set objNode = objXML.createElement("b64")
    objNode.DataType = "bin.base64"
    objNode.Text = strData
    DecodeBase64 = objNode.nodeTypedValue
    'clean up
    Set objNode = Nothing
    Set objXML = Nothing
End Function

Private Function encodeBase64(ByRef arrData() As Byte) As String
    Dim objXML As Object 'MSXML2.DOMDocument
    Dim objNode As Object 'MSXML2.IXMLDOMElement
    'get dom document
    Set objXML = CreateObject("MSXML2.DOMDocument")

    Set objNode = objXML.createElement("b64")
    objNode.DataType = "bin.base64"
    objNode.nodeTypedValue = arrData
    encodeBase64 = objNode.Text

    Set objNode = Nothing
    Set objXML = Nothing
End Function**

来源:https://stackoverflow.com/questions/51150136/generating-pdf-from-base64-byte-array-in-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!