【发布时间】:2015-02-20 16:44:28
【问题描述】:
我正在尝试使用PDFKit 创建一个 PDF 文件。我插入这样的图像:
var PDFDocument = require('pdfkit');
var doc = new PDFDocument();
doc.image(some_image_as_buffer);
它正在按预期工作。但是现在想要修剪图像,我找到了GraphicsMagick for node.js。但我遇到的问题是让它与 PDFKit 一起工作。 doc.image 需要一个文件名或一个缓冲区,但由于我已经有一个缓冲区,所以我想使用缓冲区(因为缓冲区直接来自数据库,所以任何地方都没有文件)。
修剪工作如下:
var gm = require('gm');
gm(some_image_as_buffer, 'image.png')
.trim()
.toBuffer(function(err, trimmed_image_buffer) {
// trimmed_image_buffer is correct,
// but I can't put it to the document like this:
doc.image(trimmed_image_buffer);
// beacause I don't know which page and/or position
// the doc is currently on, because of the asynchronous
// nature of this callback.
});
更新:
澄清:我希望能够在 PDFKit 的同步代码中使用异步修剪图像。 PDFKit 只能同步工作,gm 不提供同步接口。
UPDATE2:
var gm = require('gm');
gm(some_image_as_buffer, 'image.png')
.trim()
.toBuffer(function(err, trimmed_image_buffer) {
// trimmed_image_buffer is correct,
// but I can't put it to the document like this:
doc.image(trimmed_image_buffer);
// beacause I don't know which page and/or position
// the doc is currently on, because of the asynchronous
// nature of this callback.
});
doc.text('some text');
// is not guaranteed to run after image is inserted
// and a couple of hundred lines more
在此示例的最后一行之后,还有更多代码行向 PDF 添加内容,但我不想仅仅因为我需要异步函数而将所有内容(几百行)放在一个回调中操作图像。
有什么方法可以使这种操作同步吗?
【问题讨论】:
-
你的问题到底是什么?您想更好地控制异步流还是想使用与
doc.image不同的东西?如果是后者,那么如果没有进一步调查,我将无能为力,如果是第一个,那么一些基于 Promise 的解决方案应该可以很好地工作。 -
在pdfkit.org/docs/guide.pdf(第 5 页)中似乎有一种方法可以使用缓冲页面和缓冲页面范围来获取页码。我不确定您是否已经尝试过?
-
@artur grzesiak:我想要的是,我可以修剪图像并以某种同步方式将其添加到 pdf 中,因为 pdfkit 不能异步工作
-
@harryy000:这不是问题,我知道这是如何工作的,并使用这种技术来呈现页码,但我想要的是,使
gm的异步代码与同步代码一起工作pdfkit的代码 -
我希望我不是天真,但是为什么不使用 gm 模块完成所有图像的处理图像裁剪(将它们存储在一个数组中),然后开始与 pdk 相关的处理。
标签: node.js asynchronous node-pdfkit