python PyPDF2附加文件问题

2fjabf4q  于 2022-12-21  发布在  Python
关注(0)|答案(1)|浏览(185)

我需要写脚本,将图像转换为PDF格式,并合并成一个tchem。
我试过使用img2pdf和PYPDF2,但我得到错误。有人能看看,告诉我我做错了什么。

import img2pdf
import os
from PyPDF2 import PdfFileReader, PdfFileMerger, PdfFileWriter

merger = PdfFileMerger()
path = input()

for root,dir,files in os.walk(path):
        for eachfile in files:
            if "pdf" not in eachfile:
                os.chdir(root)
                PDFfile = img2pdf.convert((eachfile,), dpi=None, x=None, y=None)
                merger.append(fileobj=PDFfile)
merger.write(open("out.pdf", "wb"))

错误

Traceback (most recent call last):
  File "C:/Users/ms/Desktop/Desktop/test.py", line 13, in <module>
    merger.append(fileobj=PDFfile)
  File "C:\Python34\lib\site-packages\PyPDF2\merger.py", line 203, in append
    self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)
  File "C:\Python34\lib\site-packages\PyPDF2\merger.py", line 133, in merge
    pdfr = PdfFileReader(fileobj, strict=self.strict)
  File "C:\Python34\lib\site-packages\PyPDF2\pdf.py", line 1065, in __init__
    self.read(stream)
  File "C:\Python34\lib\site-packages\PyPDF2\pdf.py", line 1660, in read
    stream.seek(-1, 2)
AttributeError: 'bytes' object has no attribute 'seek'
sg3maiej

sg3maiej1#

img2pdf.convert返回相应PDF文件的字节(作为字符串?),而不是文件处理程序。如果你读help(merger.append),你会发现你需要传递一个文件处理程序或PDF文件的路径。这里有一个可能的解决方案。也可能不生成所有中间PDF文件。

import img2pdf
import os
from PyPDF2 import PdfFileReader, PdfFileMerger, PdfFileWriter
merger = PdfFileMerger()
path = "/tmp/images"

for root,dir,files in os.walk(path):
        for eachfile in files:
            if "pdf" not in eachfile:
                os.chdir(root)
                pdfbytes = img2pdf.convert((eachfile,), dpi=None, x=None, y=None)
                pdfname = eachfile.split('.')[0]+".pdf"
                f = open(pdfname, 'wb+')
                f.write(pdfbytes)
                merger.append(fileobj=f)
                f.close()

f = open("out.pdf", "wb")
merger.write(f)
f.close()

顺便说一下,使用常规工具(如convertpdfjampdftk)也会简单得多。

相关问题