컴퓨터/Python

python 여러개의 pdf들의 1페이지만 합쳐서 새로운 pdf파일 만들기

풍경소리^^ 2024. 5. 21. 15:00

PyPDF2 설치

pip install PyPDF2

 

파일 pdf1page.py

import os
from PyPDF2 import PdfReader, PdfWriter

# 작업 디렉터리 설정
pdf_dir = r'G:\회사\임시\일본출장\일본출장2024\항공권\240527출발_43명단체항공권'
output_file_path = os.path.join(pdf_dir, 'all.pdf')

# PDF 파일 작성기 생성
pdf_writer = PdfWriter()

# 폴더 내 모든 PDF 파일 처리
for filename in os.listdir(pdf_dir):
    if filename.endswith('.pdf'):
        file_path = os.path.join(pdf_dir, filename)
        
        # PDF 파일 열기
        with open(file_path, 'rb') as pdf_file:
            pdf_reader = PdfReader(pdf_file)
            
            # 첫 페이지 가져오기
            if len(pdf_reader.pages) > 0:
                first_page = pdf_reader.pages[0]
                pdf_writer.add_page(first_page)

# 첫 페이지들을 결합하여 새로운 PDF 파일 생성
with open(output_file_path, 'wb') as output_pdf_file:
    pdf_writer.write(output_pdf_file)

print(f'작업이 완료되었습니다. 파일 경로: {output_file_path}')