Skip to content

Commit

Permalink
refactor: converge pdfkit (#2532)
Browse files Browse the repository at this point in the history
  • Loading branch information
diegomura authored Jan 20, 2024
1 parent a35b1ba commit 36c6ba3
Show file tree
Hide file tree
Showing 21 changed files with 843 additions and 204 deletions.
5 changes: 5 additions & 0 deletions .changeset/thin-windows-smell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@react-pdf/pdfkit': patch
---

refactor: converge pdfkit
11 changes: 11 additions & 0 deletions packages/pdfkit/src/abstract_reference.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
PDFAbstractReference - abstract class for PDF reference
*/

class PDFAbstractReference {
toString() {
throw new Error('Must be implemented by subclasses');
}
}

export default PDFAbstractReference;
10 changes: 5 additions & 5 deletions packages/pdfkit/src/data.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class Data {
constructor(data = []) {
this.pos = 0;
this.data = data;
this.pos = 0;
this.length = this.data.length;
}

Expand Down Expand Up @@ -42,12 +42,11 @@ class Data {

readInt32() {
const int = this.readUInt32();

if (int >= 0x80000000) {
return int - 0x100000000;
} else {
return int;
}

return int;
}

writeInt32(val) {
Expand All @@ -72,8 +71,9 @@ class Data {
const int = this.readUInt16();
if (int >= 0x8000) {
return int - 0x10000;
} else {
return int;
}
return int;
}

writeInt16(val) {
Expand Down
7 changes: 5 additions & 2 deletions packages/pdfkit/src/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import TextMixin from './mixins/text';
import ImagesMixin from './mixins/images';
import AnnotationsMixin from './mixins/annotations';
import OutlineMixin from './mixins/outline';
import MarkingsMixin from './mixins/markings';
import AcroFormMixin from './mixins/acroform';
import AttachmentsMixin from './mixins/attachments';
import MetadataMixin from './mixins/metadata';
import capitalize from './utils/capitalize';

class PDFDocument extends stream.Readable {
Expand Down Expand Up @@ -352,19 +354,20 @@ class PDFDocument extends stream.Readable {
endAcroForm() {}
}

const mixin = (methods) => {
const mixin = methods => {
Object.assign(PDFDocument.prototype, methods);
};

// Load mixins
mixin(MetadataMixin);
mixin(ColorMixin);
mixin(VectorMixin);
mixin(FontsMixin);
mixin(TextMixin);
mixin(ImagesMixin);
mixin(AnnotationsMixin);
mixin(OutlineMixin);
// mixin(MarkingsMixin);
mixin(MarkingsMixin);
mixin(AcroFormMixin);
mixin(AttachmentsMixin);

Expand Down
38 changes: 20 additions & 18 deletions packages/pdfkit/src/gradient.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class PDFGradient {
Domain: [0, 1],
C0: this.stops[i + 0][1],
C1: this.stops[i + 1][1],
N: 1,
N: 1
});

stops.push(fn);
Expand All @@ -90,7 +90,7 @@ class PDFGradient {
Domain: [0, 1],
Functions: stops,
Bounds: bounds,
Encode: encode,
Encode: encode
});

fn.end();
Expand All @@ -105,7 +105,7 @@ class PDFGradient {
Type: 'Pattern',
PatternType: 2,
Shading: shader,
Matrix: this.matrix.map(number),
Matrix: this.matrix.map(number)
});

pattern.end();
Expand All @@ -130,14 +130,14 @@ class PDFGradient {
Group: {
Type: 'Group',
S: 'Transparency',
CS: 'DeviceGray',
CS: 'DeviceGray'
},
Resources: {
ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'],
Pattern: {
Sh1: grad,
},
},
Sh1: grad
}
}
});

form.write('/Pattern cs /Sh1 scn');
Expand All @@ -148,8 +148,8 @@ class PDFGradient {
SMask: {
Type: 'Mask',
S: 'Luminosity',
G: form,
},
G: form
}
});

gstate.end();
Expand All @@ -165,12 +165,12 @@ class PDFGradient {
Resources: {
ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'],
Pattern: {
Sh1: pattern,
Sh1: pattern
},
ExtGState: {
Gs1: gstate,
},
},
Gs1: gstate
}
}
});

opacityPattern.write('/Gs1 gs /Pattern cs /Sh1 scn');
Expand All @@ -184,7 +184,7 @@ class PDFGradient {
return pattern;
}

