使用jspdf将PDF直接保存到文件 [英] Save pdf directly to file using jspdf

查看:3206
本文介绍了使用jspdf将PDF直接保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本是一个Firefox插件,所以可以访问敏感的代码,比如访问文件系统等。
我显示一个面板填充了<$我可以使用 postMessage

轻松地将输入发送到插件代码当我运行生成一个 pdf 下面的代码,并显示一个下载提示,这样我就可以选择目录来放置文件,但是我想直接把文件保存到一个文件中
类似于: doc.saveToFile(/ path / to / file)//我的插件代码中的自定义方法

这可以使用 jsPDF 对象吗?

 < 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>


解决方案

这应该适用于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 < a>


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

这篇关于使用jspdf将PDF直接保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