可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.