Published on

Tiptap Output: Save as JSON, HTML, Text, or PDF

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

Export Tiptap Content as JSON, HTML, Text, or PDF

Utility Function for Downloads

...
const onDownload = (blob: Blob, filename: string) => {
  const userFilename = prompt("Enter a filename:", filename);
  if (!userFilename) return;
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = userFilename;
  a.click();
  URL.revokeObjectURL(url);
};

const onSaveJSON = () => {
  if (!editor) return;
  const content = editor.getJSON();
  const blob = new Blob([JSON.stringify(content)], {
    type: "application/json",
  });
  onDownload(blob, "document.json");
};

const onSaveHTML = () => {
  if (!editor) return;
  const content = editor.getHTML();
  const blob = new Blob([content], {
    type: "text/html",
  });
  onDownload(blob, "document.html");
};

const onSaveText = () => {
  if (!editor) return;
  const content = editor.getText();
  const blob = new Blob([content], {
    type: "text/plain",
  });
  onDownload(blob, "document.txt");
};
...
<MenubarMenu>
    <MenubarTrigger className="text-base font-normal rounded-sm hover:bg-muted h-auto p-1">
      <span>File</span>
    </MenubarTrigger>
    <MenubarContent className="print:hidden">
      <MenubarSub>
        <MenubarSubTrigger>
          <SaveIcon className="size-4 mr-2" />
          <span>Save</span>
        </MenubarSubTrigger>
        <MenubarSubContent>
          <MenubarItem onClick={onSaveJSON}>
            <FileJson2Icon className="size-4 mr-2" />
            <span>JSON</span>
          </MenubarItem>
          <MenubarItem onClick={onSaveHTML}>
            <GlobeIcon className="size-4 mr-2" />
            <span>HTML</span>
          </MenubarItem>
          <MenubarItem onClick={() => window.print()}>
            <BsFilePdf className="size-4 mr-2" />
            <span>PDF</span>
          </MenubarItem>
          <MenubarItem onClick={onSaveText}>
            <FileTextIcon className="size-4 mr-2" />
            <span>Text</span>
          </MenubarItem>
        </MenubarSubContent>
      </MenubarSub>
    </MenubarContent>
  </MenubarMenu>
<MenubarMenu>
...