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

Ask a Doctor Online: A Simple Guide to Virtual Healthcare

In our fast-paced world, the traditional trip to a doctor’s office isn’t always the most practical first step when health concerns arise. Whether you are dealing with…

Read More

Best Free Programming Ebooks to Learn Software Development

Learning modern technology can feel overwhelming when tutorials are scattered across dozens of websites. Many software developers, engineering students, and IT professionals struggle to find comprehensive study…

Read More

FinOps Training: Understanding Cost Visibility and Optimization

Introduction Moving workloads to the cloud can simplify infrastructure management, but it can also introduce a new financial challenge. Teams can provision resources whenever they need them,…

Read More

The Architecture of Intelligent DataOps: From Ingestion to Automation

Introduction Modern organizations run on distributed data ecosystems. On any given day, an enterprise environment ingests, transforms, and serves petabytes of records sourced from transactional databases, external…

Read More

Transforming Data Reliability: How DataOps Platforms Drive Proactive Monitoring

Introduction Traditional monitoring focuses almost entirely on infrastructure availability and binary job execution states—whether a server is up or whether a task completed. However, modern distributed environments…

Read More

Navigating Pipeline Risks with Expert DevSecOps Consulting Services

Software delivery moves faster today than at any point in technological history. High-performing engineering organizations push code changes to production multiple times a day using automated deployment…

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