简体   繁体   English

PyPDF2 writer 函数创建空白页

[英]PyPDF2 writer function creates blank page

Trying to write a function to combine pages in a PDF document.尝试编写一个函数来组合 PDF 文档中的页面。 Streaming the output creates a blank page for an unknown reason Here is the test case流式输出由于未知原因创建了一个空白页面这是测试用例

from PyPDF2 import PdfReader, PdfWriter

dr = r"C:\GC"
ldr = dr + r"\12L.pdf"
writer = PdfWriter()

with open(ldr, "rb") as f:
    reader = PdfReader(f)
    page = reader.pages[0]
    writer.add_page(page)
    f.close()

with open(dr + r"\new.pdf", "wb") as output_stream:
    writer.write(output_stream)
    output_stream.close()

Edit: I made some changes to my PE and got more information.编辑:我对我的 PE 进行了一些更改并获得了更多信息。

writer.write(output_stream)

raises the error引发错误

ValueError: I/O operation on closed file: C:\GC\12L.pdf

I did some troubleshooting with keeping the reader file open and changing syntax to suggestions and I still raise the error.我通过保持阅读器文件打开并将语法更改为建议进行了一些故障排除,但我仍然提出了错误。

Since you're using a context manager, you don't need to explicitly call .close() .由于您使用的是上下文管理器,因此您无需显式调用.close() Try this:尝试这个:

from PyPDF2 import PdfReader, PdfWriter

dr = r"C:\GC"
ldr = dr + r"\12L.pdf"
writer = PdfWriter()

with open(ldr, "rb") as f:
  reader = PdfReader(f)
  page = reader.pages[0]
  writer.add_page(page)
  
  with open(dr + r"\new.pdf", "wb") as output_stream:
    writer.write(output_stream)

The code below opens a PDF file that has 12 pages, gets the first page and writes that page to a new PDF file.下面的代码打开一个有 12 页的 PDF 文件,获取第一页并将该页面写入一个新的 PDF 文件。

from PyPDF2 import PdfFileWriter, PdfFileReader

input_pdf = open('test.pdf', 'rb')
writer = PdfFileWriter()

reader = PdfFileReader(input_pdf)
in1 = writer.addPage(reader.getPage(0))
input_pdf.close()

output_pdf = open('new_test.pdf', 'wb')
writer.write(output_pdf)
output_pdf.close()
----------------------------------------
My system information
----------------------------------------
Platform:     Apple
OS Version:   macOS Catalina 10.15.7
Python Version: 3.9
PyPDF2 Version: 1.26.0
----------------------------------------

This is what works.这是有效的。 Not using the open() as f syntax wouldn't initalize the fields of the writer object.不使用 open() as f 语法不会初始化 writer 对象的字段。 Closing the file before the output being written would produce an error.在写入输出之前关闭文件会产生错误。 I guess the file must be open so the object can point to the instance.我想文件必须打开,这样对象才能指向实例。

from PyPDF2 import PdfFileReader, PdfFileWriter

dr = r"C:\GC"
ldr = dr + r"\pgSrc\12L.pdf"
rdr = dr + r"\pgSrc\12R.pdf"
r5 = dr + r"\pgSrc\pg5R.pdf"
writer = PdfFileWriter()
with open(ldr, "rb") as f:
  reader = PdfFileReader(f)
  page = reader.getPage(5)
  writer.addPage(page)
  with open(dr + r"\new.pdf", "wb") as outputStream:
    writer.write(outputStream)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM