Загрузка...

Help with search function

Thread in Node.js created by AntiSempai Oct 4, 2023. (bumped Oct 4, 2023) 182 views

  1. AntiSempai
    AntiSempai Topic starter Oct 4, 2023 guest я слежу за тобой 34 May 13, 2022
    Пищу PDF-Viewer на React App, нужно чтобы кнопка поиска находила текст который введен в поисковую строку
    [IMG][IMG]

    Она должна искать и выделять его по сути как F3:
    [IMG]



    Вот сам код:
    App.js:
    JS
    import React, { useState, useRef } from 'react'
    import ReactDOM from 'react-dom'
    import pdfjs from 'pdfjs-dist/webpack' // Import PDF.js at the top
    import './App.css'

    function App() {
    const [pdfURL, setPdfURL] = useState(null)
    const inputTextRef = useRef(null)

    const searchFunction = text => {
    console.log('Search Text:', text) // Check the input text
    const information = document.querySelectorAll('.searchDiv')
    console.log('Elements:', information) // Check the selected elements
    information.forEach(element => {
    if (element.textContent.includes(text)) {
    console.log('Matched Element:', element) // Check matched elements
    element.classList.add('animationElement')
    setTimeout(() => {
    element.classList.remove('animationElement')
    }, 2000)
    }
    })
    }

    const openPdf = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'application/pdf'

    input.addEventListener('change', async event => {
    const file = event.target.files[0]

    if (file) {
    const fileURL = URL.createObjectURL(file)
    setPdfURL(fileURL)
    }
    })

    input.click()
    }

    const searchPdf = async text => {
    if (!pdfURL) {
    alert('Please open a PDF first.')
    return
    }

    try {
    const pdf = await pdfjs.getDocument(pdfURL).promise
    const maxPages = pdf.numPages

    for (let pageNum = 1; pageNum <= maxPages; pageNum++) {
    const page = await pdf.getPage(pageNum)
    const pageText = await page.getTextContent()

    pageText.items.forEach(item => {
    const itemText = item.str
    if (itemText.includes(text)) {
    // Handle the matched text within the PDF, e.g., highlight or alert
    console.log('Match found on page', pageNum)
    }
    })
    }
    } catch (error) {
    console.error('Error searching PDF:', error)
    }
    }

    const downloadBasicPdf = () => {
    alert('In development')
    }

    const openBasicPdf = () => {
    alert('In development')
    }

    const handleSubmit = e => {
    e.preventDefault()
    const searchText = inputTextRef.current.value
    searchFunction(searchText) // Search on the webpage content
    searchPdf(searchText) // Search within the PDF
    }

    return (
    <div className='App'>
    <header className='App-header'>
    <h1>PDF View</h1>
    <div className='buttons-container'>
    <button onClick={openPdf}>Open PDF</button>
    <button onClick={downloadBasicPdf}>Download Basic PDF</button>
    <button onClick={openBasicPdf}>Open Basic PDF</button>
    <form onSubmit={handleSubmit}>
    <input type='text' ref={inputTextRef} />
    <input type='submit' value='search' />
    </form>
    </div>
    </header>
    {pdfURL && (
    <iframe src={pdfURL} title='PDF Viewer' width='100%' height='1250px' />
    )}
    </div>
    )
    }

    ReactDOM.render(<App />, document.getElementById('root'))
    export default App
    App.css:
    CSS
    @import '@react-pdf-viewer/core/lib/styles/index.css';


    .App {
    text-align: center;
    }

    /* Header styles */
    .App-header {
    background-color: #282c34;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: calc(10px + 2vmin);
    color: white;
    }

    .buttons-container {
    margin-top: 20px;
    }

    button {
    background-color: #61dafb;
    color: white;
    border: none;
    padding: 10px 20px;
    margin: 5px;
    cursor: pointer;
    }


    button:hover {
    background-color: #45aaf2;
    }

     
  2. 0w0
    0w0 Oct 4, 2023 0x5F3759DF 332 Dec 27, 2017
    У тебя код для устаревшей версии библиотеки pdf.js. Потыкал код, теперь работает:

    JS
    import React, { useState, useRef } from 'react'
    import ReactDOM from 'react-dom'
    import pdfjs from 'pdfjs-dist' // Import PDF.js at the top

    import './App.css'

    function App() {
    const [pdfURL, setPdfURL] = useState(null)
    const inputTextRef = useRef(null)
    pdfjsLib.GlobalWorkerOptions.workerSrc = '../../node_modules/pdfjs-dist/build/pdf.worker.js';


    const searchFunction = text => {
    console.log('Search Text:', text) // Check the input text
    const information = document.querySelectorAll('.searchDiv')
    console.log('Elements:', information) // Check the selected elements
    information.forEach(element => {
    if (element.textContent.includes(text)) {
    console.log('Matched Element:', element) // Check matched elements
    element.classList.add('animationElement')
    setTimeout(() => {
    element.classList.remove('animationElement')
    }, 2000)
    }
    })
    }

    const openPdf = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'application/pdf'

    input.addEventListener('change', async event => {
    const file = event.target.files[0]

    if (file) {
    const fileURL = URL.createObjectURL(file)
    setPdfURL(fileURL)
    }
    })

    input.click()
    }

    const searchPdf = async text => {
    if (!pdfURL) {
    alert('Please open a PDF first.')
    return
    }

    try {
    const pdf = await pdfjsLib.getDocument(pdfURL).promise
    const maxPages = pdf.numPages

    for (let pageNum = 1; pageNum <= maxPages; pageNum++) {
    const page = await pdf.getPage(pageNum)
    const pageText = await page.getTextContent()

    pageText.items.forEach(item => {
    const itemText = item.str
    if (itemText.includes(text)) {
    // Handle the matched text within the PDF, e.g., highlight or alert
    console.log('Match found on page', pageNum)
    }
    })
    }
    } catch (error) {
    console.error('Error searching PDF:', error)
    }
    }

    const downloadBasicPdf = () => {
    alert('In development')
    }

    const openBasicPdf = () => {
    alert('In development')
    }

    const handleSubmit = e => {
    e.preventDefault()
    const searchText = inputTextRef.current.value
    searchFunction(searchText) // Search on the webpage content
    searchPdf(searchText) // Search within the PDF
    }

    return (
    <div className='App'>
    <header className='App-header'>
    <h1>PDF View</h1>
    <div className='buttons-container'>
    <button onClick={openPdf}>Open PDF</button>
    <button onClick={downloadBasicPdf}>Download Basic PDF</button>
    <button onClick={openBasicPdf}>Open Basic PDF</button>
    <form onSubmit={handleSubmit}>
    <input type='text' ref={inputTextRef} />
    <input type='submit' value='search' />
    </form>
    </div>
    </header>
    {pdfURL && (
    <iframe src={pdfURL} title='PDF Viewer' width='100%' height='1250px' />
    )}
    </div>
    )
    }

    ReactDOM.render(<App />, document.getElementById('root'))
    export default App
    [IMG]
    Ссылка на гайд по обновлённой либе
     
    1. AntiSempai Topic starter
      0w0, Лучший. Спасибо
    2. AntiSempai Topic starter
      0w0, подскажите, чем заменить iframe?
    3. 0w0
      AntiSempai, В примере на GitHub, что я выше кинул, используется canvas
Loading...
Top