Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add with ... as ... Usage to PdfMerger() #1108

Closed
JianzhengLuo opened this issue Jul 14, 2022 · 5 comments · Fixed by #1193
Closed

Add with ... as ... Usage to PdfMerger() #1108

JianzhengLuo opened this issue Jul 14, 2022 · 5 comments · Fixed by #1193
Assignees

Comments

@JianzhengLuo
Copy link
Contributor

Explanation

As I need to call write() and close() in PdfMerger(), why not add __enter__ and __exit__ method to it so I can use it more elegantly.

Code Example

from PyPDF2 import PdfMerger

with PdfMerger(strict=False) as merger:
    for name in ["01.pdf", "02.pdf", "03.pdf", ...]:
        merger.append(name)
    merger.write("./output.pdf")
@MartinThoma
Copy link
Member

I like the idea! Do you want to create a pr?

@JianzhengLuo
Copy link
Contributor Author

I'd like so, but as a middle school student in China, I am still busy even in summer vacation, but I will try my BEST!

@JianzhengLuo
Copy link
Contributor Author

JianzhengLuo commented Jul 15, 2022

I noticed that write() is also necessary, and it has a parameter called fileobj, so I decided to add fileobj to the class initialization, now the code looks like this:

from PyPDF2 import PdfMerger

with PdfMerger(strict=False, fileobj="./output.pdf") as merger:
    for name in ["01.pdf", "02.pdf", "03.pdf", ...]:
        merger.append(name)

@JianzhengLuo
Copy link
Contributor Author

JianzhengLuo commented Jul 15, 2022

PdfWriter() also need to call write(), but it required stream, and the stream need to be writable, that's not as convenient as fileboj I thought, so I made it just like PdfMerger()----set fileobj when initializing.

It will be like:

from PyPDF2 import PdfWriter

with PdfWriter(fileobj="./output.pdf") as writer:
    ...  # Do what you like to do.

@MartinThoma
Copy link
Member

Please leave this open until the pr is merged

@MartinThoma MartinThoma reopened this Aug 3, 2022
MartinThoma added a commit that referenced this issue Aug 3, 2022
Closes #1108
Closes #1117

Full credit for this PR goes to JianzhengLuo

Co-authored-by: JianzhengLuo <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants