Ionic framework PdfViewer - pdf

I want to develop pdf ebook application for mobile. Is there pdf viewer component for ionic framework. I fond mozilla pdf.js . I need ionic project example.

Have you tried the angular module ng-pdfviewer? Because angular works under the hood of Ionic.

var app = angular.module('testApp', [ 'ngPDFViewer' ]);
app.controller('TestCtrl', [ '$scope', 'PDFViewerService', function($scope, pdf) {
$scope.viewer = pdf.Instance("viewer");
$scope.nextPage = function() {
$scope.viewer.nextPage();
};
$scope.prevPage = function() {
$scope.viewer.prevPage();
};
$scope.pageLoaded = function(curPage, totalPages) {
$scope.currentPage = curPage;
$scope.totalPages = totalPages;
};
}]);
And the Directive uses the above pdf.js file
and the Html is bellow:
<button ng-click="prevPage()"><</button>
<button ng-click="nextPage()">></button>
<br>
<span>{{currentPage}}/{{totalPages}}</span>
<br>
<pdfviewer src="test.pdf" on-page-load='pageLoaded(page,total)' id="viewer"></pdfviewer>
and using ng-pdf should solve your problem.

Have you tried this Phonegap plugin https://github.com/ti8m/DocumentHandler
Below is how I used it.
$scope.HandleDocumentPlugin = function () {
if (DocumentViewer != null) {
DocumentViewer.previewFileFromUrlOrPath(
function () {
console.log('success');
}, function (error) {
if (error == 53) {
console.log('No app that handles this file type.');
var alert = $ionicPopup.alert({
title: 'Alert!',
template: "There is no app installed that handles this file type."
});
alert.then(function (res) {
});
}
}, $scope.PDF_URL);
}
else if (DocumentHandler != null) {
DocumentHandler.previewFileFromUrlOrPath(
function () {
console.log('success');
}, function (error) {
if (error == 53) {
console.log('No app that handles this file type.');
var alert = $ionicPopup.alert({
title: 'Alert!',
template: "There is no app installed that handles this file type."
});
alert.then(function (res) {
});
}
}, $scope.PDF_URL);
}
else {
console.log("error");
}
}

You could use Cordova - InAppBrowser since it will be able to display pdf just open specify the static or dynamic path . you do need to add other modules as this an be also used to open web pages also you could use
https://github.com/initialxy/cordova-plugin-themeablebrowser
to theme the pdf openings for custom loading to hide url etc fields
these two approaches can be used to open a simple pdf document for reading purposes.
but for more specific options you should go with
https://github.com/akrennmair/ng-pdfviewer
which requires pdf.js and pdf.compat.js.
add it as a dependency in your app.
var app = angular.module('testApp', [ 'ngPDFViewer' ]);
basic controller syntax useage :
app.controller('TestCtrl', [ '$scope', 'PDFViewerService', function($scope,
pdf) {
$scope.viewer = pdf.Instance("viewer");
$scope.nextPage = function() {
$scope.viewer.nextPage();
};
$scope.prevPage = function() {
$scope.viewer.prevPage();
};
$scope.pageLoaded = function(curPage, totalPages) {
$scope.currentPage = curPage;
$scope.totalPages = totalPages;
};
}]);

you can use pdfmake library to generate the pdf, there is a good example to integrate it to ionic

Related

how to implement an image and pdf picker in one single upload button in expo?

I am building a mobile app by using EXPO.Now i am stucked in a img & pdf picker,i can't pick image and pdf in one single function or button. can anyone know any packages that enable pdf & image picker in one function.....
You can use expo document picker to pick multiple file types and images as following:
import * as DocumentPicker from 'expo-document-picker';
const picker = await DocumentPicker.getDocumentAsync({
type: "*/*",
multiple: true,
copyToCacheDirectory: true
});
Check the official expo docs DocumentPicker
If you wanna allow your user to select pdf then you can do this
async function openDocumentPicker() {
try {
const res = await DocumentPicker.getDocumentAsync({
type: "*/*",
copyToCacheDirectory: true,
multiple: false,
});
console.log(res)
var lastThree = res.name.substr(res.name.length - 3);
if(lastThree == 'pdf')
{
if(res.type == 'success')
{
//Do Something here
}
}
else
{
alert('Please select PDF File')
}
} catch (error) {
alert(error);
}
}

how to create pdf in react-native

