How can I use custom fonts?
sergio9929 opened this issue ยท 2 comments
Ask your question
Hello,
I'm trying to use Satoshi, a custom font from FontShare, and I'm not being able to get it working. I've tried downloading the font and adding this to the html options in exportToPDF()
:
fontFaces: [{
family: 'satoshi',
weight: 'normal',
src: [{
url: '/GHM6WVH6MILNYOOCXHXB5GTSGNTMGXZR.woff',
format: 'woff',
}]
}],
I've googled about it and everyone is adding the font using jsPDF.addFont()
and setFont()
and I don't know how to access to those things outside of exportToPDF().then()
.
I'm of course using the font in my css:
html {
overflow-x: hidden;
background-color: var(--base-color);
color: var(--primary-color);
font-size: 16px;
font-family: 'Satoshi', sans-serif;
scroll-behavior: smooth;
}
And I also console logged jsPDF.getFontList()
:
{
"helvetica": [
"normal",
"bold",
"italic",
"bolditalic"
],
"Helvetica": [
"",
"Bold",
"Oblique",
"BoldOblique"
],
"courier": [
"normal",
"bold",
"italic",
"bolditalic"
],
"Courier": [
"",
"Bold",
"Oblique",
"BoldOblique"
],
"times": [
"normal",
"bold",
"italic",
"bolditalic"
],
"Times": [
"Roman",
"Bold",
"Italic",
"BoldItalic"
],
"zapfdingbats": [
"normal"
],
"ZapfDingbats": [
""
],
"symbol": [
"normal"
],
"Symbol": [
""
]
}
Help would be much appreciated ๐
Additional information
No response
I have solved the problem.
After this and several other problems, such as not being able to compress pdfs, I decided to remove nuxt-pdf and just use jsPDF directly.
After that the problems were over. Now my pdfs are 400KB instead of 8MB and have a nice typography.
Here is the composable I created to easily export things to pdf with jsPDF:
import jsPDF, { HTMLWorker } from 'jspdf';
export const useHTMLToPDF = (filename: string, html: string | HTMLElement): HTMLWorker => {
const doc = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4',
putOnlyUsedFonts: true,
floatPrecision: 4,
compress: true,
});
return doc.html(html, {
callback: function (doc) {
doc.save(`${filename}.pdf`)
},
margin: [10, 10, 10, 10],
image: { quality: .9, type: 'jpeg' },
autoPaging: 'text',
x: 0,
y: 0,
width: 190, //target width in the PDF document
windowWidth: 1000, //window width in CSS pixels
fontFaces: [
{
family: 'Satoshi',
weight: 'normal',
src: [{
url: '/Satoshi-Regular.ttf',
format: 'truetype',
}]
},
{
family: 'Satoshi',
weight: 'bold',
src: [{
url: '/Satoshi-Bold.ttf',
format: 'truetype',
}]
},
],
html2canvas: {
onclone(document) {
document.documentElement.classList.add('exportToPDF')
},
}
})
}
Note that you have to put your custom fonts in /public
for this to work.
Usage:
useHTMLToPDF(filename, pdfSection.value).then(jsPDF => {
// successfully exported
useNotify({ text: 'Exportado correctamente', icon: 'heroicons:document-check', theme: 'success' })
}).catch(error => {
// error
console.error(error)
useNotify({ text: 'Error', icon: 'heroicons:exclamation-circle', theme: 'warning' })
})