1. Data Analyst/1-1. Python

[python 실무 / 업무자동화] - 여러 pdf 파일 1개로 합치기

Data Analyst 2023. 10. 6. 03:36
728x90
반응형

 

 

 

매일 개별 pdf로 날라오는 여러 인보이스 파일을 하나의 pdf 파일로 보관하려고 한다. 이 글에서는 아래의 두 가지 케이스를 다룰 예정이다. 즉, 아래의 두 코드 모두 주어진 경로에 있는 PDF 파일을 합쳐서 새로운 파일로 저장하는 작업을 수행하는 코드이다.

 

1. 폴더 안의 일부 파일만 하나의 PDF로 합치기

2. 폴더 안의 모든 파일 하나의 PDF로 합치기

 

또한 다음편에서는 하나의 pdf파일을 excel, csv 파일로 변환하는 것까지 다룰 예정이다. 

 

 


Python을 사용해 여러 PDF 파일 한 개로 합치는 방법

 

 

1. 라이브러리 설치 (PyPDF2 )

 

 

 

 

2. 폴더 안의 일부 파일만 하나의 PDF로 합치기 (경로 찾는법)

2-1. 파이썬 파일경로 찾기

아래의 코드는 파이썬에서 파일의 경로를 찾는 코드이다. 

폴더 안에는 두 개의 파일이 있으며 각 경로가 결과값으로 잘 찾아졌다. 

 

 

 

(코드)

import os

def find_pdfs(directory):
    pdf_files = [f for f in os.listdir(directory) if f.endswith('.pdf')]
    return [os.path.join(directory, pdf) for pdf in pdf_files]

directory_path = "변환하려는 파일이 있는 경로 입력"
pdf_paths = find_pdfs(directory_path)

for pdf_path in pdf_paths:
    print(pdf_path)

 

 

 

2-2. 일부 PDF 파일 하나로 합치기

아래의 코드는 파이썬에서 여러 개의 PDF 파일들을 하나의 파일로 합치는 코드이다. 

위에서 추출된 파일 중 원하는 파일의 경로를 빨간 네모칸 안에 입력하면 된다. 위의 예시에서는 두 개밖에 없으므로 두 개 다 입력하겠다. 

 

 

 

(코드) : PyPDF2 라이브러리를 사용하여 PDF 파일을 합치는 코드

import PyPDF2
import os

def merge_pdfs(output_path, input_paths):
    pdf_merger = PyPDF2.PdfMerger()

    for path in input_paths:
        pdf_merger.append(path)

    with open(output_path, 'wb') as output_file:
        pdf_merger.write(output_file)


if __name__ == "__main__":
    # 입력할 PDF 파일들의 경로 리스트
    input_paths = ["파일1.pdf", 
                   "파일2.pdf"]

    # 출력될 PDF 파일의 경로 or 파일명
    output_path = "결과 파일명.pdf"

    # PDF 파일들을 합치는 함수 호출
    merge_pdfs(output_path, input_paths)

 

코드 설명:
- merge_pdfs 함수는 출력 경로 (output_path)와 합칠 PDF 파일들의 경로 리스트 (input_paths)를 인자로 받기
- PdfMerger 객체를 생성하고, 각각의 PDF 파일을 append 메서드로 추가
- write 메서드 합쳐진 PDF를 새로운 파일로 저장

 

 

 

 

 

 

 

 

3. 폴더 안의 모든 파일 하나의 PDF로 합치기 

아래의 코드는 파이썬에서 폴더 내 모든 PDF 파일들을 하나의 파일로 합치는 코드이다.

 

 

(코드): 특정 디렉토리에 있는 모든 PDF 파일을 찾아서 병합하는 코드

import PyPDF2
import os

def merge_pdfs(output_path, input_directory):
    pdf_merger = PyPDF2.PdfMerger()

    # 입력 디렉토리에서 모든 PDF 파일 찾기
    pdf_files = [f for f in os.listdir(input_directory) if f.endswith('.pdf')]
    pdf_files = [os.path.join(input_directory, pdf) for pdf in pdf_files]

    # PDF 파일들을 합치기
    for path in pdf_files:
        pdf_merger.append(path)

    # 결과 저장
    with open(output_path, 'wb') as output_file:
        pdf_merger.write(output_file)

if __name__ == "__main__":
    # 입력할 PDF 파일들이 있는 디렉토리 경로
    input_directory = "입력할 PDF 파일들이 있는 디렉토리 경로"

    # 출력될 PDF 파일의 경로 or 이름
    output_path = "결과 파일명.pdf"

    # PDF 파일들을 합치는 함수 호출
    merge_pdfs(output_path, input_directory)

 

 

코드설명:
- merge_pdfs 함수는 출력 경로 (output_path) 입력 디렉토리 (input_directory)를 인자로 받기
- os.listdir와 리스트 컴프리헨션을 사용하여 입력 디렉토리에서 모든 PDF 파일을 찾기
- 찾은 PDF 파일들의 경로를 PdfMerger 객체에 추가하고, 마지막으로 합친 결과를 새로운 파일로 저장

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형