【问题标题】:Using rotate for images leads to blank pdf with pdfkit对图像使用旋转会导致带有 pdfkit 的空白 pdf
【发布时间】:2026-01-29 02:50:02
【问题描述】:

我已经直接在存储库上提出了这个问题,但根据我的经验,SO 更具反应性。

你好,

我正在尝试使用 pdfkit 从照片创建 pdf。 根据图像是横向还是纵向模式,我想翻转图像。

这基本上意味着以下(在打字稿中):

function toPostscriptPoint(mm: number) {
    return mm * 2.8346456693;
}
const document = new PDFDocument({
    size: [toPostscriptPoint(156), toPostscriptPoint(106)],
});

document.pipe(fs.createWriteStream('output.pdf'));

document.save();
document.rotate(90);
document.image(
            'photos/sample.jpeg',
            { width: toPostscriptPoint(150), fit: [toPostscriptPoint(150), toPostscriptPoint(100)] });
    document.restore();

document.end();

不过,pdf 呈现完全白色。但是我确实看到发生了一些事情,因为 pdf 具有输入图像的大小。

不支持图像旋转吗?可能的替代方案是什么?我想避免在将文件放入 pdf 之前重写我的文件。

谢谢

【问题讨论】:

    标签: node.js typescript pdfkit node-pdfkit


    【解决方案1】:

    好的,经过调查,我可以回答我自己的问题了:)。

    由于文件的大小,我可以看到图像在 pdf 中,所以我更深入地研究。

    发生的事情是图像被渲染出视口。这是由于多方面的原因: * 默认情况下,pdfkit 中旋转后的页面原点是页面中心! (有关更多信息,请参阅the doc) * 原点与变换一起旋转。 * image 方法中的x和y实际上是倒置的。

    所以在所有这些都正确之后,下面的代码会按预期显示图像:

    function toPostscriptPoint(mm: number) {
        return mm * 2.8346456693;
    }
    const document = new PDFDocument({
        size: [toPostscriptPoint(156), toPostscriptPoint(106)],
    });
    
    document.pipe(fs.createWriteStream('output.pdf'));
    
    document.save();
    document.rotate(90, {origin : [0, 0]});
    document.image(
                'photos/sample.jpeg',
                toPostscriptPoint(0),
                toPostscriptPoint(-150),
                { width: toPostscriptPoint(150), height: toPostscriptPoint(100) });
        document.restore();
    
    document.end();
    

    注意:

    • 旋转中的原点参数
    • toPostscriptPoint(-150)其实考虑了原点的位置,对应X轴。

    希望以后能帮到一些人:)。

    【讨论】: