我已经将jsPDF库添加到我的Titanium项目中以生成PDF客户端,这一直很好用。但现在我想为阿拉伯国家本地化应用程序,这意味着我添加了自定义字体。如果您使用doc.save('file.pdf'),这可以完美地工作,但它似乎不能正确地用于doc.output()。我必须使用输出,因为我在浏览器之外使用jsPDF。
为了使库在Titanium中工作,我必须删除所有对窗口的引用,因为它不在浏览器或webview中运行。
我试过从不同的来源编写文件,但似乎没有任何结果。
我目前的实施:
doc = new jsPDF();
var f = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'fonts/markazi-text.regular.ttf');
var contents = f.read();
var base64font = Ti.Utils.base64encode(contents).toString();
doc.addFileToVFS("MarkaziText-Regular", base64font);
doc.addFont('MarkaziText-Regular', 'markazi-text', 'normal');
doc.setFontSize(20);
doc.setFont('markazi-text', 'normal');
doc.text('The quick brown fox jumps over the lazy dog', 20, 20);
var tempFile = Ti.Filesystem.getFile(Ti.Filesystem.getTempDirectory(), 'report.pdf');
if (tempFile.exists()) {
tempFile.deleteFile();
}
tempFile.write(doc.output());
我也尝试从blob写入文件:
var reader = new FileReader();
reader.onloadend = function () {
tempFile.write(reader.result);
};
reader.readAsText(getBlob(buildDocument()));
但如果我使用它,pdf是空的。我也在一个钛金属应用程序中的webview中尝试了这个库,它确实有效,但我真的不想走那条路。这将需要对代码进行太多更改。
预期:
实际:
我终于通过创建本地HTML文件解决了这个问题。在这个HTML文件中,我加载了jsPDF和我自己的JavaScript来生成PDF文件。我已经在WebView中加载了这个HTML文件。
我在Alloy控制器中生成PDF所需的所有数据。我通过触发应用程序事件并将其捕获到WebView中,将此数据发送到我的WebView JavaScript。
创建PDF后,我在WebView中触发一个包含jsPDF doc的base64数据的app事件:
Ti.App.fireEvent('app:pdfdone', {
output: doc.output('dataurlstring').replace("data:application/pdf;filename=generated.pdf;base64,", "")
});
我最后将其保存为Alloy控制器中的文件:
var f = Ti.Filesystem.getFile(Ti.Filesystem.getTempDirectory(), 'doc.pdf');
f.write(Ti.Utils.base64decode(e.output));