Skip to content

Commit

Permalink
Super janky super basic docx exporting
Browse files Browse the repository at this point in the history
  • Loading branch information
lyssieth committed Jan 6, 2024
1 parent 823553a commit 1f890a9
Show file tree
Hide file tree
Showing 4 changed files with 186 additions and 2 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,8 @@
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vite": "^5.0.11"
},
"dependencies": {
"docx": "^8.5.0"
}
}
125 changes: 123 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions src/lib/ExportBlock.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<script lang="ts">
import { Packer } from "docx";
import { exportToDoc } from "./document";
import { current } from "./store";
import { exportQuestions } from "./util";
Expand Down Expand Up @@ -46,4 +48,25 @@
}
}}">Copy to Clipboard</button
>
<button
on:click="{async () => {
if (exportBlock && exportBlock.value.length > 0) {
const doc = exportToDoc(exportBlock.value);

const blob = await Packer.toBlob(doc);
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'exported.docx';
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 5);
} else {
alert('Nothing to export!');
}
}}">Export as ODT</button
>
</div>
37 changes: 37 additions & 0 deletions src/lib/document.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Document, Paragraph } from "docx";

export function exportToDoc(markdown: string): Document {
const children = [];

for (const line of markdown.split(/\n+/)) {
if (line.startsWith("#")) {
const [level, ...rest] = line.split(" ");
children.push(
new Paragraph({
text: rest.join(" "),
heading: `Heading${level.length}` as
| "Heading1"
| "Heading2"
| "Heading3"
| "Heading4"
| "Heading5"
| "Heading6"
})
);
} else {
children.push(new Paragraph({ text: line }));
}
}

const doc = new Document({
description:
"A document exported from markdown, created using https://lyssieth.github.io/worldbuilding-questionnaire/",
sections: [
{
children: children
}
]
});

return doc;
}

0 comments on commit 1f890a9

Please sign in to comment.