Simple plugin to generate (offline) pdf. the plugin transform HTML to PDF and also provide the mechanism to share the pdf to other apps like Mail, etc. For now works in iOS and Android, if you want to add other platform feel free contribute.
API
Before using the plugin just make sure that the device is ready by listening to the onDeviceReady event:
document.addEventListener('deviceready', function(){
})
Description
The plugin expose a global variable named pdf, this variable expose the following functions.
pdf.fromURL( url, options )
Creates a PDF using a URL, it download the document into an in memory Webkit object, and renders it into a PDF.
- url : Takes the URL with the HTML document you want to transform to PDF, once the document finish loading is render by webkit and transformed into a PDF file.
Example:
let options = {
documentSize: 'A4',
type: 'base64'
}
pdf.fromURL('http://www.google.es', options)
.then(()=>'ok')
.catch((err)=>console.err(err))
pdf.fromData( url, options )
Creates a PDF using string with the HTML representation, it download the document into an in memory Webkit object, and renders it into a PDF.
- data : Takes a string representing the HTML document, it load this in Webkit and creates a PDF.
Example:
let options = {
documentSize: 'A4',
type: 'base64'
}
pdf.fromData('<html><h1>Hello World</h1></html>', options)
.then((base64)=>'ok')
.catch((err)=>console.err(err))
Options
documentSize
- Its take
A4, A3, A2
this specify the format of the paper, just available in iOS, in Android this option is ignored.
type
base64
it will return a Base64 representation of the PDF file. ```{ type: 'base64' } ``, is not type is provided this one is choosen by default. `
let options = {
documentSize: 'A4',
type: 'base64'
}
pdf.fromData('<html><h1>Hello World</h1></html>', options)
.then((base64)=> console.log(base64) )
.catch((err)=>console.err(err))
share
It will delegate the file to the OS printing infraestructure, this basically will allow the user to handle the file himself using the mobile OS features available.
let options = {
documentSize: 'A4',
type: 'share'
}
pdf.fromData( '<html><h1>Hello World</h1></html>', options)
.then((stats)=> console.log('status', stats) )
.catch((err)=>console.err(err))
filename
- You can specify the name of the PDF file.
let options = {
documentSize: 'A4',
type: 'share',
fileName: 'myFile.pdf'
}
pdf.fromData( '<html><h1>Hello World</h1></html>', options)
.then((stats)=> console.log('status', stats) )
.catch((err)=>console.err(err))
How Tos
Loading an internal CSS, using raw HTML.
# cssFile have to be the following:
# iOS: www/<css-folder>/<your-file.css>
# Android: file:
function createPDF(cssFile) {
var opts = {
documentSize: "A4",
landscape: "portrait",
type: "share",
fileName: 'my-pdf.pdf'
}
var payload = _.template(' <head><link rel="stylesheet" href="<%=css_file%>"></head><body> <h1> Hello World </h1></body>')
pdf.fromData(payload({css_file: cssFile}),
opts)
.then(progressHide)
.catch(progressHide);
}
Loading from Device Filesystem.
function printInternalFile(param) {
if(cordova.platformId === 'ios') {
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory,
(url) => {
var file = param.replace('file:///android_asset/',url.nativeURL);
pdf.fromURL(file, {
documentsize: 'a4',
landscape: 'portrait',
type: 'share'
})
.then((stats)=> this.preparetogobackground )
.catch((err)=> this.showerror)
},
(err) =>
console.log('error', err, ' args ->', arguments)
);
}else {
pdf.fromURL(param, {
documentsize: 'a4',
landscape: 'portrait',
type: 'share'
})
.then((stats)=> this.preparetogobackground )
.catch((err)=> this.showerror)
}
}
Ionic/Angular 2 Example:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
declare var cordova:any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController) {
const before = Date.now();
document.addEventListener('deviceready', () => {
console.log('DEVICE READY FIRED AFTER', (Date.now() - before), 'ms');
cordova.plugins.pdf.fromData( '<html> <h1> Hello World </h1> </html>', options )
.then(()=>'ok')
.catch((err)=>console.err(err))
}
}
Saving a pdf file directly into the file system
If you'd like to directly save the pdf file into the Downloads directory of the device, or any other, without asking the user for what to do with the file, you will need to use type as base64
and then use such information to save the pdf into a file. For this you will need the plugin cordova-plugin-file
.
Here is an example
var fileName = "myPdfFile.pdf";
var options = {
documentSize: 'A4',
type: 'base64'
};
var pdfhtml = '<html><body style="font-size:120%">This is the pdf content</body></html>';
pdf.fromData(pdfhtml , options)
.then(function(base64){
var contentType = "application/pdf";
var folderpath = cordova.file.externalRootDirectory + "Download/";
savebase64AsPDF(folderpath, fileName, base64, contentType);
})
.catch((err)=>console.err(err));
You will also need these two functions. Due to javascript functions hoisting you can declare them afterwards as here:
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
function savebase64AsPDF(folderpath,filename,content,contentType){
var DataBlob = b64toBlob(content,contentType);
console.log("Starting to write the file :3");
window.resolveLocalFileSystemURL(folderpath, function(dir) {
console.log("Access to the directory granted succesfully");
dir.getFile(filename, {create:true}, function(file) {
console.log("File created succesfully.");
file.createWriter(function(fileWriter) {
console.log("Writing content to file");
fileWriter.write(DataBlob);
}, function(){
alert('Unable to save file in path '+ folderpath);
});
});
});
}
Deprecated
Here are examples to use the deprecated methods.
This generates a pdf from a URL, it convert HTML to PDF and returns the file representation in base64.
document.addEventListener('deviceready', function() {
pdf.htmlToPDF({
url: 'http://www.google.es',
documentSize: 'A4',
landscape: 'portrait',
type: 'base64'
}, this.success, this.failure);
});
The same but giving HTML without URL.
document.addEventListener('deviceready', function() {
pdf.htmlToPDF({
data: '<html> <h1> Hello World </h1> </html>',
documentSize: 'A4',
landscape: 'portrait',
type: 'base64'
}, this.success, this.failure);
});
Opening the pdf with other app menu.
document.addEventListener('deviceready', function() {
pdf.htmlToPDF({
data: '<html> <h1> Hello World </h1> </html>',
documentSize: 'A4',
landscape: 'portrait',
type: 'share'
}, this.success, this.failure);
});