Skip to content

html(): Custom font does not get set again if it has already been added once #3890

@jhook1

Description

@jhook1

I have read and understood the contribution guidelines. Version: 3.0.3 (also 2.5.1)

When using the html() function and multiple fonts are applied via CSS, once a font has been set once, it will not be used for rendering again if it is interrupted by an element of different font.

In the below example, the expected result would be that the 3 barcode elements would render with the Libre Barcode font and the text element in between 2 and 3 would render as the default font. However, the third barcode element is rendered in the default font instead:

JSFiddle: https://jsfiddle.net/145y9nfv/

Expected:

Image

Actual:

Image

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/3.0.3/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<div class="container">
  <p class="barcode">barcode</p>
  <p class="barcode">barcode2</p>
  <p>Text</p>
  <p class="barcode">barcode3</p>
</div>
<button onclick="ConvertHtmlToPdf()">HTML to PDF</button>

CSS:

@font-face {
  font-family: 'Libre Barcode 128';
  font-style: normal;
  font-display: swap;
  font-weight: 400;
  src: url(https://cdn.jsdelivr.net/fontsource/fonts/libre-barcode-128@latest/latin-400-normal.ttf) format('truetype');
}
.barcode {
    font-family: "Libre Barcode 128";
}

Javascript:

const { jsPDF } = window.jspdf;
    
async function LoadFont(fontUrl) {
    let fontBytes = await fetch(fontUrl).then(res => res.arrayBuffer());
    return btoa(String.fromCharCode.apply(null, new Uint8Array(fontBytes)));
}

async function ConvertHtmlToPdf() {
    let pdfDoc = new jsPDF({
        orientation: "portrait",
        unit: "px",
        hotfixes: ["px_scaling"],
        format: "letter",
    });

    let barcodeFont = await LoadFont("https://cdn.jsdelivr.net/fontsource/fonts/libre-barcode-128@latest/latin-400-normal.ttf");
    pdfDoc.addFileToVFS("LibreBarcode128-Regular.ttf", barcodeFont);
    pdfDoc.addFont("LibreBarcode128-Regular.ttf", "Libre Barcode 128", "normal");
    pdfDoc.setFont("Libre Barcode 128");
    
    const containerEl = document.querySelector(".container");
    
    pdfDoc.html(containerEl, {
        callback: function (pdfDoc) {
            pdfDoc.output('dataurlnewwindow');
        },
        html2canvas: {
            useCORS: true,
        },
        width: pdfDoc.internal.pageSize.getWidth(),
        windowWidth: pdfDoc.internal.pageSize.getWidth(),
        margin: [75, 0, 0, 0],
        autoPaging: 'text',
    });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions