Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active July 14, 2024 08:07
Show Gist options
  • Save daliborgogic/1bfa57ce0e0f3cdcd75bf8998442f775 to your computer and use it in GitHub Desktop.
Save daliborgogic/1bfa57ce0e0f3cdcd75bf8998442f775 to your computer and use it in GitHub Desktop.
Pdfmake on Cloudflare Workers. Total Upload: 2324.17 KiB / gzip: 983.62 KiB
{
"type": "module",
"scripts": {
"dev": "wrangler dev --port 3000 worker.mjs",
"deploy": "wrangler deploy"
},
"devDependencies": {
"pdfmake": "^0.3.0-beta.8",
"wrangler": "^3.63.1"
}
}
import pdfmake from 'pdfmake'
import pdfFonts from 'pdfmake/build/vfs_fonts'
pdfmake.vfs = pdfFonts
export default {
fetch: async request => {
const docDefinition = await request.json()
const pdf = pdfmake.createPdf(docDefinition)
const base64 = await pdf.getBase64()
const binStr = atob(base64)
const len = binStr.length
const arr = new Uint8Array(len)
for (let i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i)
}
const blob = new Blob([arr], { type: 'application/pdf' })
return new Response(blob)
}
}
name = 'pdfmake'
main = 'worker.mjs'
compatibility_date = "2024-07-01"
minify = true
@daliborgogic
Copy link
Author

daliborgogic commented Jul 13, 2024

pdfmake Virtual File System (VFS)

Total Upload: 1559.04 KiB / gzip: 566.71 KiB

import pdfmake from 'pdfmake'

let normal

export default {
  fetch: async request => {
    if (!normal) normal = await (await fetch('https://cdn.jsdelivr.net/npm/[email protected]/build/ttf/Hack-Regular.ttf')).arrayBuffer()
    let string = ''
    new Uint8Array(normal).forEach(byte => { string += String.fromCharCode(byte) })
    pdfmake.vfs = pdfmake.addVirtualFileSystem({
      'Hack-Regular.ttf': btoa(string)
    })
    pdfmake.fonts = {
      Hack: {
        normal: 'Hack-Regular.ttf'
      }
    }
    const docDefinition = await request.json()
    const pdf = pdfmake.createPdf(docDefinition)
    const base64 = await pdf.getBase64()
    const binStr = atob(base64)
    const len = binStr.length
    const arr = new Uint8Array(len)
    for (let i = 0; i < len; i++) {
      arr[i] = binStr.charCodeAt(i)
    }
    const blob = new Blob([arr], { type: 'application/pdf' })
    return new Response(blob)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment