33 lines
1.0 KiB
TypeScript
33 lines
1.0 KiB
TypeScript
import {useApi} from '~/composables/useApi'
|
|
|
|
export const usePdfPrinter = () => {
|
|
const api = useApi()
|
|
|
|
const printPdf = async (url: string): Promise<void> => {
|
|
const res = await api.getBlob(url);
|
|
const disposition = res.headers.get('content-disposition') || '';
|
|
const match = disposition.match(/filename="(.+?)"/i);
|
|
const filename = match?.[1] ?? 'document.pdf';
|
|
|
|
const pdfBlob = res.data.type === 'application/pdf'
|
|
? res.data
|
|
: new Blob([res.data], { type: 'application/pdf' });
|
|
|
|
const blobUrl = URL.createObjectURL(pdfBlob);
|
|
|
|
const a = document.createElement('a');
|
|
a.href = blobUrl;
|
|
a.download = filename;
|
|
a.style.display = 'none';
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
a.remove();
|
|
// L'ouverture dans un nouvel onglet déclenche un 2e PDF sans le nom personnalisé.
|
|
setTimeout(() => URL.revokeObjectURL(blobUrl), 60_000);
|
|
}
|
|
|
|
return {
|
|
printPdf
|
|
}
|
|
}
|