[정보] IT정보&활용 2024. 11. 6. 12:10

PDF 나누기(split)

반응형

PDF 나누기.html
0.01MB

 

PDF를 두개로 나누는 html입니다.

 

pdf-lib (MIT 라이선스): https://github.com/Hopding/pdf-lib
pdf.js (Apache 2.0 라이선스): https://github.com/mozilla/pdf.js
위 라이브러리를 사용하였으며, chatGPT 등의 도움을 받아 실습 삼아 만들어 보았습니다.

 

아래는 html 스크립트 입니다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>PDF 나누기 (Split)</title>

    <!-- pdf-lib 및 pdf.js 라이브러리 로드 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.17.1/pdf-lib.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f3f4f6;
            margin: 0;
        }
        .container {
            width: 100%;
            max-width: 500px;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        h1 {
            font-size: 24px;
            color: #333;
            text-align: center;
        }
        p {
            font-size: 14px;
            color: #555;
            text-align: left;
        }
        input[type="file"] {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            font-size: 14px;
        }
        input[type="number"] {
            width: 50%;
            padding: 10px;
            margin: 10px 0;
            font-size: 14px;
        }
        #split-button {
            width: 100%;
            padding: 12px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 10px;
        }
        #split-button:hover {
            background-color: #218838;
        }
        footer {
            text-align: left;
            font-size: 12px;
            color: #777;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>PDF 나누기</h1>
        <p>PDF를 두 개의 파일로 나눌 수 있습니다.</p>
        <p>1. "파일 선택" 버튼을 눌러 나눌 PDF 파일을 선택하세요.</p>
        <input type="file" id="file-input" accept="application/pdf" />

        <p>2. 나눌 페이지 번호를 입력하세요. <br>
             &nbsp;&nbsp;&nbsp;&nbsp;(예: 3을 입력하면 1-3페이지와 4-마지막 페이지로 나뉩니다.)</p>
        <input type="number" id="split-page" min="1" />

        <p>3. "PDF 나누기" 버튼을 누르세요.</p>
        <button id="split-button">PDF 나누기</button>

        <footer>
            <p><strong>사용된 라이브러리</strong></p>
            <ul>
                <li>pdf-lib (MIT 라이선스): <a href="https://github.com/Hopding/pdf-lib">https://github.com/Hopding/pdf-lib</a></li>
                <li>pdf.js (Apache 2.0 라이선스): <a href="https://github.com/mozilla/pdf.js">https://github.com/mozilla/pdf.js</a></li>
            </ul>
        </footer>
    </div>

<script>
    const fileInput = document.getElementById('file-input');
    const splitPage = document.getElementById('split-page');
    const splitButton = document.getElementById('split-button');

    splitButton.addEventListener('click', async () => {
        if (!fileInput.files[0]) {
            alert('PDF 파일을 선택해주세요.');
            return;
        }

        const pageNumber = parseInt(splitPage.value);
        if (isNaN(pageNumber) || pageNumber < 1) {
            alert('유효한 페이지 번호를 입력해주세요.');
            return;
        }

        const file = fileInput.files[0];
        const arrayBuffer = await file.arrayBuffer();
        const pdfDoc = await PDFLib.PDFDocument.load(arrayBuffer);

        if (pageNumber >= pdfDoc.getPageCount()) {
            alert('입력한 페이지 번호가 PDF의 총 페이지 수보다 크거나 같습니다.');
            return;
        }

        // 첫 번째 PDF 생성 (1부터 pageNumber까지)
        const firstPdf = await PDFLib.PDFDocument.create();
        const firstPages = await firstPdf.copyPages(pdfDoc, Array.from({length: pageNumber}, (_, i) => i));
        firstPages.forEach(page => firstPdf.addPage(page));

        // 두 번째 PDF 생성 (pageNumber+1부터 끝까지)
        const secondPdf = await PDFLib.PDFDocument.create();
        const secondPages = await secondPdf.copyPages(pdfDoc, Array.from({length: pdfDoc.getPageCount() - pageNumber}, (_, i) => i + pageNumber));
        secondPages.forEach(page => secondPdf.addPage(page));

        // PDF 저장 및 다운로드
        const firstPdfBytes = await firstPdf.save();
        const secondPdfBytes = await secondPdf.save();

        downloadPdf(firstPdfBytes, 'split_first.pdf');
        downloadPdf(secondPdfBytes, 'split_second.pdf');
    });

    function downloadPdf(pdfBytes, fileName) {
        const blob = new Blob([pdfBytes], { type: 'application/pdf' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        a.click();
        URL.revokeObjectURL(url);
    }
</script>

</body>
</html>

반응형