如何翻译PDF文件的内容,然后用翻译后的内容替换它?

问题描述 投票:0回答:1

我知道如何使用 Google Translate API。我想知道一件事,您是否有想法在不丢失文件格式的情况下翻译 PDF 文件。我曾尝试将 PDF 文件转换为 DOCX,然后翻译该文件,然后将其返回为 PDF,但由于许多 PHPWORD BUG,从 PDF 到 DOCX 的转换失败了。

这是我收到的问题和代码,用于请求将 PDF 转换为 DOCX。

<?php
require_once 'vendor/autoload.php';

// Create a new PDF reader
$reader = \PhpOffice\PhpWord\IOFactory::createReader('PDF');
$reader->setReadDataOnly(true);

// Load the PDF file
$phpWord = $reader->load('example.pdf');

// Save the DOCX file
$writer = $PhpOfficePhpWordIOFactory::createWriter($phpWord, 'Word2007');
$writer->save('example.docx');

echo 'PDF file converted to DOCX successfully!';

<?php
require_once 'vendor/autoload.php';
use PhpOffice\PhpWord\IOFactory as WordIOFactory;

// Convert PDF to text
exec('pdftotext -layout input.pdf output.txt');

// Load text file
$text = file_get_contents('output.txt');

// Create new DOCX file
$phpWord = new \PhpOffice\PhpWord();
$section = $phpWord->addSection();
$textrun = $section->addTextRun();
$textrun->addText($text);

// Save DOCX file
$objWriter = WordIOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('output.docx');

您知道如何翻译 PDF 文件而不需要转换为其他格式吗?

php pdf docx google-translate phpword
1个回答
0
投票

最近开发了一个文档翻译网站https://officetranslator.com/,翻译的方式和问题中提到的一样,只是使用不同的语言(node.js)。

翻译过程并不复杂:

  1. 从PDF文档中提取文本并获取其位置、字体、大小、颜色等属性信息。(使用pdf.js
  2. 根据属性确定哪些单词应分组。
  3. 翻译分组的文本。(使用ChatGPT
  4. 将翻译后的文本输出到文本的原始位置。(使用pdf-lib

但是翻译的质量取决于你第二步的执行情况。您可能需要:

  • 根据左右位置间距和字体大小判断是否合并到同一行。
  • 根据上下位置的间距来判断是否合并为多行。
  • 避免基于背景线(表格)的非法分割。
  • 根据文本是否为目录,动态处理长度。
  • 根据ChatGPT反馈判断是否为数学公式。
  • ...其他判断...

这部分处理比较复杂,可能需要较长的调试时间才能处理好。

© www.soinside.com 2019 - 2024. All rights reserved.