Download an exported document

Q: How can trigger the download of an exported document?

A: PSPDFKit.Instance#exportPDF() resolves to an ArrayBuffer. In order for it to be downloadable, you need to create an object URL that can be assigned to an anchor element to trigger the download:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const buffer = await instance.exportPDF();
const supportsDownloadAttribute = HTMLAnchorElement.prototype.hasOwnProperty("download");
const blob = new Blob([buffer], { type: "application/pdf" });
if (navigator.msSaveOrOpenBlob) {
  navigator.msSaveOrOpenBlob(blob, "download.pdf");
} else if (!supportsDownloadAttribute) {
  const reader = new FileReader();
  reader.onloadend = function() {
	const dataUrl = reader.result;
	downloadPdf(dataUrl);
  };
  reader.readAsDataURL(blob);
} else {
  const objectUrl = window.URL.createObjectURL(blob);
  downloadPdf(objectUrl);
  window.URL.revokeObjectURL(objectUrl);
}
function downloadPdf(blob) {
  const a = document.createElement("a");
  a.href = blob;
  a.style.display = "none";
  a.download = "download.pdf";
  a.setAttribute("download", "download.pdf");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

This has been tested with PSPDFKit for Web 2020.5.1.