PDF 转换为 PNG 红色调在 macOS 上的 IronPDF for Node.js
This article was translated from English: Does it need improvement?
TranslatedView the article in English
在 macOS 上使用 IronPDF for Node.js 将 PDF 栅格化为 PNG 时,输出图像的颜色不正确。 在源 PDF 中看起来是黑色的 QR 代码在导出的 PNG 中呈现为红色。
macOS PDF 到图像栅格化管道中的颜色通道映射错误导致输出使用了错误的通道顺序,从而产生红色调。
解决方案
栅格化为 JPG 而不是 PNG,然后使用 sharp 将 JPG 转换为灰度 PNG。 这可以避免 macOS 的颜色通道映射问题。
安装 sharp:
npm install sharpnpm install sharpSHELL
栅格化为 JPG,然后转换为 PNG:
import { PdfDocument, ImageType } from "@ironsoftware/ironpdf";
import sharp from "sharp";
const pdf = await PdfDocument.fromFile("input.pdf");
const [jpgPage] = await pdf.rasterizeToImageBuffers({
fromPages: 0,
imageType: ImageType.JPG,
});
const pngBuffer = await sharp(jpgPage)
.flatten({ background: "#ffffff" })
.grayscale()
.threshold(160)
.png()
.toBuffer();根据 PDF 中 QR 代码的对比度,在 120 到 200 之间调整 threshold 值。 这个后处理步骤对于 QR 代码是安全的,因为它们是二进制的:白色背景上的黑色单元。 灰度转换对于 QR 代码没有任何损失。





