在VBA中从Base64字符串生成PDF
I have the following JSON response:
{ 'status': 'Success', 'label': 'pdf_base64_string', 'order': 'ABC123456'}
I'm trying to save a PDF file from the Base64 string per the following code:
FileData = Base64DecodeString(pdf_base64_string)fileNum = FreeFileFilePath = 'C:\label.pdf'Open FilePath For Binary Access Write As #fileNum Put #fileNum, 1, FileDataClose #fileNum
This results in a broken/invalid PDF file (not recognized by the PDF viewer).
解决方案
Adapted from: Inserting an Image into a sheet using Base64 in VBA?
This works for me - saves the file to the same location as the workbook running the code.
Sub TestDecodeToFile() Dim strTempPath As String Dim b64test As String 'little face logo b64test = 'R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48' & _ 'CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==' strTempPath = ThisWorkbook.Path & '\temp.png' 'use workbook path as temp path 'save byte array to temp file Open strTempPath For Binary As #1 Put #1, 1, DecodeBase64(b64test) Close #1End SubPrivate 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 = NothingEnd Function
赞 (0)