Files
ihaleist/src/services/pdfDocumentReader.js
T

28 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {awaitWithAbort} from './abortable.js';
/** Read every requested page in order, retaining text/OCR provenance per page. */
export async function readPdfPages(doc, {maxPages=Infinity, ocrPage, forceOcr=false, onProgress, signal}={}) {
if (!(maxPages === Infinity || (Number.isInteger(maxPages) && maxPages > 0))) throw new Error('Geçersiz sayfa sınırı.');
signal?.throwIfAborted();
const pages = Math.min(doc.numPages,maxPages);
const results=[];
for(let number=1;number<=pages;number++) {
signal?.throwIfAborted();
onProgress?.({sayfa:number,toplam:pages});
const page=await awaitWithAbort(doc.getPage(number).then(page=>{if(signal?.aborted){page.cleanup?.();signal.throwIfAborted();}return page;}),signal);
try {
const content=await awaitWithAbort(page.getTextContent(),signal);
let text=content.items.map(item=>item.str + (item.hasEOL ? '\n' : ' ')).join('').trim();
let method='text';
if(ocrPage && (forceOcr || text.replace(/\s/g,'').length < 100)) {
try { text=await awaitWithAbort(ocrPage(page),signal); method='ocr'; }
catch { signal?.throwIfAborted(); throw new Error(`${number}. sayfada OCR tamamlanamadı. Okunabilir belgeyle yeniden deneyin.`); }
}
signal?.throwIfAborted();
results.push({page:number,text,method});
} finally { page.cleanup?.(); }
}
return {text:results.map(p=>p.text).join('\n\n').replace(/[ \t]+/g,' ').trim(),
pageCount:doc.numPages,usedPages:pages,pages:results,ocr:results.some(p=>p.method==='ocr'),
complete:pages===doc.numPages};
}