为什么我必须从 BytesIO 转换字节然后再转换回 BytesIO 以便它可以作为 PDF 文件响应读取?

Why I have to convert bytes from BytesIO then convert back to BytesIO so it can be read as PDF file response?

我用PyPDF4合并pdf文件,然后我用合并后的pdf作为HttpResponse。 我使用 BytesIOPdfFileMerger 得到结果。

我使用这段代码让它工作

def mergePDF(listOfPDFFile):
    merger = PdfFileMerger()
    for file in listOfPDFFile:
        merger.append(PdfFileReader(file))
    _byteIo = BytesIO()
    merger.write(_byteIo)
    return _byteIo.getvalue()

然后当我使用 APIView 中的方法将合并后的 pdf return 作为 HttpResponse

class DocumentBundlePDFView(APIView):
    def get(self, request, format=None):
        '''
         here goes a process to assign list of document to documentList
        '''
        pdfBytes = mergePDF(documentList)
        pdfFile = io.BytesIO(pdfBytes)
        response = HttpResponse(FileWrapper(pdfFile), content_type='application/pdf')
        return response

但是,为什么我必须创建 BytesIO 对象两次才能使其正常工作? 最初我 return _byteIO 实例然后直接将实例传递给 FileWrapper 但它输出 0Kb 文件。

所以我将 _byteIO 实例转换为 bytes,然后在 APIView 中创建另一个 BytesIO 实例以使其正常工作。

如何简化代码?

在你的 mergePDF 函数中,而不是返回

return _byteIo.getvalue()

做点什么效果

_byteIo.seek(0)
return _byteIo

Initially I return the _byteIO instance then directly pass the instance to FileWrapper but it output 0Kb file.

问题是当您写入类文件对象时,光标设置到最后一个字节。把它移回开头,否则就像从一个空文件中读取一样。