Save pdf directly to file using jspdf

China☆狼群 提交于 2019-12-24 08:25:15

问题


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>

回答1:


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




回答2:


But why you don't wanna use your add-on? I think that you don't be able to access the filesystem or things like that, with jsPDF or pdf.js (http://mozilla.github.io/pdf.js/, which is a mozilla project), you will be able to print something that is being displayed on the window, but not sure if you can access some local files.



来源:https://stackoverflow.com/questions/25233344/save-pdf-directly-to-file-using-jspdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!