我需要写脚本,将图像转换为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'
1条答案
按热度按时间sg3maiej1#
img2pdf.convert
返回相应PDF文件的字节(作为字符串?),而不是文件处理程序。如果你读help(merger.append)
,你会发现你需要传递一个文件处理程序或PDF文件的路径。这里有一个可能的解决方案。也可能不生成所有中间PDF文件。顺便说一下,使用常规工具(如convert、pdfjam、pdftk)也会简单得多。