且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jspdf将PDF直接保存到文件

更新时间:2023-12-02 20:16:22

这应该适用于Firefox附加代码:

  const {OS} = require(resource://gre/modules/osfile.jsm); 

var pathToFile = OS.Path.join(path,to,file.pdf);

var doc = new jsPDF();
doc.text(20,20,'Hello bob');

var ab = doc.output('arraybuffer');
var u8 = new Uint8Array(ab);

OS.File.writeAtomic(pathToFile,u8).then(
function()
{
alert('File written!');
(e)

alert('Error'+ e);
}
);

如果您不使用附加SDK,而是使用普通扩展名,请将第一个符合:

  const {OS} = Components.utils.import(resource://gre/modules/osfile.jsm ,{}); 

查看OS.File的更多信息: https://developer.mozilla.org/zh-CN/docs/JavaScript_OS.File/OS.File_for_the_main_thread


My script is a Firefox addon so has access to sensitive code like access to filesystem etc.
I display a Panel populated with html content, I could easily send input to the addon code using postMessage
When I run the code below a pdf is generated and a download prompt is shown so i can select directory to place file, but I'd like to save the file using javascript directly to a file in background without the download prompt showing.
Something like: doc.saveToFile("/path/to/file") // custom method in my addon code
Would this be possible using the jsPDF object?

<html>

    <head>
        <script type='text/javascript' src='jspdf.source.js'></script>
    </head>

    <body>
        Hey
        <script>
        var doc = new jsPDF();
        doc.text(20, 20, 'Hello bob');
        doc.save('test.pdf');
        </script>

    </body>
</html>

This should work on your Firefox add-on code:

const { OS } = require("resource://gre/modules/osfile.jsm");

var pathToFile = OS.Path.join("path", "to", "file.pdf");

var doc = new jsPDF();
doc.text(20, 20, 'Hello bob');

var ab = doc.output('arraybuffer');
var u8 = new Uint8Array(ab);

OS.File.writeAtomic(pathToFile, u8).then(
   function()
   {
       alert('File written!');
   },
   function(e)
   {
       alert('Error ' + e);
   }
);

If you aren't using the Add-On SDK, but rather a normal extension, replace the first line with:

const { OS } = Components.utils.import("resource://gre/modules/osfile.jsm", {});

Check this out for further info on OS.File: https://developer.mozilla.org/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread