pdfkit create

Create a PDF in the browser using pdfKit.

by Bryan McIntosh

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/pdfkit.standalone.js"></script>

<script src="https://github.com/devongovett/blob-stream/releases/download/v0.1.3/blob-stream.js"></script>
<div>PDF Output <button onclick="download()">Download</button></div>

JavaScript

//Helpful tips here: https://codepen.io/blikblum/pen/gJNWMg?editors=1010
let blob;
let doc;
let txtTitle = "Da Title"; //Future ternary
let txtAuthor = "Da Author"; //Future ternary
let txtNotes = "I have lots of notes that I want to include in this map but I'm not sure how many characters I can put before I get to the end of the area that could be filled by such information. Maybe if I type lots of information I can tell how long this might be able to get to before I reach the limits. Or maybe this will get too long and I will need to come up with a different solution. But I could keep going juust to see when this actually cuts off and no longer produces any outputs on the screen. I have lots of notes that I want to include in this map but I'm not sure how many characters I can put* before I get to the end of t";
//txtNotes = "I have lots of notes that I want to include in this map but this is all.";
//txtNotes = "";

const dateOptions = {
  year: "numeric",
  month: "short",
  day: "2-digit",
};
const date = new Date();
let txtDate = date.toLocaleString("en-US", dateOptions);
let txtDateAuth = `Date: ${txtDate}\nAuthor: ${txtAuthor}`

function generatePDF() {
  doc = new window.PDFDocument({
    pdfVersion: '1.6',
    lang: 'en-US',
    tagged: true,
    displayTitle: true,
    info: {
      Title: txtTitle,
      Author: txtTitle
    },
    size: "letter", //w,h: 792,612 ;  //590 is right edge of map
    layout: "landscape",
    margin: 2
  });
  const stream = doc.pipe(blobStream());

  // Initialise document logical structure
  var struct = doc.struct('Document');
  doc.addStructure(struct);

  //Add outline: Thick border
  doc.lineWidth(3);
  doc.rect(15, 15, doc.page.width - 30, doc.page.height - 30);
  doc.stroke();
  //Add outline: thin border
  doc.lineWidth(1);
  doc.rect(20, 20, doc.page.width - 40, doc.page.height - 40);
  doc.stroke();
  //Add outline: Map area
  doc.lineWidth(1);
  doc.rect(30, 30, 560, doc.page.height - 60);
  doc.stroke();

  //...