The process of compressing font files (such as ArialMT.ttf) using JSZip is experiencing issues

While zipping images and HTML files works smoothly, I encountered an issue when trying to add font files for CSS. The font file is only 1kb in size, but it cannot be opened.

Even after attempting to zip the font without any other files, the problem persisted.

let zip = new JSZip()
let imageURLCount = 0
let fontFileCount = 0

let imageURLs = [
 'http:site.com/image1.jpg',
 'http:site.com/image2.jpg',
 'http:site.com/image3.jpg',
 'http:site.com/image4.jpg'
]

let fontFiles = [
 'http:site.com/fontFile1.ttf',
 'http:site.com/fontFile2.ttf',
 'http:site.com/fontFile3.ttf',
 'http:site.com/fontFile4.ttf'
]

// zipping images
imageURLs.forEach((url, i) => {
  JSZipUtils.getBinaryContent(url, (error, data) => {
     if (error) {
        throw error
     }
     // naming the zipped file
     imageFileName = 'image_'+i+'.jpg'

     // creating a folder for images
     zip.folder('images')
        .file(imageFileName, data,{binary: true})

     imageURLCount++
     if (imageURLCount === imageURLs.length) {
        zipComplete(imageURLCount,fontFileCount)
     }
  })
}) // end of forEach loop for imageURLs[]

// zipping font files
fontFiles.forEach((fontFile, i) => {
  JSZipUtils.getBinaryContent(fontFile, (error, data) => {
     if (error) {
        throw error
     }

     // naming the zipped file
     fileName = 'font_'+i+'.ttf'
     zip.file(fileName, data, {binary:true})
     fontFileCount++
     if (fontFileCount === fontFiles.length) {
        zipComplete(imageURLCount,fontFileCount)
     }
  })
}) // end of forEach loop for fontFiles[]

// Note: zipComplete(imageURLCount,fontFileCount) checks if both arrays have been fully iterated to trigger the 'file-saver' SaveAs()

How can I properly compress the font files using JSZip? Is it even feasible to zip fonts with JSZip?

Answer №1

Upon reviewing your code sample, I initially anticipated to identify an issue but was pleased to find that everything is in order. Below is a functional demonstration illustrating how to zip a .ttf file and proceed with downloading the zip file.

The likely culprit could be the content returned from your .ttf URIs.

let zip = new JSZip()
let imageURLCount = 0
let fontFileCount = 0

let imageURLs = []

let fontFiles = [
  'https://fontlibrary.org/assets/fonts/symbola/cf81aeb303c13ce765877d31571dc5c7/7d8d51a2e1b57d59075325384458fac6/SymbolaRegular.ttf'
]

// zipping font files
fontFiles.forEach((fontFile, i) => {
  JSZipUtils.getBinaryContent(fontFile, (error, data) => {
    if (error) {
      throw error
    }

    // naming the zip file
    fileName = 'font_' + i + '.ttf'
    zip.file(fileName, data, {
      binary: true
    })
    fontFileCount++
    if (fontFileCount === fontFiles.length) {
      zipComplete(imageURLCount, fontFileCount)
    }
  })
}) // end of fontFiles[] forEach 
function zipComplete(imageURLCount, fontFileCount) {
  zip.generateAsync({
      type: "blob"
    })
    .then(function(content) {
      // utilizing FileSaver.js
      saveAs(content, "example.zip");
    });
}
// PS: zipComplete(imageURLCount,fontFileCount) checks if both arrays looped to the end and then triggers the 'file-saver' SaveAs()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.2/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip-utils/0.1.0/jszip-utils.js"></script>
<script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on extracting the image URL from a canvas element using Selenium in Java and leveraging JavascriptExecutor

My main objective is to extract the image URL from a canvas container. Here is what I have attempted: JavascriptExecutor jse = (JavascriptExecutor) driver; Object imageURL = jse.executeScript("arguments[0].toDataURL('image/png');", canvas); Un ...

Saving the current date in MongoDB using the save method

Is there a way to have MongoDB automatically populate a field with the current UTC DateTime when saving a document? I'm aware of the $currentDate operator, but it seems to only be accessible within the update method. ...

Dynamic value in Angular select using ng-initExperience the power of Angular select

