36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
/**
|
|
* "Save as PDF" through the browser's print dialog. While printing (also with ⌘ P) the page title is `fileName`, which
|
|
* browsers name the PDF after, and dark mode is off, so the PDF is dark text on white.
|
|
*/
|
|
export function usePdfExport(fileName: MaybeRefOrGetter<string>, onBeforePrint?: () => void) {
|
|
// What to restore after printing; null while not printing. Browsers can fire beforeprint twice before afterprint.
|
|
let screen: { title: string, dark: boolean } | null = null
|
|
|
|
function beforePrint() {
|
|
onBeforePrint?.()
|
|
if (screen) return
|
|
screen = { title: document.title, dark: document.documentElement.classList.contains('dark') }
|
|
document.title = toValue(fileName)
|
|
document.documentElement.classList.remove('dark')
|
|
}
|
|
|
|
function afterPrint() {
|
|
if (!screen) return
|
|
document.title = screen.title
|
|
if (screen.dark) document.documentElement.classList.add('dark')
|
|
screen = null
|
|
}
|
|
|
|
onMounted(() => {
|
|
window.addEventListener('beforeprint', beforePrint)
|
|
window.addEventListener('afterprint', afterPrint)
|
|
})
|
|
onBeforeUnmount(() => {
|
|
window.removeEventListener('beforeprint', beforePrint)
|
|
window.removeEventListener('afterprint', afterPrint)
|
|
})
|
|
|
|
// Opens the browser's print dialog, which offers "Save as PDF"
|
|
return { savePdf: () => window.print() }
|
|
}
|