我正在使用离子框架,我想从厨房中选择一个图像文件,并希望将其转换为PDF并希望将其保存在手机上的文件系统中。 是否有任何javascript或cordova插件可用于执行此任务。
我发现jsPDF可用于将图片转换为PDF格式,但它是否真的适用于移动设备?
答案 0 :(得分:1)
我希望我不会那么晚!
除了jSPDF之外,还需要以下软件包:
并安装相应的ionic-package:
bower install ngCordova
请注意,如何在文件系统中保存pdf文件有几种可能的解决方案。我必须将pdf文件移动到某个目录才能打开它。不过这个解决方案适用于我到目前为止测试的所有Android手机,你可以创建你喜欢的所有PDF文件。
iOS:您可以修改存储目录,以便它也适用于iOS版本。
的index.html:
<head>
<meta charset="utf-8">
... include jsPDF
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>
....
some html
....
... include ngCordova
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
.... the core-library
<script src="cordova.js"></script>
....
</head>
View.html:
<ion-view view-title="Dashboard">
<ion-content class="padding">
<p on-tap="savePDF()">Create PDF</p>
<p on-tap="openPDF()">Open PDF</p>
</ion-content>
</ion-view>
应用-JS:
// to not forget to include ngCordova in order to use $cordovaFile in your controller
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','ngCordova'])
...
...
控制器-JS:
angular.module('starter.controllers', []).controller('DashCtrl', function($scope,$cordovaFile) {
$scope.pdfFilename = "test.pdf";
$scope.makePDF = function(){
var imgData = "your base64 image-data";
var doc = new jsPDF();
doc.setFontSize(40);
doc.text(35, 25, "Octonyan loves jsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
return doc.output('blob');
};
$scope.getDirectoryInfo = function(){
return {
storage: cordova.file.externalRootDirectory, // for android, you may have to use another directory
pdfDir: cordova.file.externalRootDirectory+"pdfs/"
}
};
$scope.savePDF = function(){
var dirs = $scope.getDirectoryInfo();
var storageDir = dirs.storage;
// create directory on the first place if it has not been created so far
$cordovaFile.createDir(storageDir, "pdfs", false);
var pdfBlob = $scope.makePDF();
// create empty pdf-file(in the root-dir)
$cordovaFile.createFile(storageDir, $scope.pdfFilename, true).then(function(success) {
// write pdf-file(in the root dir)
$cordovaFile.writeExistingFile(storageDir, $scope.pdfFilename, pdfBlob, true).then(function (success) {
var fullTmpPath = storageDir + $scope.pdfFilename;
window.resolveLocalFileSystemURL(fullTmpPath, function (fileEntry) {
// get destination-directory to put your pdf into
window.resolveLocalFileSystemURL(dirs.pdfDir, function (dirEntry) {
// move written pdf to the destination-directory
fileEntry.moveTo(dirEntry, $scope.pdfFilename, function (newFileEntry) {
alert($scope.pdfFilename+' is finish! Now you can open it');
});
});
});
}, function (error) {
console.log('there was some error while writting file: ',error);
});
});
};
$scope.openPDF =function(){
var dirs = $scope.getDirectoryInfo();
cordova.plugins.fileOpener2.open(dirs.pdfDir+$scope.pdfFilename,'application/pdf',function(){
console.log('success');
});
};
});
希望这有助于尽管您的问题已经提前了一段时间。