I am using python, and I want to combine two PDF pages into a single page. My purpose is to combine these two pages into one, not two PDFs. Is there any way to combine the two PDFs one by one? I don't want to merge these two. Without overlapping, is there any way to combine them?
Asked
Active
Viewed 2,741 times
5
-
Did you see that [topic](https://stackoverflow.com/questions/3444645/merge-pdf-files) to inspire you some solutions? – AvyWam Apr 13 '19 at 00:15
-
With what I have, I would perhaps turn them into images with python, then join them in Inkscape and then export it to a PDF file. – Harry Apr 07 '23 at 02:21
2 Answers
7
If I understood you correctly, you want to stitch two pages this way:
---------
| | |
| 1 | 2 |
| | |
---------
The pyPDF3 module allows you to do this.
from PyPDF3 import PdfFileWriter, PdfFileReader
from PyPDF3.pdf import PageObject
pdf_filenames = ["out_mitry.pdf", "out_cdg.pdf"]
input1 = PdfFileReader(open(pdf_filenames[0], "rb"), strict=False)
input2 = PdfFileReader(open(pdf_filenames[1], "rb"), strict=False)
page1 = input1.getPage(0)
page2 = input2.getPage(0)
total_width = page1.mediaBox.upperRight[0] + page2.mediaBox.upperRight[0]
total_height = max([page1.mediaBox.upperRight[1], page2.mediaBox.upperRight[1]])
new_page = PageObject.createBlankPage(None, total_width, total_height)
# Add first page at the 0,0 position
new_page.mergePage(page1)
# Add second page with moving along the axis x
new_page.mergeTranslatedPage(page2, page1.mediaBox.upperRight[0], 0)
output = PdfFileWriter()
output.addPage(new_page)
output.write(open("result.pdf", "wb"))

Alexander Nikitin
- 306
- 4
- 12
0
Use module PyPDF2 (https://pypi.org/project/PyPDF2/).
Example:
from PyPDF2 import PdfFileMerger
pdf_list = ['/path/to/first.pdf', '/path/to/second.pdf']
merger = PdfFileMerger()
for i in pdf_list:
merger.append(open(i, 'rb'))
with open('/path/to/save/new.pdf', 'wb') as fout:
merger.write(fout)

Sergey Rùdnev
- 54
- 3
-
1I have only one pdf. I need to combine two pages of a single pdf into one page – tins johny Apr 13 '19 at 01:09
-
what do you mean combine 2 pages of pdf into 1 page ?! I can see one reason why you would do that, which is if you have one empty page. I haven't tried this, but I think you can merge the content if you use the `from io import BytesIO` and then read the content of your pdfs, append it to a list, then write the bytes with `PdfWriter()` – lalam Apr 13 '19 at 13:01