【发布时间】:2018-01-23 00:33:18
【问题描述】:
我没有尝试修改 PDF,我只是尝试更改显示的文本
pdf.js 输出它在一堆 div 中读取的文本.textLayer > div,它还绘制了一个画布
我read here 认为在浏览器中查看和编辑 pdf 几乎是不可能的,但是...
由于 pdf.js 确实有 API,我的想法是“挂钩”到 pdf.js 并更改显示的文本(在我的情况下这已经足够了)
我能找到的最接近的是这个名为 getTextContent() 的函数,但没有注册回调的 AFAICS。
这甚至可能吗(不弄乱 pdf.js 本身)?如果有,怎么做?
编辑(3)
此代码会将 PDF 文本打印到控制台,但如何从那里继续对我来说是个谜。
'use strict';
// In production, the bundled pdf.js shall be used instead of SystemJS.
Promise.all([System.import('pdfjs/display/api'),
System.import('pdfjs/display/global'),
System.import('pdfjs/display/network'),
System.resolve('pdfjs/worker_loader')])
.then(function (modules)
{
var api = modules[0], global = modules[1];
// In production, change this to point to the built `pdf.worker.js` file.
global.PDFJS.workerSrc = modules[3];
// Fetch the PDF document from the URL using promises
let loadingTask = api.getDocument('cv.pdf');
loadingTask.onProgress = function (progressData) {
document.getElementById('progress').innerText = (progressData.loaded / progressData.total);
};
loadingTask.then(function (pdf)
{
// Fetch the page.
pdf.getPage(1).then(function (page)
{
var scale = 1.5;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions.
var canvas = document.getElementById('pdf-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// (Debug) Get PDF text content
page.getTextContent().then(function (textContent)
{
console.log(textContent);
});
// Render PDF page into canvas context.
var renderContext =
{
canvasContext: context,
viewport : viewport
};
page.render(renderContext);
});
});
});
编辑(2)
我试图弄乱的代码示例是viewer.js。当然这不是最简单的例子,但它是我能找到的在 DOM 中实现文本的最简单的例子
编辑(1)
我确实尝试过操作 DOM(特别是我之前提到的 .textLayer > div),但是 pdf.js 使用 DIV 和画布来发挥它的魔力,它不仅仅是文本,所以结果是文本 div 显示在顶部画布(或其他方式),请参阅:
【问题讨论】:
-
PDF.js “转换” pdf 为 html,如果文本确实是文本而不是文本图像,那么您应该能够直接操作 html
-
@JaromandaX 我编辑了我的帖子,但我被画布标签卡住了,如果我可以只使用 DOM 实现文本操作,那就太棒了
-
我觉得可以。它在文档完成加载后有一个承诺,并返回文档本身。您能否更新您的问题并提供一个完整的示例来说明您现在如何使用它?
-
@ChristosLytras:我为延迟道歉,我编辑了我的帖子以指向代码示例(我试图提出我自己的示例,但我悲惨地失败了:()
-
如果我理解正确,您想修改 PDF 文件中的文本。我会得到您要编辑的模板的 SVG 版本,更改 SVG 中的文本,然后将该 SVG 转换为 PDF - pdf.js 仅用于查看 pdf 文件而不是编辑其内容。
标签: javascript pdf pdf.js