Reputation: 27
I need to split a pdf file in group of pages specified by the user. For example, I have a pdf with 20 pages, and I want to split it in groups of 5 pages. The output would be 4 pdfs of 5 pages each.
I read the pikepdf documentation and it can only split it in a single page, so I would have 20 single page pdfs.
pdf = Pdf.open('../tests/resources/fourpages.pdf')
for n, page in enumerate(pdf.pages):
dst = Pdf.new()
dst.pages.append(page)
dst.save(f'{n:02d}.pdf')
This is the code of the pikepdf documentation. I made it work, but as said before, the output is just single page pdfs. I tried changing it a bit with a nested while but it didn't work. I think it's weird that it doesn't allow to split in more than one page. Maybe there is something obvious that I'm not seeing. I thought about splitting it in single pages, and then merging it again by the desired amount of pages, but it doesn't seem very optimal.
For now I'm not allowed to use another library other than pikepdf. Is there a way to achieve this?
Thanks in advance.
Upvotes: 1
Views: 712
Reputation: 1
You can add several pages by not instantiate object every iteration.
example : if you want to split a 3 pages pdf in :
pdf1 with pages 1 and 2
pdf2 with page 3
dst = Pdf.new()
for n, page in enumerate(pdf.pages):
if n < 2:
dst.pages.append(page)
elif n == 2:
dst.save('pdf1.pdf')
# reinstanciate object to get only the 3d page
dst = Pdf.new()
dst.pages.append(page)
dst.save('pdf2.pdf')
Upvotes: 0