html 属性错误:"bytes"对象没有属性"getPage"

lo8azlld  于 2023-01-24  发布在  其他
关注(0)|答案(1)|浏览(117)

我做了一些编码。html和 flask 。接受pdf文件从一个形式和水印它使用 flask 。
下面是我的html代码:

<!DOCTYPE html>
<html>
<body>

<p>Click on the "Choose File" button to upload a file:</p>

<form action="/upload_file" method="POST" enctype = "multipart/form-data">
  <input type="file" name="file">
  <input type="submit">
</form>

</body>
</html>

下面是我的 flask 编码:

@app.route('/upload_file', methods=['POST'])
def upload_file():

pdf_file = request.files['file']
watermark = "watermark.pdf"
merged_file = "merged.pdf"

input_pdf= pdf_file.read()
#input_pdf = PyPDF2.PdfFileReader(open(pdf_file,'rb'))

watermark_file = open(watermark,'rb')
watermark_pdf = PyPDF2.PdfFileReader(watermark_file)

pdf_page = input_pdf.getPage(0)

watermark_page = watermark_pdf.getPage(0)

pdf_page.mergePage(watermark_page)

output = PyPDF2.PdfFileWriter()

output.addPage(pdf_page)

merged_file = open(merged_file,'wb')
output.write(merged_file)

merged_file.close()
watermark_file.close()
input_pdf.close()

return "Success"

追溯:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2088, in 
__call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2073, in 
wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2070, in 
wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1515, in 
full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1513, in 
full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1499, in 
dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:\Users\User\Desktop\abc\test.py", line 57, in upload_file
    pdf_page = input_pdf.getPage(0)
AttributeError: 'bytes' object has no attribute 'getPage'

如何修复AttributeError:"bytes"对象没有属性"getPage"错误,也没有AttributeError:'bytes'对象没有属性'mergePage'错误?
我需要帮助。谢谢。

wlzqhblo

wlzqhblo1#

相关代码为:

input_pdf= pdf_file.read()
pdf_page = input_pdf.getPage(0)

从注解掉的行(input_pdf = PyPDF2.PdfFileReader(open(pdf_file,'rb')))看,您可能希望基于pdf_file创建一个PdfFileReader对象。由于pdf_file是一个文件,请尝试:

input_pdf = PyPDF2.PdfFileReader(pdf_file) # changed from pdf_file.read()
pdf_page = input_pdf.getPage(0)

相关问题