apply(op) {
apply(stroke) {
// apply gradient transform to existing document ctm
const [m0, m1, m2, m3, m4, m5] = this.doc._ctm;
const [m11, m12, m21, m22, dx, dy] = this.transform;
Expand All @@ -194,12 +194,14 @@ class PDFGradient {
m0 * m21 + m2 * m22,
m1 * m21 + m3 * m22,
m0 * dx + m2 * dy + m4,
m1 * dx + m3 * dy + m5,
m1 * dx + m3 * dy + m5
];

if (!this.embedded || m.join(' ') !== this.matrix.join(' ')) {
this.embed(m);
}
this.doc._setColorSpace('Pattern', stroke);
const op = stroke ? 'SCN' : 'scn';
return this.doc.addContent(`/${this.id} ${op}`);
}
}
Expand All @@ -219,7 +221,7 @@ class PDFLinearGradient extends PDFGradient {
ColorSpace: this._colorSpace,
Coords: [this.x1, this.y1, this.x2, this.y2],
Function: fn,
Extend: [true, true],
Extend: [true, true]
});
}

Expand All @@ -246,7 +248,7 @@ class PDFRadialGradient extends PDFGradient {
ColorSpace: this._colorSpace,
Coords: [this.x1, this.y1, this.r1, this.x2, this.y2, this.r2],
Function: fn,
Extend: [true, true],
Extend: [true, true]
});
}

Expand All @@ -258,7 +260,7 @@ class PDFRadialGradient extends PDFGradient {
this.r1,
this.x2,
this.y2,
this.r2,
this.r2
);
}
}
Expand Down
23 changes: 14 additions & 9 deletions packages/pdfkit/src/image.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/*
PDFImage - embeds images in PDF documents
By Devon Govett
*/

import fs from 'fs';
import JPEG from './image/jpeg';
import PNG from './image/png';
Expand All @@ -10,24 +15,24 @@ class PDFImage {
} else if (src instanceof ArrayBuffer) {
data = Buffer.from(new Uint8Array(src));
} else {
let match = /^data:.+;base64,(.*)$/.exec(src);
if (match) {
let match;
if ((match = /^data:.+?;base64,(.*)$/.exec(src))) {
data = Buffer.from(match[1], 'base64');
} else if (!BROWSER) {
} else {
data = fs.readFileSync(src);
if (!data) return;
if (!data) {
return;
}
}
}

if (data[0] === 0xff && data[1] === 0xd8) {
return new JPEG(data, label);
}

if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') {
} else if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') {
return new PNG(data, label);
} else {
throw new Error('Unknown image format.');
}

throw new Error('Unknown image format.');
}
}

Expand Down
15 changes: 6 additions & 9 deletions packages/pdfkit/src/image/png.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ class PNGImage {
let dataDecoded = false;

this.document = document;
if (this.obj) {
return;
}

if (this.obj) return;

const { hasAlphaChannel } = this.image;
const hasAlphaChannel = this.image.hasAlphaChannel;
const isInterlaced = this.image.interlaceMethod === 1;

this.obj = this.document.ref({
Expand Down Expand Up @@ -117,14 +118,12 @@ class PNGImage {

// free memory
this.image = null;
this.imgData = null;
return (this.imgData = null);
}

splitAlphaChannel() {
return this.image.decodePixels(pixels => {
let a;
let p;

let a, p;
const colorCount = this.image.colors;
const pixelCount = this.width * this.height;
const imgData = Buffer.alloc(pixelCount * colorCount);
Expand All @@ -144,7 +143,6 @@ class PNGImage {
}

this.imgData = zlib.deflateSync(imgData);

this.alphaChannel = zlib.deflateSync(alphaChannel);
return this.finalize();
});
Expand All @@ -161,7 +159,6 @@ class PNGImage {
}

this.alphaChannel = zlib.deflateSync(alphaChannel);

return this.finalize();
});
}
Expand Down
37 changes: 37 additions & 0 deletions packages/pdfkit/src/metadata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class PDFMetadata {
constructor() {
this._metadata = `
<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
`;
}

_closeTags() {
this._metadata = this._metadata.concat(`
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>
`);
}

append(xml, newline = true) {
this._metadata = this._metadata.concat(xml);
if (newline) this._metadata = this._metadata.concat('\n');
}

getXML() {
return this._metadata;
}

getLength() {
return this._metadata.length;
}

end() {
this._closeTags();
this._metadata = this._metadata.trim();
}
}

export default PDFMetadata;
Loading

0 comments on commit 36c6ba3

Please sign in to comment.