n8n-nodes-extract-pdf
Version:
n8n node to extract text, images and tables from PDF with multilingual support, language detection and comprehensive test suite
179 lines • 7.75 kB
JavaScript
;
/**
* Module trích xuất và xử lý hình ảnh cho ExtractPdfNode
* @author AI Assistant
* @version 1.0.0
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractEmbeddedImages = exports.enhanceImage = exports.saveBase64Image = exports.extractImagesFromPdf = void 0;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const { convert: convertPdfToImages } = require('pdf-img-convert');
const sharp_1 = __importDefault(require("sharp"));
/**
* Trích xuất hình ảnh từ tệp PDF
* @param filePath Đường dẫn đến tệp PDF
* @param pageNumbers Mảng số trang cần trích xuất hình ảnh
* @param options Tùy chọn trích xuất
* @returns Danh sách hình ảnh đã trích xuất
*/
async function extractImagesFromPdf(filePath, pageNumbers, options = {}) {
try {
// Thiết lập các tùy chọn trích xuất
const extractionOptions = {
// Sử dụng số trang làm chỉ số 0-based
page_numbers: pageNumbers.map(p => p - 1),
// Thiết lập các tùy chọn khác
scale: options.scale || 2.0,
// Chất lượng và định dạng mặc định
quality: options.quality || 90,
format: options.format || 'png',
dpi: options.dpi || 300
};
// Thực hiện chuyển đổi PDF thành hình ảnh
const outputImages = await convertPdfToImages(filePath, extractionOptions);
// Tạo đối tượng hình ảnh cho từng trang
const images = outputImages.map((imageBuffer, index) => {
const page = pageNumbers[index];
// Chuyển đổi buffer thô thành chuỗi base64
let base64Data = '';
if (imageBuffer instanceof Uint8Array) {
base64Data = Buffer.from(imageBuffer).toString('base64');
}
else if (typeof imageBuffer === 'string') {
base64Data = Buffer.from(imageBuffer, 'binary').toString('base64');
}
const imageData = `data:image/png;base64,${base64Data}`;
return { page, imageData };
});
return images;
}
catch (error) {
throw new Error(`Failed to extract images from PDF: ${error.message}`);
}
}
exports.extractImagesFromPdf = extractImagesFromPdf;
/**
* Lưu hình ảnh từ base64 ra file
* @param base64Data Dữ liệu hình ảnh dạng base64
* @param outputPath Đường dẫn lưu file
* @returns Đường dẫn đến file đã lưu
*/
function saveBase64Image(base64Data, outputPath) {
try {
// Tách prefix data URL nếu có
const base64Content = base64Data.includes('base64,')
? base64Data.split('base64,')[1]
: base64Data;
// Chuyển đổi về buffer và lưu
const imageBuffer = Buffer.from(base64Content, 'base64');
fs.writeFileSync(outputPath, imageBuffer);
return outputPath;
}
catch (error) {
throw new Error(`Failed to save image: ${error.message}`);
}
}
exports.saveBase64Image = saveBase64Image;
/**
* Nâng cao chất lượng hình ảnh cho OCR
*/
async function enhanceImage(imagePath, options = {}) {
try {
const { contrast = 1.2, brightness = 1.1, sharpness = 1.5, denoise = true, format = 'png' } = options;
const outputPath = path.join(path.dirname(imagePath), `enhanced_${path.basename(imagePath, path.extname(imagePath))}.${format}`);
// Sử dụng type assertion để tránh lỗi TypeScript
let pipeline = (0, sharp_1.default)(imagePath)
.normalize()
// @ts-ignore - modulate is available in sharp but not in TypeScript definitions
.modulate({
brightness,
saturation: 1.2
})
.sharpen(sharpness);
if (contrast !== 1) {
// @ts-ignore - linear is available in sharp but not in TypeScript definitions
pipeline = pipeline.linear(contrast, -(128 * contrast) + 128);
}
if (denoise) {
pipeline = pipeline.median(3);
}
await pipeline.toFile(outputPath);
return outputPath;
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
throw new Error(`Failed to enhance image: ${errorMessage}`);
}
}
exports.enhanceImage = enhanceImage;
/**
* Phát hiện và trích xuất các hình ảnh nhúng trong trang PDF
* @param filePath Đường dẫn đến file PDF
* @param pageNumber Số trang cần trích xuất (bắt đầu từ 1)
* @returns Danh sách các hình ảnh đã trích xuất
*/
async function extractEmbeddedImages(filePath, pageNumber) {
try {
// Lưu ý: Trích xuất hình ảnh nhúng từ PDF yêu cầu thư viện nâng cao hơn
// như pdf.js hoặc pdfimages.
// Đây là bản triển khai đơn giản sử dụng chuyển đổi hoàn toàn trang thành hình ảnh
// Chuyển đổi trang thành hình ảnh
const outputImages = await convertPdfToImages(filePath, {
page_numbers: [pageNumber - 1],
scale: 2.0
});
if (!outputImages || outputImages.length === 0) {
return [];
}
// Lưu hình ảnh trang vào file tạm
const tempImagePath = path.join(os.tmpdir(), `page_${pageNumber}.png`);
let imageBuffer;
if (outputImages[0] instanceof Uint8Array) {
imageBuffer = Buffer.from(outputImages[0]);
}
else if (typeof outputImages[0] === 'string') {
imageBuffer = Buffer.from(outputImages[0], 'binary');
}
else {
imageBuffer = outputImages[0];
}
fs.writeFileSync(tempImagePath, imageBuffer);
// Trong phiên bản đơn giản này, chúng ta chỉ trả về hình ảnh trang
// Để trích xuất các hình ảnh riêng lẻ, cần triển khai thuật toán phát hiện vùng ảnh
return [tempImagePath];
}
catch (error) {
console.error(`Failed to extract embedded images: ${error.message}`);
return [];
}
}
exports.extractEmbeddedImages = extractEmbeddedImages;
//# sourceMappingURL=index.js.map