0xh8h
0xh8h

Reputation: 3509

FileSaver.js Save as type is incorrect

I'm working on a project that uses Electron to wrap a web app to desktop app.

In this project, I use FileSaver.js to export canvas content to png/jpg/pdf.

  1. canvas is turned into base64 image
  2. base64 image is turned into blob
  3. blob file is saved using FileSaver.js

Here is how it looks like when Save dialog appears:

enter image description here

This is what it should look like as normal save as (png file):

enter image description here

This matters because if the user forgets to insert .png at the end of file name, the file can not be opened normally.

How can I solve this problem?

Thank you very much.

Upvotes: 2

Views: 2701

Answers (1)

kemotoe
kemotoe

Reputation: 1777

I would suggest using the electron-canvas-to-buffer package and depending on the users export choice, create two methods and use electron dialog's filter to save accordingly.

For the pdf I used jspdf package. This will save the file as whatever filename you specify. Also I added a snippet to paint the canvas background white to avoid black backgrounds.

Here is a simple example

var canvasBuffer = require('electron-canvas-to-buffer');
var fs = require('fs');
var jsPDF = require('jspdf');

// your canvas drawing
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
// painting the canvas white to prevent black background
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
// drawing
context.fillStyle = 'blue';
context.fillRect(0, 0, 50, 50);
context.fillStyle = 'red';
context.fillRect(50, 10, 30, 20);


// PNG
function savePNG() {
    var buffer = canvasBuffer(canvas, 'image/png');
    dialog.showSaveDialog({
        filters: [{
            name: 'png',
            extensions: ['png']
        }]
    }, function (fileName) {
        if (fileName === undefined) return;
        fs.writeFile(fileName, buffer, function (err) {});
    });
}
// JPG
function saveJPG() {
  var buffer = canvasBuffer(canvas, 'image/jpg');
  dialog.showSaveDialog(
    {
      filters: [
        {
          name: 'jpg',
          extensions: ['jpg'],
        },
      ],
    },
    (fileName) => {
      if (fileName === undefined) return;
      fs.writeFile(fileName, buffer, (err) => {});
    },
  );
}
// PDF
function savePDF() {
  // only jpeg is supported by jsPDF
  let imgData = canvas.toDataURL('image/jpeg', 1.0);
  let pdf = new jsPDF();
  pdf.addImage(imgData, 'JPEG', 0, 0);
  pdf.save('test.pdf');
}

Upvotes: 1

Related Questions