* Embed a PNG image into the document. * * PNG images are decoded and re-encoded with FlateDecode filter. * Alpha channels are separated into a soft mask (SMask) for * proper transparency support. * * @param bytes - PNG file bytes * @returns PDFImage that can be drawn with page.
(bytes: Uint8Array)
| 2168 | * ``` |
| 2169 | */ |
| 2170 | embedPng(bytes: Uint8Array): PDFImage { |
| 2171 | const data = parsePng(bytes); |
| 2172 | const { info, pixels, alpha } = data; |
| 2173 | |
| 2174 | // Compress pixel data with FlateDecode |
| 2175 | const compressedPixels = deflate(pixels); |
| 2176 | |
| 2177 | // Build XObject dictionary |
| 2178 | const dictEntries: Record<string, PdfObject> = { |
| 2179 | Type: PdfName.of("XObject"), |
| 2180 | Subtype: PdfName.of("Image"), |
| 2181 | Width: PdfNumber.of(info.width), |
| 2182 | Height: PdfNumber.of(info.height), |
| 2183 | ColorSpace: PdfName.of(info.colorSpace), |
| 2184 | BitsPerComponent: PdfNumber.of(info.bitDepth > 8 ? 8 : info.bitDepth), |
| 2185 | Filter: PdfName.of("FlateDecode"), |
| 2186 | }; |
| 2187 | |
| 2188 | // If there's alpha, create a soft mask |
| 2189 | if (alpha) { |
| 2190 | const compressedAlpha = deflate(alpha); |
| 2191 | |
| 2192 | const smaskStream = PdfStream.fromDict( |
| 2193 | { |
| 2194 | Type: PdfName.of("XObject"), |
| 2195 | Subtype: PdfName.of("Image"), |
| 2196 | Width: PdfNumber.of(info.width), |
| 2197 | Height: PdfNumber.of(info.height), |
| 2198 | ColorSpace: PdfName.of("DeviceGray"), |
| 2199 | BitsPerComponent: PdfNumber.of(8), |
| 2200 | Filter: PdfName.of("FlateDecode"), |
| 2201 | }, |
| 2202 | compressedAlpha, |
| 2203 | ); |
| 2204 | |
| 2205 | const smaskRef = this.register(smaskStream); |
| 2206 | dictEntries.SMask = smaskRef; |
| 2207 | } |
| 2208 | |
| 2209 | const stream = PdfStream.fromDict(dictEntries, compressedPixels); |
| 2210 | const ref = this.register(stream); |
| 2211 | |
| 2212 | return new PDFImage(ref, info.width, info.height); |
| 2213 | } |
| 2214 | |
| 2215 | // ───────────────────────────────────────────────────────────────────────────── |
| 2216 | // Low-Level Drawing API - Shadings |