How to Create a Split PDF Website through HTML and javascript

Step 1:- Create a page

Put where you want

<form id="form" class="btn rounded-top" style="background: -webkit-linear-gradient(to right, #c31432, #240b36);">
                        <div class="form-group">
                            <input type="file" name="" id="file" required accept=".pdf" class="btn rounded">
                        </div>
                        <div class="form-group " id="result"> </div>
                        <button class="btn">
                            Download PDF
                        </button>
                    </form>

Step 2:- Write a script code

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.min.js"></script>
<script src="https://unpkg.com/pdf-lib@1.3.0"></script>
<script src="https://unpkg.com/downloadjs@1.4.7"></script>

<script>
    const {
        PDFDocument
    } = PDFLib;

    let form = document.getElementById('form');
    let inputElement = document.getElementById('file');
    let selectedPages = [];
    let typedarray;

    form.addEventListener('submit', (e) => {
        e.preventDefault();

        for (var option of document.getElementById("pages").options) {
            if (option.selected) {
                selectedPages.push(option.value);
            }
        }

        console.log(selectedPages);

        extractSelectedPages(typedarray, selectedPages);
    });

    inputElement.onchange = function(event) {
        var file = event.target.files[0];

        var fileReader = new FileReader();

        fileReader.onload = function() {
            typedarray = new Uint8Array(this.result);

            const loadingTask = pdfjsLib.getDocument(typedarray);

            loadingTask.promise.then(async (pdf) => {
                let pages = [];

                for (let i = 0; i < pdf.numPages; i++) {
                    pages.push(i + 1);
                }
                let html = `
                        <label for="select pages">Select Pages of PDF You want to Split:</label>
                        <select id="pages" class="form-control" name="sites-list" size="${pdf.numPages}" multiple>
                        ${appendOption(pages)}
                        </select>`;

                document.getElementById('result').innerHTML = html;
                document.getElementById('result').style.display = "block";
            });
        };

        fileReader.readAsArrayBuffer(file);
    };

    function appendOption(pages) {
        let html = '';

        pages.forEach(page => {
            html += `
                    <option value="${page}">${page}</option>`;
        });

        return html;
    }

    window.onmousedown = function(e) {
        var el = e.target;
        if (
            el.tagName.toLowerCase() == "option" &&
            el.parentNode.hasAttribute("multiple")
        ) {
            e.preventDefault();

            if (el.hasAttribute("selected")) el.removeAttribute("selected");
            else el.setAttribute("selected", "");

            var select = el.parentNode.cloneNode(true);
            el.parentNode.parentNode.replaceChild(select, el.parentNode);
        }
    };

    async function extractSelectedPages(typedarray, selectedPages) {
        const pdfDoc = await PDFDocument.load(typedarray);
        const selectedPdfDoc = await PDFDocument.create();

        for (const pageNum of selectedPages) {
            const [copiedPage] = await selectedPdfDoc.copyPages(pdfDoc, [pageNum - 1]);
            selectedPdfDoc.addPage(copiedPage);
        }

        const pdfBytes = await selectedPdfDoc.save();

        download(pdfBytes, "SelectedPages.pdf", "application/pdf");
    }

    function download(data, filename, mimeType) {
        const blob = new Blob([data], {
            type: mimeType
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    }
</script>

Output:- Upload a pdf pages file and select which page you want to split

Then Select Fill will be downloaded

You see above there are two pages and in the download pdf, there is only one page.

Hopefully, This will help you …!!!

Related Posts

Real-World DataOps Implementations: A Simple Guide for Data Teams

Introduction Imagine a manager walks into a Monday meeting with a sales report. Another manager has a different report, and the numbers do not match. Both reports…

Read More

IVF Cost by Country: Comparing Fertility Treatment Expenses Worldwide

Fertility care often starts with a flood of questions. Where do I even begin? Which clinic can I trust? Why does every price look different? These worries…

Read More

Choosing Business Software: A Step-by-Step Comparison Guide

Every workplace runs on apps today, but choosing software that actually delivers has turned into a painful guessing game. Slick product sites promise the moon, yet companies…

Read More

Hyderabad Events This Weekend: Where to Go and What to Do

Hyderabad is always buzzing. Something fun is always happening somewhere. But here’s the problem. You often don’t know where. Your weekend slips away in confusion. Should you…

Read More

Simple Ways to Choose Modern Analytics Tools That Never Break

Introduction Most data teams have lived through this headache. A vendor shows off shiny charts, slick buttons, and fast dashboards during an afternoon sales demo. Your company…

Read More

Accredited Hospitals and Top Doctors for Hip Replacement Surgery Abroad

Hip pain steals your joy. It makes simple things hurt. Walking to the car hurts. Sleeping at night hurts too. When your hip wears down, getting help…

Read More
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x