pdf word
unknown
javascript
a year ago
6.4 kB
15
Indexable
async autoCategorizeDocument() {
this.autoCategorizeLoading = true;
await this.$nextTick();
const roots = Object.values(this.tree).filter(item => item.parent === null);
const categories = {
financial: this.counter++,
tax: this.counter++,
legal: this.counter++,
other: this.counter++
};
for (const key in categories) {
this.tree[categories[key]] = {
id: categories[key],
name: key.charAt(0).toUpperCase() + key.slice(1),
type: 'folder',
parent: null,
children: [],
size: null
};
}
for (const root of roots) {
const file = this.tree[root.id].file;
try {
if (file && file.type === 'application/pdf') {
console.log(`Cutting PDF into 2 pages: ${root.name}`);
const newFile = await this.extractTwoPagePdf(file);
}else if (file.type ===
'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
console.log(`Extracting 2 sections from Word: ${root.name}`);
newFile = await this.extractTwoSectionWord(file);
}
await new Promise((resolve, reject) => {
$wire.upload(
'pdfFile',
newFile,
async (uploadedFilename) => {
const category = await $wire.classifyWithFile(root.name);
if (category === 'financial') {
this.tree[root.id].parent = categories.financial;
this.tree[categories.financial].children.push(root.id);
} else if (category === 'tax') {
this.tree[root.id].parent = categories.tax;
this.tree[categories.tax].children.push(root.id);
} else if (category === 'legal') {
this.tree[root.id].parent = categories.legal;
this.tree[categories.legal].children.push(root.id);
} else {
this.tree[root.id].parent = categories.other;
this.tree[categories.other].children.push(root.id);
}
resolve();
},
(error) => {
console.error('Upload failed:', error);
reject(error);
}
);
});
} catch (error) {
console.error(`Error processing file ${root.name}:`, error);
}
}
this.autoCategorizeLoading = false;
},
async extractTwoSectionWord(file) {
try {
const arrayBuffer = await file.arrayBuffer();
// Extract dengan format HTML untuk mendapatkan struktur yang lebih baik
const result = await mammoth.convertToHtml({ arrayBuffer: arrayBuffer });
const html = result.value;
// Parse HTML untuk mencari heading (h1, h2, h3, dll)
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Cari semua heading elements
const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
if (headings.length >= 2) {
// Ambil konten dari awal sampai heading ke-3 (2 section pertama)
const thirdHeading = headings[2];
const bodyContent = doc.body.innerHTML;
const thirdHeadingIndex = bodyContent.indexOf(thirdHeading.outerHTML);
const extractedHtml = bodyContent.substring(0, thirdHeadingIndex);
// Convert HTML kembali ke text
const tempDiv = document.createElement('div');
tempDiv.innerHTML = extractedHtml;
const extractedText = tempDiv.textContent || tempDiv.innerText || '';
const newFileName = file.name.replace(/\.(docx?)$/i, '_2sections.txt');
const newFile = new File([extractedText], newFileName, {
type: 'text/plain',
lastModified: Date.now()
});
return newFile;
} else {
// Fallback ke metode paragraf jika tidak ada cukup heading
const fullText = doc.body.textContent || doc.body.innerText || '';
const paragraphs = fullText.split('\n').filter(p => p.trim().length > 0);
const sectionsToTake = Math.min(paragraphs.length, Math.ceil(paragraphs.length / 2));
const extractedText = paragraphs.slice(0, sectionsToTake).join('\n\n');
const newFileName = file.name.replace(/\.(docx?)$/i, '_extracted.txt');
const newFile = new File([extractedText], newFileName, {
type: 'text/plain',
lastModified: Date.now()
});
return newFile;
}
} catch (error) {
console.error('Error extracting Word document:', error);
throw error;
}
},
async extractTwoPagePdf(file) {
try {
const arrayBuffer = await file.arrayBuffer();
const pdfDoc = await PDFLib.PDFDocument.load(arrayBuffer);
const newPdf = await PDFLib.PDFDocument.create();
const pagesToExtract = Math.min(pdfDoc.getPageCount(), 2);
const copiedPages = await newPdf.copyPages(pdfDoc, [...Array(pagesToExtract).keys()]);
copiedPages.forEach((page) => newPdf.addPage(page));
const newPdfBytes = await newPdf.save();
const newFile = new File([newPdfBytes], `preview_${file.name}`, { type: 'application/pdf' });
return newFile;
} catch (err) {
return file;
}
},Editor is loading...
Leave a Comment