Accessing bytesIO object after creation
<p>I am working on a scrapy spider, trying to extract text multiple pdfs in a directory, using slate (<a href="https://pypi.python.org/pypi/slate" rel="nofollow">https://pypi.python.org/pypi/slate</a>). I have no interest in saving the actual PDF to disk , and so I've been advised to look into the io.bytesIO subclass at <a href="https://docs.python.org/2/library/io.html#buffered-streams" rel="nofollow">https://docs.python.org/2/library/io.html#buffered-streams</a>. Based on <a href="http://stackoverflow.com/questions/39799009/creating-and-accessing-bytesio-object/39799090#39799090">Creating bytesIO object</a> , I have initialized the bytesIO class with the pdf body, but now I need to pass the data to the slate module. So far I have:</p>

<pre><code>def save_pdf(self, response):
    in_memory_pdf = BytesIO(response.body)

    with open(in_memory_pdf, 'rb') as f:
        doc = slate.PDF(f)
        print(doc[0])
</code></pre>

<p>I'm getting: </p>

<pre><code>in_memory_pdf.read(response.body)
TypeError: integer argument expected, got 'str'
</code></pre>

<p>How can I get this working?</p>

<p>edit:</p>

<pre><code>with open(in_memory_pdf, 'rb') as f:
TypeError: coercing to Unicode: need string or buffer, _io.BytesIO found
</code></pre>

<p>edit 2:</p>

<pre><code>def save_pdf(self, response):
    in_memory_pdf = BytesIO(bytes(response.body))
    in_memory_pdf.seek(0)
    doc = slate.PDF(in_memory_pdf)
    print(doc)
</code></pre>

<p>You already know the answer. It is clearly mentioned in the Python TypeError message and clear from the documentation:</p>

<pre><code>class io.BytesIO([initial_bytes])
</code></pre>

<p>BytesIO accepts bytes. And you are passing it contents. i.e: response.body which is a string.</p>

python pdf