pdfmake
Version:
Client/server side PDF printing in pure JavaScript
76 lines (65 loc) • 1.51 kB
JavaScript
class OutputDocument {
/**
* @param {Promise<object>} pdfDocumentPromise
*/
constructor(pdfDocumentPromise) {
this.pdfDocumentPromise = pdfDocumentPromise;
this.bufferPromise = null;
this.streamEnded = false;
this.streamEndListenerAttached = false;
}
/**
* @returns {Promise<object>}
*/
async getStream() {
const stream = await this.pdfDocumentPromise;
if (this.streamEnded) {
throw new Error('PDF stream has already been consumed.');
}
if (!this.streamEndListenerAttached) {
stream.once('end', () => {
this.streamEnded = true;
});
this.streamEndListenerAttached = true;
}
return stream;
}
/**
* @returns {Promise<Buffer>}
*/
getBuffer() {
const getBufferInternal = (async () => {
const stream = await this.getStream();
return new Promise((resolve, reject) => {
let chunks = [];
stream.on('data', chunk => {
chunks.push(chunk);
});
stream.on('end', () => {
resolve(Buffer.concat(chunks));
});
stream.on('error', reject);
stream.end();
});
});
if (this.bufferPromise === null) {
this.bufferPromise = getBufferInternal();
}
return this.bufferPromise;
}
/**
* @returns {Promise<string>}
*/
async getBase64() {
const buffer = await this.getBuffer();
return buffer.toString('base64');
}
/**
* @returns {Promise<string>}
*/
async getDataUrl() {
const data = await this.getBase64();
return 'data:application/pdf;base64,' + data;
}
}
export default OutputDocument;