def attach(self, binary):
# determine the format of the file
ext = puremagic.from_string(binary)
page = None
# if the attachment is a PDF
if ext == ".pdf":
# use PyPDF2 to read the stream
pdf = PdfFileReader(BytesIO(binary))
# if it is a multi-page PDF
if pdf.getNumPages() > 1:
# add the pages individually
for pdf_page in pdf.pages:
output = PdfFileWriter()
output.addPage(pdf_page)
pdf_page_buf = BytesIO()
output.write(pdf_page_buf)
page = self.add_page(pdf_page_buf.getvalue())
# if it is just a single page PDF
else:
# then add the original bytestream
page = self.add_page(binary)
# if the attachment is a recognized image
elif ext in [".png", ".jfif", ".gif", ".jpeg", ".jpg"]:
page = self.add_page(binary)
# could not recognize file
else:
pass
if page:
return(page)
评论列表
文章目录