I'm using SvelteKit and the npm package docx.

Based on the example 85-template-document.ts, I have the following code:

import { error } from "@sveltejs/kit";

import {
  ExternalHyperlink,
  HeadingLevel,
  Paragraph,
  patchDocument,
  PatchType,
  Table,
  TableCell,
  TableRow,
  TextDirection,
  TextRun,
  VerticalAlign,
} from "docx";

export async function GET({ params }) {

  const doc = await createDoc();
  if (!doc) {
    error(500, "It didn't work out.");
  }
  return new Response(doc, { status: 200, headers: {} });
}

async function createDoc() {
  const simpleTemplate = await getRemoteTemplate();

  if (!simpleTemplate) {
    return error(500, "failed to get document");
  }

  const doc = await patchDocument({
    outputType: "nodebuffer",
    data: simpleTemplate,
    patches: { 
      ... 
    },
  });

  return doc;
}


async function getRemoteTemplate() {
  const response = await fetch(
    "https://raw.githubusercontent.com/dolanmiu/docx/master/demo/assets/simple-template.docx"
  );

  let blob = await response.blob();

  // Correct the mime type because github sends the wrong one
  const mimeTypeDocx =
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
  blob = blob.slice(0, blob.size, mimeTypeDocx);

  console.log(blob.type); // --> mimeTypeDocx
  return blob;
}

When I try to load the simpleTemplate into patchDocument, I'm seeing the following error:

Error: Can't read the data of 'the loaded zip file'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?
    at file:///path/to/node_modules/docx/build/index.mjs:16886:43
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

It appears to be in the correct Blob type. Where do you think I am going wrong?

I've also tried passing in an ArrayBuffer instead...

  const simpleTemplateArrayBuffer = await simpleTemplate.arrayBuffer();

  const doc = await patchDocument({
    outputType: "nodebuffer",
    data: simpleTemplateArrayBuffer,
    patches: { 
  
      ... 
    },
  });

...but get the same error.

What am I doing wrong?

0

There are 0 best solutions below