How to print a Base64 encoded file with the Print.js library

I am facing an issue with printing a Base64 file. Despite my efforts, the file does not print as expected.

function convertToBase64() {

var selectedFile = document.getElementById("inputFile").files;

if (selectedFile.length > 0) {

    var fileToLoad = selectedFile[0];

    var fileReader = new FileReader();
    var base64;

    fileReader.onload = function (fileLoadedEvent) {
        base64 = fileLoadedEvent.target.result;

        const pdfBlob = new Blob([base64], { type: "application/pdf" });
        const url = URL.createObjectURL(pdfBlob);
        printJS({
            printable: url,
            type: "pdf",
            base64: true
        });
    };
    fileReader.readAsDataURL(fileToLoad);
}

}

In this code snippet, I attempt to convert a selected PDF file into a Base64 format for printing purposes using Print.js. Unfortunately, I am encountering difficulties in making the printing process work correctly.

Answer №1

Your current code is passing a URL instead of the base64 data to the print function.

If you prefer to keep your code as is, simply remove the base64 flag from the print parameters.

printJS({
  printable: url,
  type: 'pdf',
});

Alternatively, you can directly pass the base64 variable to the print function without creating the blob and URL. The print library will take care of that for you.

For example:

If you have a variable named base64Data containing valid base64 data.

printJS({
  printable: base64Data,
  type: 'pdf',
  base64: true
});

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

Organizer featuring Outlook-inspired capabilities

My goal is to develop a system for efficiently managing appointments. Upon opening the application, I want to display a calendar control that will retrieve an individual's schedule from a SQL server database. For example, if the user has meetings sch ...

The system does not acknowledge "ENVIRONMENT" as a command that can be executed either internally or externally, or as a batch file that can be

While running my Next.js application, I encountered the following error in a script: "scripts": { "dev: "ENVIRONMENT=env/.env.development next dev", "check": "npm run format && npm run eslint", "e ...

Setting up Redis for session store in the right way involves a few key steps

I have been attempting to configure Redis Store in the following manner: var express = require('express'); var app = express(); ....... ....... var session = require('express-session'); var redis = require("redis").createClient(); var ...

What's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

The function of window.location is a mixed bag of success and failure

I am encountering an issue with a JavaScript function that is supposed to navigate to the next page when clicking a button. The function works correctly for step 1, but it fails for step 2. Upon executing the function using nextstep = 'form', _b ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

Creating a Form with Dynamic HTML when Button is Clicked

I have been working on enhancing the functionality of my website app located at , but unfortunately, I have not been successful so far. My goal is to introduce a vendor information form with just one click of a button and then enable users to add products ...

Issue: Unable to locate module '/node_modulesprogressbar/package.json'

Currently, I am facing an issue with the generation of a progress bar using Browserify and progressbar.js. When I try to var ProgressBar = require('node_modules/progressbar');, an error pops up saying Error: Cannot find module '/node_modules ...

jQuery Modal activated only once upon clicking

Recently, I've been experiencing a frustrating issue that's giving me a splitting headache. Despite scouring this forum for answers, my problem persists. Here's the situation: I have a button that triggers modals. Upon first click after refr ...

Guidance on using an array to filter an object in Javascript

Looking at the object structure in Chrome Dev Tools, it appears like this: obj: { 1: {...}, 2: {...}, 3: {...}, 4: {...}, 5: {...}, } On the other hand, there is a simple array as well: arr: [1,3,5,7] The goal here is to filter the object bas ...

Converting all numbers separated by commas to numbers separated by periods in a string using JavaScript

Imagine a scenario where you have a string containing numbers, such as, test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text Your task is to replace the numbers with decimals instead of commas without altering anything else in the ...

Leveraging the power of React Native with embedded RapidAPI functionality in the source

I had previously used the following code to retrieve a JSON file containing personal data in my React Native source code: async componentDidMount() { try { const response = await fetch('mydomain.org/personaldata.json'); const responseJson ...

Having trouble with the sleep function in nodejs?

Hey there! I'm currently working on a Node.js function that sends requests using array.map. However, I'm facing a challenge with making the function wait for 4 minutes when an error occurs before sending the next request. I've attempted to u ...

When json.parse encounters an undefined value at position 1

Currently, I am diving into learning express.js and my latest project involves creating a web app that can convert cryptocurrency to Fiat currency. Things have been progressing smoothly so far, but I've hit a roadblock when attempting to use json.pars ...

Express middleware for handling errors with Node.js router

My application structure is laid out as follows: - app.js - routes ---- index.js The ExpressJS app sets up error handlers for both development and production environments. Here's a snippet from the app.js file: app.use('/', routes); // ro ...

Issue encountered when attempting to retrieve elements within an HTA's IFrame

We are currently working on automating an Intranet site using HTA and JavaScript. To bypass the browser security settings, we have implemented an Iframe within the HTA itself instead of opening the site in a browser. Despite being able to successfully logi ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

Can you update the `runtime` property to `segment` in the export config?

I'm currently working on setting up an upload API route within my application. /admin/upload However, when I attempt to console.log(req.file), it returns as undefined. This seems to be related to the following configuration: export const config = { ...

Creating a 3D object using three.js framework

When playing video games, I often notice a common pattern where hovering the mouse over an object triggers a gradient highlight around its 2D representation. To recreate this effect in my Three.js scene, I started by setting up the necessary raycaster vari ...

React Native, state values are stagnant

I created an edit screen where I am attempting to update the post value through navigation v4 using getParams and setParams. However, when I modify the old value and click the save button, it does not update and no error is displayed. The old values still ...