In your first block, open file in binary write mode (wb), since you are writing binary to it. Also, you don't need to convert it explicitly to str. It should look like this:

file = open('code.txt', 'wb')
for line in open('somefile.pdf', 'rb').readlines():
    file.write(line)
file.close()

For second block, open file in read binary mode (rb). Here also, no need to explicitly convert to bytes. It should look like this:

file = open('new.pdf', 'wb')
for line in open('code.txt', 'rb').readlines():
    file.write(line)
file.close()

This should do the trick. But why do you need to convert it in the first place? Keeping file intact will save your hardwork and computational power.

Answer from Jay Bhavsar on Stack Overflow
🌐
GitHub
github.com › shinray › bytetopdf
GitHub - shinray/bytetopdf: Python script to convert from byte array to PDF · GitHub
Python script to convert from byte array to PDF. Contribute to shinray/bytetopdf development by creating an account on GitHub.
Author: shinray
Discussions

python - Reading the bytes of a PDF - Code Review Stack Exchange
I'm quite a newbie in Python and I want to speed up this method since it takes very long time especially when the size of the input file in Mbs. Also, I couldn't figure out how to use Cython in the for loop. I'm using this function with other functions to compare files byte by byte. Any recommendations? # this function returns a file bytes in a list filename1 = 'doc1.pdf... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
June 4, 2015
Unable to process pdf converted to bytes
I have just installed the package ... file to PdfReader gives an error, path should be string, bytes, os.PathLike or integer, not FileStorage" Not sure why it is doing so, but I have tried changing it to byte data and using temp file but still getting the same issue, here's my code · $ python -m platform ... More on github.com
🌐 github.com
4
November 17, 2023
python 3.x - Convert a byte type data from .tiff file into PDF - Stack Overflow
TODO: Convert a TIFF file from URL into PDF I have a .tiff based file that I need to download/get from a url. When trying to save/download that file into cwd, it is downloaded, however, I am unable... More on stackoverflow.com
🌐 stackoverflow.com
Problem converting PDFs to bytes?
img_bytes = fig.to_image(format="pdf") img = Image.open(io.BytesIO(img_bytes)) img.save("image.pdf") Traceback (most recent call last): File "test.py", line 27, in img = Image.open(io.BytesIO(img_bytes)) File "XXX/lib/python3.7/site-packages/PIL/Image.py", line 2896, in open "cannot ... More on github.com
🌐 github.com
4
June 1, 2020
🌐
Python.org
discuss.python.org › python help
From list of bytes to PDF file - Python Help - Discussions on Python.org
November 2, 2021 - Hello! I am working on a simple program that works on PDF files. So far I’ve been able to read the PDF into a list of bytes with the following code: def bstr(n): # n in range 0-255 return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)]) def read_binary(): f = open('source.pdf','rb') ...
🌐
Quora
quora.com › How-do-I-convert-a-PDF-into-an-array-of-bytes-and-then-back-to-the-same-PDF-in-Python
How to convert a PDF into an array of bytes and then back to (the same) PDF in Python - Quora
Answer (1 of 2): You set up a Python bytearray, use Python file read operations to read the contents of the file without processing into the bytearray, then use Python file write operations to write the bytearray back to another file (preferably with a different name), making sure to give the new...
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert python bytes to pdf
5 Best Ways to Convert Python Bytes to PDF - Be on the Right Side of Change
February 23, 2024 - This code uses ReportLab to write text contained within a bytes object to a PDF. The BytesIO object works as in-memory file, which then is written into an actual file. The FPDF library is a flexible and easy-to-use Python library to create PDFs programmatically.
🌐
Base64.Guru
base64.guru › home › developers › python › examples
Convert Base64 to PDF in Python | Examples | Python | Developers | Base64
To convert Base64 to PDF file in Python you need the base64.b64decode function and any function to write binary data into local files.
🌐
IQCode
iqcode.com › code › python › create-pdf-from-bytes-python
create pdf from bytes python Code Example
November 12, 2021 - file = open('new.pdf', 'wb') for line in open('code.txt', 'rb').readlines(): file.write(line) file.close() ... Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
🌐
e-iceblue
e-iceblue.com › Knowledgebase › Python › Spire.PDF-for-Python › Program-Guide › Conversion › Python-Load-and-Save-PDFs-with-Byte-Streams.html
Python: Load and Save PDFs with Byte Streams
This article will demonstrate how ... and bytearray using Spire.PDF for Python, offering practical examples for Python developers. ... This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command. ... Developers can create PDF documents using the classes and methods provided by Spire.PDF for Python, save them to a Stream object, and then convert it to an immutable ...
Find elsewhere
🌐
PyFPDF
pyfpdf.readthedocs.io › en › latest › reference › output › index.html
output() - PyFPDF - Read the Docs
Send the document to some destination: standard output, a file or a byte string. The method first calls close if necessary to terminate the document. NOTICE: In Python 2 strings were raw data but in Python 3 strings are now unicode by default. If you are using Python 3.x you have to use pdf.output(dest='S').encode('latin-1') in order to get the output, if you don't do so the generated PDF will be invalid and depending on the viewer either not open at all or show up as some blank pages.
🌐
GitHub
github.com › py-pdf › pypdf › issues › 2299
Unable to process pdf converted to bytes · Issue #2299 · py-pdf/pypdf
November 17, 2023 - I have just installed the package and tried uploading a file using form data, passing the file to PdfReader gives an error, path should be string, bytes, os.PathLike or integer, not FileStorage" Not sure why it is doing so, but I have tried changing it to byte data and using temp file but still getting the same issue, here's my code · $ python -m platform macOS-13.2.1-arm64-arm-64bit $ python -c "import pypdf;print(pypdf._debug_versions)" pypdf==3.17.1, crypt_provider=('local_crypt_fallback', '0.0.0'), PIL=10.0.1
Author: py-pdf
🌐
Readthedocs
pdf2image.readthedocs.io › en › latest › overview.html
Overview — pdf2image latest documentation - Read the Docs
from pdf2image import convert_from_path, convert_from_bytes images = convert_from_path("/home/user/example.pdf") # OR with open("/home/user/example.pdf") as pdf: images = convert_from_bytes(pdf.read()) This is the most basic usage, but the converted images will exist in memory and that may not be what you want since you can exhaust resources quickly with big PDF. Instead, use an output_folder to avoid using the memory directly.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-write-bytes-to-file
Python - Write Bytes to File - GeeksforGeeks
May 17, 2025 - Explanation: This code writes a byte sequence (some_bytes) to a file in binary mode. It opens my_file.txt in wb mode, and writes the bytes (b'\xC3\xA9') to it, representing the Unicode character é.
🌐
Reddit
reddit.com › r/aspose_pdf_for_net › convert pdf to bytearray via python🥸
r/aspose_pdf_for_net on Reddit: Convert PDF to BYTEARRAY via Python🥸
December 7, 2022 - A byte is a fundamental data type of information in computing and telecommunications. PDF is the most versatile, reliable, editable file format that can contain more than text and can be opened on any device. Aspose.PDF for Python allows you to convert PDF to BYTEARRAY programmatically.
🌐
GitHub
github.com › plotly › plotly.py › issues › 2521
Problem converting PDFs to bytes? · Issue #2521 · plotly/plotly.py
June 1, 2020 - The following code throws an error when format="pdf": img_bytes = fig.to_image(format="pdf") img = Image.open(io.BytesIO(img_bytes)) img.save("image.pdf") Traceback (most recent call last): File "test.py", line 27, in img = Imag...
Author: plotly
🌐
Better Programming
betterprogramming.pub › efficiently-convert-pdf-to-png-or-jpeg-images-in-python-50c5ce224c20
Efficiently Convert PDF to PNG or JPEG Images in Python | by Hatim Zahid | Better Programming
July 9, 2022 - The warkzeug documentation explicitly tells to call the secure function on the file.filename to get a secure version of the the filename. ... 3. Import pdf2image package and convert the pdf bytes ...
🌐
Readthedocs
pypdf2.readthedocs.io › en › 3.0.0 › user › streaming-data.html
Streaming Data with PyPDF2 — PyPDF2 documentation
from io import BytesIO import boto3 from PyPDF2 import PdfReader, PdfWriter reader = PdfReader(BytesIO(raw_bytes_data)) writer = PdfWriter() # Add all pages to the writer for page in reader.pages: writer.add_page(page) # Add a password to the new PDF writer.encrypt("my-secret-password") # Save the new PDF to a file with BytesIO() as bytes_stream: writer.write(bytes_stream) bytes_stream.seek(0) s3 = boto3.client("s3") s3.write_get_object_response( Body=bytes_stream, RequestRoute=request_route, RequestToken=request_token )
🌐
ConvertAPI
convertapi.com › any-to-pdf › python
File to PDF Conversion Python SDK - Convert 100+ file types to PDF
The raw file bytes are streamed back in the API response without touching disk or external storage, ensuring maximum security and zero persistence so that only you can access the content. Easy File to PDF integration using our Python library · ConvertAPI provides a Python library that allows you to perform a File to PDF conversion with just a few lines of code.
Top answer
1 of 1
1

