1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

How to embed custom fonts in a PDF generated with html2pdf.js in angular

Discussão em 'Angular' iniciado por abolfazl_mehdi, Setembro 26, 2024.

  1. I'm working on an Angular project where I need to generate a PDF from HTML content using html2pdf.js and embed a custom font (Shabnam.ttf) into the PDF. I'm loading the font from the assets folder and converting it to base64, but the font is not being applied to the final PDF.

    Here’s what I have so far:

    public onPrint(): void {
    const pdf = new jspdf();
    this.convertFontToBase64('/assets/fonts/Shabnam.ttf')
    .then(base64String => {
    pdf.addFileToVFS('Shabnam.ttf', base64String);
    pdf.addFont('Shabnam.ttf', 'Shabnam', 'normal');
    this.generatePdf();
    });
    }

    generatePdf() {
    const content = document.querySelector('#print-layout');

    // Set font for HTML content
    document.body.style.fontFamily = 'Shabnam';

    html2pdf().from(content)
    .set({
    jsPDF: {
    unit: 'mm',
    format: 'a4',
    orientation: 'p'
    },
    html2canvas: { scale: 2 }
    })
    .toPdf((pdf: any) => {
    pdf.save('document.pdf');
    }).save();
    }

    convertFontToBase64(url: string) {
    return fetch(url)
    .then(response => response.arrayBuffer())
    .then(buffer => {
    const base64String = btoa(
    new Uint8Array(buffer)
    .reduce((data, byte) => data + String.fromCharCode(byte), '')
    );
    return base64String;
    });
    }


    The convertFontToBase64 function works and returns the base64 string, but the font is not applied to the PDF. Is there a way to properly embed custom fonts using html2pdf.js?

    Continue reading...

Compartilhe esta Página