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

How DataOps and MLOps Work Together for Scalable AI Pipelines

Introduction In the current landscape of artificial intelligence, building a model is only the beginning. The real challenge for enterprise teams lies in the transition from a…

Read More

Evaluating Modern DataOps Tools Across Business Analytics Infrastructure

Introduction Managing data pipelines used to be a straightforward task for single analytics teams. Today, data ecosystems are complex, fast-moving, and frequently fragmented across multiple cloud environments….

Read More

Essential Guide To Choosing And Mastering Modern Enterprise DataOps Platforms

Introduction DataOps platforms represent the modern standard for orchestrating the entire data lifecycle, from initial ingestion to final analytics delivery. By applying agile engineering and automated DevOps…

Read More

Exploring Financial Operations Workflows in Modern Cloud Environments

Introduction The Certified FinOps Professional is the definitive benchmark for experts looking to master the intersection of finance, engineering, and business. As organizations transition from traditional data…

Read More

Strategic Certified FinOps Engineer integrates governance with cloud operations

Introduction The shift to cloud computing has fundamentally altered how businesses manage infrastructure, but it has also introduced significant financial complexities that many engineering teams struggle to…

Read More

Certified FinOps Manager Knowledge for Cloud Financial Governance

Introduction The shift toward cloud-native infrastructure has brought undeniable speed, but it has also introduced significant financial complexity. The Certified FinOps Manager is a professional designation designed…

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