base64编码 vba_在VBA中从Base64字符串生成PDF

该博客介绍了如何从Base64编码的字符串创建PDF文件。作者遇到了使用Base64解码字符串后生成的PDF文件无法正常打开的问题。为了解决这个问题,他们提供了一个VBA代码示例,通过创建一个临时的PNG文件,成功地将Base64字符串转换并保存到工作簿路径。解码过程使用了MSXML2.DOMDocument对象来处理Base64数据。
摘要由CSDN通过智能技术生成

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 = FreeFile

FilePath = "C:\label.pdf"

Open FilePath For Binary Access Write As #fileNum

Put #fileNum, 1, FileData

Close #fileNum

This results in a broken/invalid PDF file (not recognized by the PDF viewer).

解决方案

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 #1

End Sub

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值