【发布时间】:2015-03-14 11:51:34
【问题描述】:
我在 Windows 7 上使用 Python 3.4.2 和 PyPDF2 1.24(如果有帮助,也使用 reportlab 3.1.44)。
我最近从 Python 2.7 升级到 3.4,并且正在移植我的代码。此代码用于创建一个空白 pdf 页面,其中嵌入了链接(使用 reportlab)并将其(使用 PyPDF2)与现有的 pdf 页面合并。我在reportlab 中遇到了一个问题,即保存画布使用的StringIO 需要更改为BytesIO,但在这样做之后我遇到了这个错误:
Traceback (most recent call last):
File "C:\cms_software\pdf_replica\builder.py", line 401, in merge_pdf_files
input_page.mergePage(link_page)
File "C:\Python34\lib\site-packages\PyPDF2\pdf.py", line 2013, in mergePage
self.mergePage(page2)
File "C:\Python34\lib\site-packages\PyPDF2\pdf.py", line 2059, in mergePage
page2Content = PageObject._pushPopGS(page2Content, self.pdf)
File "C:\Python34\lib\site-packages\PyPDF2\pdf.py", line 1973, in _pushPopGS
stream = ContentStream(contents, pdf)
File "C:\Python34\lib\site-packages\PyPDF2\pdf.py", line 2446, in __init
stream = BytesIO(b_(stream.getData()))
File "C:\Python34\lib\site-packages\PyPDF2\generic.py", line 826, in getData
decoded._data = filters.decodeStreamData(self)
File "C:\Python34\lib\site-packages\PyPDF2\filters.py", line 326, in decodeStreamData
data = ASCII85Decode.decode(data)
File "C:\Python34\lib\site-packages\PyPDF2\filters.py", line 264, in decode
data = [y for y in data if not (y in ' \n\r\t')]
File "C:\Python34\lib\site-packages\PyPDF2\filters.py", line 264, in
data = [y for y in data if not (y in ' \n\r\t')]
TypeError: 'in <string>' requires string as left operand, not int
这是回溯提到的行和上面的行:
link_page = self.make_pdf_link_page(pdf, size, margin, scale_factor, debug_article_links)
if link_page != None:
input_page.mergePage(link_page)
以下是 make_pdf_link_page 函数的相关部分:
packet = io.BytesIO()
can = canvas.Canvas(packet, pagesize=(size['width'], size['height']))
....# left out code here is just reportlab specifics for size and url stuff
can.linkURL(url, r1, thickness=1, color=colors.green)
can.rect(x1, y1, width, height, stroke=1, fill=0)
# create a new PDF with Reportlab that has the url link embedded
can.save()
packet.seek(0)
try:
new_pdf = PdfFileReader(packet)
except Exception as e:
logger.exception('e')
return None
return new_pdf.getPage(0)
我假设这是使用 BytesIO 的问题,但我无法使用带有 StringIO 的 reportlab 创建页面。这是一个关键特性,过去可以完美地与 Python 2.7 配合使用,因此我将不胜感激任何形式的反馈。谢谢!
更新: 我也尝试过从使用 BytesIO 更改为仅写入临时文件,然后合并。不幸的是,我遇到了同样的错误。 这是临时文件版本:
import tempfile
temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, "tmp.pdf")
can = canvas.Canvas(temp_path, pagesize=(size['width'], size['height']))
....
can.showPage()
can.save()
try:
new_pdf = PdfFileReader(temp_path)
except Exception as e:
logger.exception('e')
return None
return new_pdf.getPage(0)
更新: 我发现了一些有趣的信息。似乎如果我注释掉 can.rect 和 can.linkURL 调用它会合并。因此,在页面上绘制任何内容,然后尝试将其与我现有的 pdf 合并会导致错误。
【问题讨论】:
标签: porting python-3.4 reportlab pypdf