I want to create pdf in my app in react-native for word to pdf or html to pdf converter.I have tried all possible react-native packages but none of them give me a desired result what should I do.
Are you using nodeJS on the server? If you are, send the html to the server and use this to convert the html to a pdf.
Have you Checked react-native-pdf-lib.
It is pretty good module.
Otherwise consider server side rendering
You can generate pdf file in react native with the npm package react-native-html-to-pdf.
Steps :
Create HTML template of your pdf file you want to generate.
Install the package and install pod in ios folder with pod install
Rebuild the app in android/ios.
import RNHTMLtoPDF from 'react-native-html-to-pdf';
const createPdf = async () => {
try {
let options = {
html: '<div>Hello pdf</div>',
fileName: 'demofile',
directory: 'Downloads',
base64: true,
};
let file = await RNHTMLtoPDF.convert(options);
console.log(file);
} catch (error) {
console.log(error);
}
}
Here is the more specific answer to your problem :
import RNHTMLtoPDF from 'react-native-html-to-pdf';
const createPdf = async () => {
let h1 = "Hey Heading 1";
let h2 = "heading 2";
let para = "Something description";
// use Backtick(`) to define html for your custom dynamic content
const pdf_html = `<div>
<h1>{h1}</h1>
<h1>{h2}</h1>
<h1>{para}</h1>
</div`;
try {
let options = {
html: pdf_html,
fileName: 'demofile',
directory: 'Downloads',
base64: true,
};
let file = await RNHTMLtoPDF.convert(options);
console.log(file);
} catch (error) {
console.log(error);
}
}

Downloading image file with react native fetch blob

I am trying to learn react native and how to download files to the device. I know you can do this with react native file system but that does not support authentication which I need. React native fetch blob does support this.
For education purposes, I want to have the code from the first answer to this question recreated in react native fetch blob instead of react native file system.
I someone could write sutch an examlple form me I would be super tankfull.
Question: Downloading data files with React Native for offline use
Try this, it's work fine on Android:
export const download = (url, name) => {
const { config, fs } = RNFetchBlob;
let PictureDir = fs.dirs.PictureDir;
let options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
path: PictureDir + name,
description: t('downloading_file')
}
};
config(options)
.fetch('GET', url)
.then(res => {
if (res.data) {
alert(t('download_success'));
} else {
alert(t('download_failed'));
}
});
};
downloadImage(){
var date = new Date();
var url = "http://debasish.com/image.jpg";
var ext = this.getExtention(url);
ext = "."+ext[0];
const { config, fs } = RNFetchBlob ;
let PictureDir = fs.dirs.PictureDir
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true,
notification : true,
path: PictureDir + "/image_"+Math.floor(date.getTime()
+ date.getSeconds() / 2)+ext,
description : 'Image'
}
}
config(options).fetch('GET', url).then((res) => {
Alert.alert("Download Success !");
});
}
getExtention(filename){
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) :
undefined;
}

Download using jsPDF on a mobile devices

