Javascript PDF.js 插入图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11750821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:58:05  来源:igfitidea点击:

PDF.js Inserting Images

javascriptpdfcanvaspdf-generationpdf.js

提问by Danilo Valente

I've started using PDF.js, an excelent work, by the way.

顺便说一下,我已经开始使用PDF.js 了,这是一项出色的工作。

But now I want to insert an image (from a canvas element) on the pdf page. Here's my code:

但现在我想在 pdf 页面上插入一个图像(来自画布元素)。这是我的代码:

var image = myCanvas.getContext('2d').getImageData(0,0,400,300),
doc = new pdf();
doc.setProperties({
    title: fileName,
    author: 'VirtuaLab?',
    creator: 'pdf.js'
});
doc.addPage();
data = doc.output();

But I haven't found anything about inserting images on PDF.js pages.

但我还没有找到任何关于在 PDF.js 页面上插入图像的信息。

Maybe doc.image()or doc.addImage?

也许doc.image()doc.addImage

回答by Eugene

Disclaimer: I work for Bytescout

免责声明:我为Bytescout工作

Unfortunately PDF.js not working with images and that is why we developed PDF Generator SDK for Javascript(free for non-commercial use) where you can add image (from url or canvas) like this:

不幸的是,PDF.js 不能处理图像,这就是为什么我们为 Javascript开发了PDF Generator SDK(非商业用途免费),您可以在其中添加图像(来自 url 或 canvas),如下所示:

// load image from local file
pdf.imageLoadFromUrl('image1.jpg');
// place this mage at given X, Y coordinates on the page
pdf.imagePlace(20, 40);

Important to say that you can face limitation on image size as BytescoutPDF.js may consumes memory to process large image (this issue is caused by the memory limitations for javascript).

重要的是,您可能会面临图像大小的限制,因为 BytescoutPDF.js 可能会消耗内存来处理大图像(此问题是由 javascript 的内存限制引起的)。

However the script should work fine in case you just need to insert logo image or small picture into generated pdf.

但是,如果您只需要在生成的 pdf 中插入徽标图像或小图片,脚本应该可以正常工作。

UPDATE: the latest version of jsPDF(not to be confused with PDF.js) seems to work with images, see the sample on examples page.

更新:最新版本的jsPDF(不要与 PDF.js 混淆)似乎可以处理图像,请参阅示例页面上的示例

回答by Mendy

If I understand your question correctly you want to use an <img>instead of a <canvas>with pdf.js.

如果我正确理解您的问题,您想在pdf.js 中使用 a<img>而不是 a <canvas>

So here is my fix for this problem, insert the returned image in a canvas as normal, give the canvas a display: none;.

所以这是我对这个问题的修复,像往常一样将返回的图像插入画布,给画布一个display: none;.

Then use the .toDataURL()method of the canvas element to get a srcfor your img.

然后使用.toDataURL()canvas元素的方法src为你的img获取a 。

var canvas = document.getElementById("myCanves");
var img = document.getElementById("myImg");
img.src = canvas.toDataURL();

I hope this helps.

我希望这有帮助。