(html: string)
| 42 | }; |
| 43 | |
| 44 | export const htmlToPdfBuffer = (html: string): Promise<Buffer> => |
| 45 | new Promise((resolve, reject) => { |
| 46 | // compress:false keeps the content stream uncompressed. Pads are small |
| 47 | // enough that the size cost is negligible, and it lets ops greppable PDFs |
| 48 | // out of the box for accessibility / search-engine indexers that don't |
| 49 | // FlateDecode. |
| 50 | const doc = new PDFDocument({margin: 50, compress: false}); |
| 51 | const stream = new PassThrough(); |
| 52 | const chunks: Buffer[] = []; |
| 53 | stream.on('data', (c: Buffer) => chunks.push(c)); |
| 54 | stream.on('end', () => resolve(Buffer.concat(chunks))); |
| 55 | stream.on('error', reject); |
| 56 | doc.pipe(stream); |
| 57 | |
| 58 | const styleStack: InlineState[] = [{ |
| 59 | bold: false, italic: false, underline: false, strike: false, |
| 60 | }]; |
| 61 | const listType: ('ul' | 'ol' | null)[] = []; |
| 62 | const listIndex: number[] = []; |
| 63 | let pendingNewline = false; |
| 64 | let skipDepth = 0; |
| 65 | |
| 66 | const top = () => styleStack[styleStack.length - 1]; |
| 67 | |
| 68 | const applyFont = () => { |
| 69 | const s = top(); |
| 70 | let variant: string; |
| 71 | if (s.mono) { |
| 72 | variant = |
| 73 | s.bold && s.italic ? 'Courier-BoldOblique' : |
| 74 | s.bold ? 'Courier-Bold' : |
| 75 | s.italic ? 'Courier-Oblique' : |
| 76 | 'Courier'; |
| 77 | } else { |
| 78 | variant = |
| 79 | s.bold && s.italic ? 'Helvetica-BoldOblique' : |
| 80 | s.bold ? 'Helvetica-Bold' : |
| 81 | s.italic ? 'Helvetica-Oblique' : |
| 82 | 'Helvetica'; |
| 83 | } |
| 84 | doc.font(variant); |
| 85 | doc.fontSize(s.fontSize || 11); |
| 86 | }; |
| 87 | |
| 88 | // Track whether the current run started with an alignment override so |
| 89 | // we apply `align` exactly once per pdfkit text() call (pdfkit uses the |
| 90 | // align option of the first call in a continued run for the whole line). |
| 91 | let runStartedAligned = false; |
| 92 | |
| 93 | const writeText = (raw: string) => { |
| 94 | if (!raw) return; |
| 95 | if (pendingNewline) { |
| 96 | doc.moveDown(0.5); |
| 97 | pendingNewline = false; |
| 98 | } |
| 99 | const s = top(); |
| 100 | applyFont(); |
| 101 | const opts: any = {continued: true}; |
no test coverage detected