I have a page that includes a download button using jsPDF. On desktop machines it downloads the page as it should. However, pdf.save() does not work on my tablet or phone.
I tried to add a special case for mobile devices to open the PDF in a new window, since mobile devices don't download things the same as desktops, with the idea being that once the PDF is open in a new window the user can choose to save it manually.
var pdf = new jsPDF('p', 'pt', 'letter');
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
html2canvas($("#pdf-area"), {
onrendered: function (canvas) {
$("#pdf-canvas").append(canvas);
$("#pdf-canvas canvas").css("padding", "20px");
}
});
var options = {
pagesplit: true
};
function download(doctitle) {
pdf.addHTML($("#pdf-area")[0], options, function () {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
pdf.output('dataurlnewwindow');
} else {
pdf.save(doctitle);
}
});
}
But the download function still does nothing on my tablet/phone. I tested it with this to make sure the pdf.output() function was working:
pdf.addHTML($("#pdf-area")[0], options, function () {
pdf.output('dataurlnewwindow');
});
and it does still work on desktop, but does nothing on mobile.
jsPDF won't download files on mobile apps by this pdf.save(). I have tried and searched for this issue but could not find a complete solution in one place. I am using the file and file-opener plugin. I have developed the solution in Ionic React. Install below modules.
npm i jspdf
npm install cordova-plugin-file
npm install #ionic-native/file
npm install cordova-plugin-file-opener2
npm install #ionic-native/file-opener
ionic cap sync
Go to your file and add these import statements.
import { jsPDF } from "jspdf";
import 'jspdf-autotable';
import { FileOpener } from '#ionic-native/file-opener;
import { File } from '#ionic-native/file';
import { isPlatform } from "#ionic/react";
Check the pdfDownload function
const pdfDownload = async () => {
var doc = new jsPDF();
doc.setFontSize(40);
doc.text("Example jsPDF", 35, 25)
let pdfOutput = doc.output();
if (isPlatform("android")) {
// for Android device
const directory = File.externalRootDirectory + 'Download/';
const fileName = `invoice-${new Date().getTime()}.pdf`
File.writeFile(directory, fileName, pdfOutput, true).then(succ => {
FileOpener.showOpenWithDialog(directory + fileName, 'application/pdf')
.then(() => console.log('File opened'))
.catch(error => console.log('Error opening file', error));
},
err => {
console.log(" writing File error : ", err)
})
} else if (isPlatform("ios")) {
// for iOS device
console.log('ios device')
const directory = File.tempDirectory;
const fileName = `invoice-${new Date().getTime()}.pdf`
File.writeFile(directory, fileName, pdfOutput, true).then(success => {
FileOpener.showOpenWithDialog(directory + fileName, 'application/pdf')
.then(() => console.log('File opened'))
.catch(e => console.log('Error opening file', e));
},
err => {
console.log(" writing File error : ", err)
})
} else {
// for desktop
doc.save("invoice.pdf");
}
}
I had similar issue.
jsPDF won't download file on phones/ tablets / ipads using "pdf.save()".
Do it through File plugin if you are using cordova/phonegap, this will save pdf file in downloads folder (Android) - for the ios you can access pdf file through a path (which is saved somewhere in temp directory) and can send or share.
Hope this helps you.
Here is the solution of download on mobile with jspdf
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
{
var blob = pdf.output();
window.open(URL.createObjectURL(blob));
}
else
{
pdf.save('filename.pdf');
}
Here is the example if you're using the Cordova platform for your development:
https://github.com/saharcasm/Cordova-jsPDF-Email
The workaround of the pdf not being downloaded in the devices is to use cordova-plugin-file.
Use the output method on the doc that will give you the raw pdf which needs to be written & saved in a file.
For example,
var doc = new JsPDF();
//... some work with the object
var pdfOutput = doc.output("blob"); //returns the raw object of the pdf file
The pdfOutput is then written on an actual file by using the file plugin.
The easiest way which works on both Desktop and Mobile is to use:
window.open(doc.output("bloburl"), "_blank");

Phonegap windows 8 App, with camera functionality, navigate.camera.getPicture() call back function is never called when deployed

We have made a Win8 app using phonegap.
The application also has a reference to a Windows runtime component used to perform some asyc task.
The application has a camera feature, where in the camera is invoked, picture taken and then the picture is displayed on the screen in the success call back function. Everything works perfectly when running directly from visual studio express. The problem arises when we create a package of the application and deploy it using either metro sideloader or powershell. The camera success callback function is never called.
The code for calling the camera is something like this:
CameraService = function() {
var that = {};
that.invokecamera = function(callback) {
try {
GLOBALS.callback = callback;
if (GLOBALS.Ready) {
navigator.camera.getPicture(that.onSuccess, GLOBALS.ThrowException, {
quality : 50,
saveToPhotoAlbum : true,
destinationType : Camera.DestinationType.FILE_URI
});
}
} catch (err) {
alert(err);
} finally {
}
}
that.onSuccess=function(imageURI) {
GLOBALS.ImagePath = imageURI;
GLOBALS.callback(imageURI);
}
return that;
}
Ok, So i figured out the issue mentioned here:
issue with installed app
To fix this i, as mentioned in the link replaced
Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
With
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
In the cordova.js file. I am using cordova 2.4.0.
A more elaborated exmple
Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
storageFolder.createFileAsync(tempPhotoFileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (file) {
file.openAsync(Windows.Storage.FileAccessMode.readWrite).done(function (fileStream) {
Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(_stream, fileStream).done(function () {
var _imageUrl = URL.createObjectURL(file);
successCallback(_imageUrl);
}, function () { errorCallback("Resize picture error."); });
}, function () { errorCallback("Resize picture error."); });
}, function () { errorCallback("Resize picture error."); });
});
Becomes
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
storageFolder.createFileAsync(tempPhotoFileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (file) {
file.openAsync(Windows.Storage.FileAccessMode.readWrite).done(function (fileStream) {
Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(_stream, fileStream).done(function () {
var _imageUrl = URL.createObjectURL(file);
successCallback(_imageUrl);
}, function () { errorCallback("Resize picture error."); });
}, function () { errorCallback("Resize picture error."); });
}, function () { errorCallback("Resize picture error."); });