1. 产品
  2.   OCR
  3.   JavaScript
  4.   Scribe.js
 
  

开源 OCR JavaScript API,用于创建可搜索的 PDF

领先的 JavaScript OCR 库,用于创建可搜索的 PDF,并执行 OCR(光学字符识别),从图像(PNG、JPEG)和 PDF 文件中提取文本。

Scribe.js 是什么?

在当今的数字世界中,大量有价值的信息被封存在图像中——错误信息的截图、文件的照片、演示文稿的幻灯片,甚至是带有巧妙文字的表情包。手动转录这些文本既繁琐又容易出错。光学字符识别(OCR)技术就在此时发挥作用,而 Scribe.js 提供了最友好的开发者集成方式之一。Scribe.js 是一个开源的 JavaScript 库,能够执行 OCR 并从图像和 PDF 文件中提取文本。与许多需要后端处理或外部 API 调用的 OCR 解决方案不同,Scribe.js 完全在客户端运行,让您对数据拥有完整控制权,并消除文本识别任务的服务器成本。

Scribe.js 是一个轻量级的 JavaScript 客户端,用于 Google Cloud Vision API。所有 OCR 操作直接在用户的浏览器或您的 Node.js 环境中进行,确保隐私并降低服务器基础设施成本。该库已支持多种功能,例如图像预处理、统一的图像工作流、自动检测、PDF 分层、过滤低置信度页面、缓存 OCR 引擎等。该库使用现代 JavaScript ESM(ECMAScript 模块)构建,使其能够轻松集成到当代 Web 开发工作流中,无需复杂的构建配置。这种以开发者为先的方式意味着您只需几行代码即可开始从文档中提取文本。

Previous Next

开始使用 Scribe.js

推荐的 Scribe.js 安装方式是使用 npm。请使用以下命令进行顺利安装

通过 npm 安装 Scribe.js

 npm install scribe.js-ocr 

您也可以手动安装;直接从 GitHub 仓库下载最新的发布文件。

从图像中进行文字识别

Scribe.js 库最基本的用例是从图像文件中提取文本。该库支持多种图像格式,并且可以一次性处理单个图像或多个图像的批量。以下是一个基本示例,演示在 JavaScript 应用中从图像 URL 提取文本。代码片段展示了 Scribe.js 提供的简洁 API。extractText 方法接受图像 URL 数组,并返回一个在识别文本后解析的 Promise。

如何通过 JavaScript 库从图像中提取文本?

import scribe from 'scribe.js-ocr';

// Extract text from a single image
scribe.extractText(['https://example.com/sample-image.png'])
  .then((result) => {
    console.log('Extracted text:', result);
  })
  .catch((error) => {
    console.error('OCR failed:', error);
  });

通过 JavaScript 创建可搜索的 PDF

Scribe.js 最强大的功能之一是能够向现有 PDF 文件添加不可见的文本层。此功能将基于图像的 PDF 转换为可搜索的文档,而不改变其视觉外观。向 PDF 添加文本层后,用户可以在文档中搜索特定词语或短语,选择并复制看似图像的文本,使用屏幕阅读器和辅助工具阅读扫描文档,使搜索引擎和文档管理系统能够对其进行索引,等等。

如何通过 JavaScript 库创建可搜索的 PDF 文档?

import scribe from 'scribe.js-ocr';

// Add searchable text layer to an image-based PDF
async function makeSearchablePDF(inputPdfUrl) {
  try {
    // First, perform OCR on the PDF
    const ocrResult = await scribe.extractText([inputPdfUrl]);
    
    // Then create a new PDF with the text layer embedded
    const searchablePdf = await scribe.createSearchablePDF(
      inputPdfUrl,
      ocrResult
    );
    
    // The resulting PDF maintains the original appearance
    // but now contains selectable, searchable text
    return searchablePdf;
  } catch (error) {
    console.error('Failed to create searchable PDF:', error);
    throw error;
  }
}

通过 JS 的高级文档文字检测

对于包含密集文本和复杂布局的文档图像(如扫描的书页或 PDF 导出),Scribe.js 库提供了“文档文本检测”功能。它提供了更丰富的信息,包括段落、单词和换行检测器,有助于保留原始文档的结构。这在布局和结构对源材料至关重要的应用中极为有用,例如处理表单、发票或多列布局。

如何在 JavaScript 应用中执行高级文本检测?

const Scribe = require('scribejs');
const serviceAccountKey = require('./path-to-your-key.json');
const scribe = new Scribe(serviceAccountKey);

const documentImageUrl = 'https://example.com/scanned-invoice.png';

// Use the `documentText` method for advanced detection
scribe.documentText(documentImageUrl)
  .then(fullTextAnnotation => {
    // The fullTextAnnotation object contains detailed data
    console.log('Full Document Text:');
    console.log(fullTextAnnotation.text); // The plain text of the entire document

    // You can also iterate through pages, blocks, paragraphs, and words
    fullTextAnnotation.pages.forEach(page => {
      page.blocks.forEach(block => {
        console.log('\nBlock Confidence:', block.confidence);
        block.paragraphs.forEach(paragraph => {
          console.log(paragraph.text);
        });
      });
    });
  })
  .catch(error => {
    console.error('Document OCR Error:', error);
  });

通过 JavaScript 批量处理多个文件

在实际应用中,软件专业人员经常需要同时处理多个文档。Scribe.js 开箱即支持批量处理,允许用户在 JavaScript 应用中一次性从多个图像或 PDF 中提取文本。以下示例演示了软件开发者如何使用 JavaScript 命令处理一批文档。

如何使用 JavaScript 库处理一批文档?

import scribe from 'scribe.js-ocr';

// Process multiple documents at once
async function batchProcess(fileUrls) {
  try {
    // Pass an array of URLs to process multiple files
    const results = await scribe.extractText(fileUrls);
    
    // Results are returned in the same order as input
    results.forEach((text, index) => {
      console.log(`Document ${index + 1} text:`, text);
    });
    
    return results;
  } catch (error) {
    console.error('Batch processing failed:', error);
    throw error;
  }
}

// Process a batch of documents
const documents = [
  'https://example.com/receipt1.jpg',
  'https://example.com/receipt2.jpg',
  'https://example.com/invoice.pdf'
];

batchProcess(documents)
  .then(allText => {
    console.log('All documents processed successfully');
  });
 中国人