In such cases, it's preferred to send file data passing that with the files keyword, like so:

import requests


def send_pdf_data(filename_list, encoded_pdf_data):
    files = {}

    for (filename, encoded, index) in zip(filename_list, encoded_pdf_data, range(len(filename_list))):
        files[f"pdf_name_[index].pdf"] = (filename, open(filename, 'rb'), 'application/pdf')

    data = {}
    # *Put whatever you want in data dict*

    requests.post("http://yourserveradders", data=data, files=files)


def main():
    filename_list = ["pdf_name_1.pdf", "pdf_name_2.pdf"]
    pdf_blob_data = [open(filename, 'wb').read() for filename
                     in filename_list]

if __name__ == '__main__':
    main()

However, if you really want to pass data as json, you should use base-64 module as @Mark Ransom mentioned.

You can implement it in this way:

import requests
import json
import base64


def encode(data: bytes):
    """
    Return base-64 encoded value of binary data.
    """
    return base64.b64encode(data)


def decode(data: str):
    """
    Return decoded value of a base-64 encoded string.
    """
    return base64.b64decode(data.encode())


def get_pdf_data(filename):
    """
    Open pdf file in binary mode,
    return a string encoded in base-64.
    """
    with open(filename, 'rb') as file:
        return encode(file.read())


def send_pdf_data(filename_list, encoded_pdf_data):
    data = {}
    # *Put whatever you want in data dict*
    # Create content dict.
    content = [dict([("name", filename), ("data", pdf_data)])
               for (filename, data) in zip(filename_list, encoded_pdf_data)]
    data["content"] = content

    data = json.dumps(data) # Convert it to json.
    requests.post("http://yourserveradders", data=data)


def main():
    filename_list = ["pdf_name_1.pdf", "pdf_name_2.pdf"]
    pdf_blob_data = [get_pdf_data(filename) for filename
                     in filename_list]

if __name__ == '__main__':
    main()