Repository: Hopding/pdf-lib (ts)

Issue:
Semi-transparent PNG rendered opaque in PDF
Im trying to watermark a PDF with a semi-transparent PNG, but the semi-transparent portions are being rendered fully opaque in resulting PDF.

I can't find anything in the docs regarding transparency... any help would be greatly appreciated.

Pull request description:
Fix for #483 - Semi-transparent PNG rendered opaque in PDF
Fixes #483 and #473 

Patch:
diff --git a/src/utils/png.ts b/src/utils/png.ts
index b41e810..60aad74 100644
--- a/src/utils/png.ts
+++ b/src/utils/png.ts
@@ -58,7 +58,7 @@ export class PNG {
 
     this.rgbChannel = rgbChannel;
 
-    const hasAlphaValues = alphaChannel.some((a) => a < 1);
+    const hasAlphaValues = alphaChannel.some((a) => a < 255);
     if (hasAlphaValues) this.alphaChannel = alphaChannel;
 
     this.type = getImageType(upng.ctype);


Test patch:
diff --git a/tests/utils/png.spec.ts b/tests/utils/png.spec.ts
new file mode 100644
index 0000000..c0c4584
--- /dev/null
+++ b/tests/utils/png.spec.ts
@@ -0,0 +1,19 @@
+import {PNG} from 'src/utils/png';
+
+describe(`createSemiTransparentPNG`, () => {
+  it(`createsASemiTransparentPNG`, () => {
+    // This is the byteArray of a 1x1 dimension, semi transparent PNG generated like this:
+    // const ctx = c.getContext("2d");
+    // ctx.fillStyle = "rgba(255, 120, 80, 0.5)";
+    // ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
+    const input = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 24, 87, 99, 248, 95, 17, 208, 0, 0, 6, 137, 2, 72, 25, 58, 220, 62, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]);
+
+    const pngImage = PNG.load(input);
+
+    const expected = new Uint8Array([128]);
+
+    const actual = pngImage.alphaChannel;
+
+    expect(actual).toEqual(expected);
+  });
+});
\ No newline at end of file