代码之家  ›  专栏  ›  技术社区  ›  Mathias

Base64到PDF文件失败

  •  0
  • Mathias  · 技术社区  · 2 年前

    我正在尝试将Base64字符串写入PDF文件。但是PDF文件已损坏。 Base64来自网络请求。

    我试过这样做:

    blob = js_response.get("result")
    with open("test.txt, "w") as txtfile:
        txtfile.write(blob)
    with open("test.pdf", "w") as pdffile:
        pdffile.write(blob)
    

    我首先将其写入TXT文件的原因是为了调试。该代码确实写入2个文件: 当我打开TXT文件并在base64.guru这样的base64到PDF转换器上测试它时,正确的PDF文件就会打开。

    但当我试图打开PDF文件时,文件已损坏。

    最奇怪的是,这个完全相同的代码上周也在工作。所以我不认为这与写命令有关,而是更多地与Base64的格式有关?

    感谢您的真知灼见

    1 回复  |  直到 2 年前
        1
  •  -1
  •   Mahboob Nur    2 年前

    这样试试

    import base64
    
    blob = js_response.get("result")
    
    # Decode the base64 string to binary data
    pdf_binary = base64.b64decode(blob)
    
    # Write binary data to a PDF file
    with open("test.pdf", "wb") as pdffile:
        pdffile.write(pdf_binary)