我想在我的项目中使用 Google 翻译。我与 Google 完成了所有手续。我也有 API key 。有了这个键,我可以轻松地用 JavaScript 翻译任何单词。但是如何像我们在谷歌翻译网站上那样翻译PDF文件呢?我发现这样一件事:
http://translate.google.com/translate?hl=fr&sl=auto&tl=en&u=http://www.example.com/PDF.pdf
但是在这里我无法使用我的 key ,因此翻译需要花费很多时间。所以我想使用我的 Key 翻译 PDF 文件。请帮帮我。 我的做法是这样的:
1. One html page I have.
2. One browse button for pdf
3. Upload the file
4. Transalte the pdf with Google API and show in the html page.
我在其中搜索了此 pdf 翻译,但没有找到任何内容。请帮帮我。
最佳答案
TL:DR:使用 headless 浏览器从 Google 的 PDF 翻译服务呈现 PDF。
PDF 是一种复杂的格式,可以包含许多文本组件。为了翻译它,我将描述从简单到更高级的解决方案。
翻译原始文本
如果您只需要翻译而不需要视觉输出,您可以提取文本并将其提供给 Google 翻译。
由于您没有提供有关您的项目的信息(语言、环境等),我会将您重定向到此 thread on how to extract text
翻译所有文本
如果您需要从 PDF 中的所有内容中获取文本,那是相当困难的。为了避免(部分)头痛,您可以将 PDF 转换为图像(使用 imagemagick 工具或类似工具),然后您有三个选择:
- 对图像中的文本进行 OCR,然后将其提供给 Google,但您又会丢失原始形式。
OCR 文本,但保存位置(有些库可以做到这一点,因为您没有指定项目信息,请参阅这些链接: #1 、 #2 、 #3 、 #4 )。
然后用google api翻译它,并将结果写入图像。为了获得最佳效果,您需要考虑文本字体、颜色和背景颜色。相当困难,但可行。
使用 google translate image service 翻译图像。不幸的是,此功能在公共(public) API 中不可用,因此除非进行一些逆向工程,否则这是不可能的。
使用 Google 的 PDF 翻译服务进行翻译
您通过使用翻译网站提供的解决方案可以很容易地实现自动化。它之所以这么长,是因为它是一个繁重的过程,而且您可能无法击败 Google。
使用 headless 浏览器,您可以获取带有 pdf 的翻译页面,然后观察翻译的内容位于 iframe 中,获取该 iframe 并最终打印为 PDF。
这是一个使用 SlimerJS 的简短示例(应与 Phantomjs 兼容)
var page = require("webpage").create();
// here you may want to setup page size and options
// get the page
page.open('https://translate.google.fr/translate?hl=fr&sl=en&u=http://example.com/pdf-sample.pdf', function(status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
// find the iframe with querySelector
var iframe_src = page.evaluate(function() {
return document.querySelector('#contentframe').querySelector('iframe').src;
});
console.log('Found iframe: ' + iframe_src);
// render the iframe
page.open(iframe_src, function(status) {
// wait a bit for javascript to translate
// this can be optimized to be triggered in javascript when translation is done
setTimeout(function() {
// print the page into PDF
page.render('/tmp/test.pdf', { format: 'pdf' });
phantom.exit(0);
}, 2000);
});
}
});
提供此文件:http://www.cbu.edu.zm/downloads/pdf-sample.pdf
它产生这个结果(翻译成法语):(我发布了一个屏幕截图,因为我无法嵌入 PDF ;))
关于file - 使用 Google Translate API 翻译 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30229437/