When working with Angular, I encountered an issue trying to set a default value for a select box using ng-init from an object that is generated during runtime. Here's the code snippet that's causing me trouble: <select ng-model= ...

Tips on finding the most budget-friendly item in a Vue array

I'm working with an array called item.warehouse_positions that contains various prices and IDs. I want to display only one item.id with the lowest price. How can I achieve this? <div v-for='(item, index) in item.warehouse_positions' :key= ...

Sped up object outpacing the mouse pointer

I'm currently developing a drag and drop minigame, but I've encountered an issue with the touch functionality. The draggable function (using only cursor) works flawlessly, however, when I tried to implement touch support for mobile and tablet use ...

Is it not possible to generate HTML tags using jQuery and JavaScript in JSF?

I'm currently working with jsf 2.0 and richfaces 4.0 to develop my application. Occasionally, I incorporate jQuery and JavaScript functions for displaying and hiding elements. However, I've encountered an issue when trying to generate tags within ...

Having trouble configuring the drizzle vue plugin to work with vuejs 2

After following the official documentation for setting up drizzle with vuejs 2 located here, I attempted to run my project using yarn serve. However, during this process, I encountered several errors as shown in the image https://i.stack.imgur.com/hvmnm.jp ...

Can Selenium in JavaScript be used to retrieve child elements from a webpage?

I've been struggling to adapt my JavaScript script for use with Selenium (also in JavaScript). Despite numerous attempts, I haven't been able to find a solution. I've attached an image to better explain my question await chromeDriver.findEle ...

Leverage Vue.js with Vuex for state management to achieve two-way binding without the need for mutation via v-model

While I understand that mutations are typically used to change state, I couldn't help but wonder if it's technically feasible to utilize state in a v-model binding. This is how I currently handle it: In the HTML: ... <input v-model='to ...

Understanding the concept of event bubbling through the use of querySelector

I am currently working on implementing an event listener that filters out specific clicks within a container. For instance, in the code snippet below I am filtering out clicks on elements with the class UL.head. <div> <ul class="head"> < ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

Retrieve dynamically generated v-select elements' selected options in Vue Vuetify

In my Vue project, I am utilizing Vuetify to populate a list of objects retrieved from an API. The JSON data structure looks like this: users = [ { "id": "1234", "name": "John Doe", "description": "Male, 25 years old", " ...

Using Vue components in NativeScript-Vue popups: A comprehensive guide

To initiate the popup, I include the following code in a root component: import parentt from "./parentt.vue"; . . . this.$showModal(parentt, { fullscreen: true, }); The contents of parentt.vue are as follows: <template> <StackLayout> ...

Tips for Populating Form by Selecting Options from Search Bar Dropdown in Laravel

I successfully implemented a search functionality in a Laravel component that displays data from a MySQL database in a dropdown using the Typeahead Js library following this helpful tutorial. The goal was to have the selected search result automatically p ...

Sending a form using AJAX causes the page to redirect

I have an input type="file" that triggers a form submission upon change. $(document).on("change", "#image-upload", function (e) { $.ajax({ url: '/BlogPost/UploadHomeReport', type: 'POST', data: $('#upload-i ...

Join and Navigate in Angular 2

Attempting to retrieve information from a JSON file has been an issue for me. Here is the code snippet: ngOnInit() { this.http.get('assets/json/buildings.json', { responseType: 'text'}) .map(response => response) .subsc ...

Instantly see changes without having to manually refresh the screen

I need help figuring out how to update my PHP webpage or table automatically in real-time without requiring a manual refresh. The current functionality of the page is working perfectly fine. Specifically, I want the page to instantly display any new user ...

Error: Validation error encountered while validating recipe: _listId field is mandatory and must be provided

As a newcomer to node.js, I am attempting to create a cookbook restful API using nodejs. The goal is to have a list of recipes where each recipe is associated with a specific list selected by its id. However, I am encountering an issue while trying to retr ...

Steps for organizing a list based on the number of clicks

I've created an HTML list with images of political party logos. Each logo is a grid item that can be clicked on. I want to sort the list based on the number of clicks each logo receives, essentially ranking them by popularity. However, I'm not su ...

The animation is not updating quickly enough

I'm working on a navigation bar that sticks to the top of the page. As the user scrolls down, I want the bar to shrink, and when they scroll back up, it should return to its original size. Issue: The problem I'm facing is that when the user quic ...