有没有一种简单的方法可以从 url 获取图像以放入 PDFKit pdf?
我有一个在浏览器中自动生成的 PDF。我想包含一张图片,我有一个 URL。问题是我正在浏览器中生成 PDF。由于我有可从互联网上获得的 URL,似乎应该有一种简单的方法可以将该图像转换为 PDFKit 可读的内容。
有没有办法让 Javascript 将图像 URL 转换为 PDFKit 可读的缓冲区?
我想要的是您希望以下命令执行的操作:
doc.image('http://upload.wikimedia.org/wikipedia/commons/0/0c/Cow_female_black_white.jpg')
提前致谢。我在网上找到的解决方案让您的服务器接受链接,并用缓冲区响应。这是唯一的方法吗?或者有没有一种没有 http 发布的所有浏览器内方式?
最佳答案
这是一个很老的问题,但我会添加我的注释,因为这是在 Google 上查找“pdfkit 浏览器图像”时的第一个建议。
我的解决方案基于数据 uri 选项 supported by PDFKit :
Just pass an image path, buffer, or data uri with base64 encoded data to the image method along with some optional arguments.
所以在快速浏览之后,我发现从图像 URL 获取数据 uri 的一般方法是使用 Canvas ,like in this post .放在一起 PDFKit's interactive browser demo :
function getDataUri(url, callback) {
var image = new Image();
image.crossOrigin = 'anonymous'
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
// // Get raw image data
// callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
// ... or get as Data URI
callback(canvas.toDataURL('image/png'));
};
image.src = url;
}
// Usage
getDataUri('http://pdfkit.org/docs/img/14.png', function(dataUri) {
// create a document and pipe to a blob
var doc = new PDFDocument();
var stream = doc.pipe(blobStream());
doc.image(dataUri, 150, 200, {
width: 300
});
// end and display the document in the iframe to the right
doc.end();
stream.on('finish', function() {
iframe.src = stream.toBlobURL('application/pdf');
});
});
关于javascript - 在浏览器中使用 PDFkit,从链接插入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26241650/