Giter VIP home page Giter VIP logo

pdf-generator's Introduction

cordova-pdf-generator

Index

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.

The iOS HTML to PDF transformation is based in this work BNHtmlPdfKit, I just add a new method to allow transformation between plain HTML to PDF.

Demo

Here you can find a starting guide.

  • Generates a PDF document using a URL or HTML.
  • Open-with menu, open the context menu and (push to cloud, print, save, mail, etc...).
  • Return the Base64 file representation back, so you can upload the file to a server (IOS & Android only).

Supported Platforms

  • Android
  • iOS
cordova plugin add cordova-pdf-generator

Installing using Plugman

cordova platform add ios
plugman install --platform ios --project platforms/ios --plugin cordova-pdf-generator

Installing using NPM

npm install cordova-pdf-generator
cordova plugins add node_modules/cordova-pdf-generator

Installing the hard way.

Clone the plugin

$ git clone https://github.com/cesarvr/pdf-generator

Create a new Cordova Project

$ cordova create hello com.example.helloapp Hello

Install the plugin

$ cd hello
$ cordova plugin add ../pdf-generator

Before using the plugin just make sure that the device is ready by listening to the onDeviceReady event:

document.addEventListener('deviceready', function(){
  // start using cordova plugin here.
})

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')   // it will
    .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) )   // returns base64:JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9DcmVh...
    .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) )   // ok..., ok if it was able to handle the file to the OS.  
    .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) )   // ok..., ok if it was able to handle the file to the OS.  
    .catch((err)=>console.err(err))
Loading an internal CSS, using raw HTML.
# cssFile have to be the following: 
# iOS: www/<css-folder>/<your-file.css>
# Android: file:///android_asset/www/<css-folder>/<your-file.css>

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.
      //Example: file:///android_asset/index.html

      function printInternalFile(param) {

        /* generate pdf using url. */
        if(cordova.platformId === 'ios') {

          // To use window.resolveLocalFileSystemURL, we need this plugin https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/
          // You can add this by doing cordova plugin add cordova-plugin-file or
          // cordova plugin add https://github.com/apache/cordova-plugin-file
          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;    //global;

@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');

                //generate the pdf.
                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){               
        // To define the type of the Blob
        var contentType = "application/pdf";
            
        // if cordova.file is not available use instead :
        // var folderpath = "file:///storage/emulated/0/Download/";
        var folderpath = cordova.file.externalRootDirectory + "Download/"; //you can select other folders
        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:

/**
 * Convert a base64 string in a Blob according to the data and contentType.
 * 
 * @param b64Data {String} Pure base64 string without contentType
 * @param contentType {String} the content type of the file i.e (application/pdf - text/plain)
 * @param sliceSize {Int} SliceSize to process the byteCharacters
 * @see http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
 * @return Blob
 */
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;
}

/**
 * Create a PDF file according to its database64 content only.
 * 
 * @param folderpath {String} The folder where the file will be created
 * @param filename {String} The name of the file that will be created
 * @param content {Base64 String} Important : The content can't contain the following string (data:application/pdf;base64). Only the base64 string is expected.
 */
function savebase64AsPDF(folderpath,filename,content,contentType){
    // Convert the base64 string in a Blob
    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' //use share to open the open-with-menu.
        }, this.success, this.failure);

 });

Install iOS or Android platform

cordova platform add ios
cordova platform add android

Run the code

cordova run ios
cordova run android

More Info

For more information on setting up Cordova see the documentation

For more info on plugins see the Plugin Development Guide

pdf-generator's People

Contributors

achesser avatar cesarvr avatar chuckytuh avatar cvaldezr avatar imgx64 avatar jcesarmobile avatar jfoclpf avatar lokidokicoki avatar lucashsilva avatar nokrasnov avatar rastafan avatar timbru31 avatar wnbittle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pdf-generator's Issues

reduce quality of pdf

I use the it to generate the invoice as a pdf. But since my images are high quality the pdf gets with around 10 items a size of 20mb. So I need to find a way to reduce the overall quality of the pdf, or the quality of the images before they are added to the pdf.

May this can help

Android Version

I really appreciate that you have published this plugin.
Have you made any progress to implement the pdf generator for android devices, too?
That would be very helpful!

Thanks!

Problem saving 20 page html

I have a screen that is around 20 pages long that contains many images. On calling htmlToPDF the normal pdf "preparing preview" screen would come on. After more than 5 minutes, the pdf preview is displayed or the "preparing preview" window could close without showing the preview. Is there a limit to the number or pages or number of images that can be in the html? I tried and successfully save a 4 page long html with images to pdf.

I have been testing on Galaxy S7.

Create multiple pages?

Is there a way to tell it to create a new page and have it be part of the same document?

Not working after I updated the version to 1.5.4

Hi,
My app was crashing on android 4 with 1.0.4 version so I have updated the pdf-generator version to 1.5.4 with a hope that it would fix the crashing issue. But now pdf generator stopped working. Below is how I use to generate pdf from my app with 1.0.4. is it still correct with 1.5.4 ?

pdf.htmlToPDF({ data: myhtml, documentSize: "A4", landscape: "portrait", type: "base64" }, function(){ }, function(err){ alert('Could Not Generate PDF : '+err) });

I can't Save as PDF

Hi,
I can't save as pdf , the save button is disabled ?
this is how it look

capture

i tested it in android 4.4 and android 6 !
@cesarvr Hope you can fix this issue

Android Use

This library seems fantastic!

I'd like to generate PDF in some random folder from a HTML string with this but,
how?

How to use examples given?

I'm very new to this and I'm just trying to learn js and phonegap/cordova. But I have no idea where to put the example code.

Do I attach it to a button? do I reference in the pdf.js in the index.html? I'm new to this and very confused and google doesn't seem to help with this particular plugin.

can anyone, not just cesarvr, help me out by explaining the use in a little more detail?

sorry if an "issue" is not the best place for this question but I didn't know where else to ask.

Any plans on making this compatible with PhoneGap Build?

I have a PhoneGap Build app I would love to use this with. Do you have a test version, or any plans to make, a version compatible with PGB?

Edit: I just tried this with PhoneGap Build as a plugin and it appeared to build the app correctly. However, I copy and pasted your share example from the site and when a run it I get a success callback (with a success bool as the argument) but nothing happens. I never get the share menu. Any ideas why this might be? I have pasted the exact test code I used below:

pdf.htmlToPDF({
            data: "<html> <h1>  Hello World  </h1> </html>",
            documentSize: "A4",
            landscape: "portrait",
            type: "share" //use share to open the open-with-menu. 
        }, function(success) {
            alert('htmlToPdf: ' + success);
        }, function(error) {
            alert('htmlToPdf FAILURE: ' + error);
        });

iOS - Links to CSS don't work

I'm having an issue when sending the plugin an HTML string with link elements in iOS.

On Android, I was not able to get relative paths to work either, however, I was able to rewrite the relative paths to full paths using cordova.file.applicationDirectory/www/[relative path] to make them work.

On iOS, this doesn't work. I've tried relative paths, absolute paths, and many other variations without success. Finally, I decided to debug the linked BNHtmlPdfKit.m source, I noticed that the self.baseUrl property is nil, and as a result, it uses http://localhost for the baseUrl of the webview see here. If I set self.baseUrl to [[NSBundle mainBundle] bundleURL], the relative paths work. I'm guessing that the method you added was this which could be edited to set the self.baseUrl via a configuration property from javascript.

Would you be able to expose a baseUrl property in the configuration object to set this property? I can submit a pull request, but this seemed like a pretty quick/easy change.

Thanks,
William

Accessing image file from device

I am trying to use a file uri for an image that I have saved in the file system, but the generated PDF fails to load the image. This image works fine when used in my app's html. I am guessing that it is a permission issue with this plugin, and its access to the file system, but I am not seeing any errors in the console, nor in xcode when debugging. Can you please look at this? I am trying to do something like this:

pdf.htmlToPDF({
     data:'<img src="file:///var/mobile/Containers/Data/Application/7D3EE2B9-0F1B-4A84-A6CE-4D6F2A7548E6/Library/NoCloud/19881/1499893356224.jpg" />',
     documentSize: 'A4',
     landscape: 'portrait',
     type: 'share'
}

Plugin is not working with images

@cesarvr I am using this plugin to convert html to pdf on my cordova app, but unfortunately it does not work with the CSS property background or background-image.. I also tried img tag. But, no success.

Ionic2 Use

Helo, I am currently trying to use this amazing library with ionic2. But i am very new to ionic2 and cordova platform. and now i encounter the following issue :
"The app stops at the stage of showing "Preparing preview" step described in the following screencast."
screenshot_2017-03-17-20-34-05-928_com android printspooler
What things i need to do else in order to overcome it? Thanks u , really appreciate help

Is posible to convert to PDF the current HTML page?

That's my question.

I only want to print the current HTML page. Is it posible?

Or is posible to call and HTML that is allocated in the app?.. My problem is that ion tags doesn't work when I wrote the full HTML as a data ..

Bad encoding for latin characters: é => é

Hi,

I tried to generate pdf with some latin chars but without success:

In PDFGenerator.java

private void pdfPrinter(...)
if(args.getString(1) != null && !args.getString(1).equals("null")  ) 
  // webview.loadData(args.getString(1), "text/html", null);
  // NOK webview.loadData("Tést", "text/html", null); // => Tést
  webview.loadData("Tést", "text/html", "ISO-8859-1"); // => Tést

Any ideas ?

Impossible to generate the PDF, message "Preparing preview..." never disappears

I try run your sample of Ionic (https://github.com/cesarvr/ionic2-basic-example) and nothing happens, the unique thing that happens is that the home screen is shown. I believe that is because the base64 of document is printed on console.

So, I try use the same sample, but changing the parameter type to "share", so, when I call the function is showed to me the message "Preparing preview..." indicating that the PDF is being generate, but the PDF never is generated for my and the message continues the same.

Can you help me to fix that ?

My android is on version 7.0. Do you think that can be this ?

Usage in a loop

Hello again,

I want to use this plugin in a loop like this:


  var index = 0;
    while (index < this.screeningReports.length) {
      console.log('INDEX', index);
      this.toast.show("exporting..." + index, '500', 'top')
        .subscribe(toast => { console.log('toast ', toast); });
      this.printToPDF(index)
      console.log('is this code ever reached?, returned')
      index += 1;
    }

where printToPDF() looks like this:

  printToPDF(index) {
    console.log('in func print', index)
    let content = document.getElementById(String(index)).innerHTML
    let fullReportDate = new Date(this.screeningReports[index].answers.date)
    let reportDate = fullReportDate.getDate() + '-' + (fullReportDate.getMonth() + 1) + '-' + fullReportDate.getFullYear();
    let fileName = this.screeningReports[index].nhs + '_' + reportDate + '.pdf'
    //generate the pdf.
    cordova.plugins.pdf.htmlToPDF({
      data: content,
      type: "base64"
    },
      (success) => {
        console.log('success: ', success), this.toast.show("exporting...", '1500', 'top')
          .subscribe(toast => { console.log('toast ', toast); });
        let thisFile = this.b64toBlob(String(success));
        this.file.writeFile(this.file.documentsDirectory, fileName, thisFile, false).then(_ => console.log('Should have successfully created file')).catch(err => console.log('File not created'));
      },
      (error) => console.log('error:', error)
    );
  }

but on the first iteration of the loop the plugin seems to halt the rest of the loop on execution. Could you tell me how I could use the plugin in a loop?

Not working on some android devices

Hey,
I have problem with this plugin on some Android devices.
It works perfectly on Android 6.0
But on devices with 5.1 and 7.0 it just dies silently (it does not call success or error callback)
Only info I have about this problem are these two logs from logcat:
W/ResourceType: Failure getting entry for 0x01080af0 (t=7 e=2800) (error -75)
W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 17312

Does anyone have any idea what could cause this?

EXC_BAD_ACCESS

Hi,

My app crash whenever I call this plugin, after debugging it, i'm getting EXC_BAD_ACCESS at line 53 of BNHtmlPdfKit.m because of this line:

L77: pdfKit.failureBlock = failure; of this function saveHTMLAsPdf.

  • No errors on the console.
  • Installed platforms: IOS 4.2.0

I don't have enough experience with ObjectiveC to go deeper and understand the problem, could you please help.

Thanks

Android - Paper Size is always set to A4

On Android, it seems to be applying a max width to the page (when passing HTML).

The effect is that when the HTML is printed, it's not full width in Paper size = Letter (A4?). Changing the Paper size to something else that's smaller, works and the HTML is resized to fit as expected. Changing the Paper size back to Letter or a paper size larger than Letter, it doesn't fit the whole page. You can also see this when changing the orientation to landscape with Letter size.

Looking at the source code, the problem seems to be in the PDFPrinter class here. From what I read, regardless of the user selected print size, this code will force it to render in A4. I'm not sure why that code is there, perhaps to solve some other problem, or maybe some testing code? Either way, when I change that method to:
return attrs;
The printing now works as expected, resizing and filling the whole page in all print sizes.

Thanks,
William

script or canvas drawing is not supported?

A simple image screen with the image drawing with canvas is not printed.
I think maybe it's only support simple css and html page only.

is there any plan to support more simulated webbrowser based print?

Return saved file name/location

Is it possible to return the saved file name/location in onFinish method for Android?
From the print dialog user may choose any folder, create a new folder or change the file name at the time of saving. So how do I get that info.
I need to open the file in some viewer after user saves a file from print dialog.

add browser support

Now I do not really like to use a native wrapper for creating a pdf, but there where problems in all other solutions.

  • jsPDF
    • html2pdf was very blurry or made only one page (took canvas screenshot..)
    • Tried other way's but then it crashed due memory issues when using images
  • pdfmake

Maybe we could somehow use jsPDF or another lib to generate the PDF in the browser platform. Since it would be cool to have a working solutions for all platforms.

generating pdf with list of images

Is it possible to create such number of pdf pages as amount of images?
My generated pdf looks like that

ezgif-1-227e20d892

I want to show one item per page

Turn a section of a template into a PDF

Hello,

I'm using your plugin with Ionic 2 - I'm basically creating an export component which should work by writing data into a hidden div tag (called print-area) which I then send to your PDF plugin. Unfortunately it just keeps crashing. Do you have any ideas what I can do to fix this?

  printToPDF() {

     let content = document.getElementById('print-area');
     const before = Date.now();
    document.addEventListener('deviceready', () => {
                console.log('DEVICE READY FIRED AFTER', (Date.now() - before), 'ms');

                //generate the pdf.
                cordova.plugins.pdf.htmlToPDF({
                        data: content,
                        type: "share"
            
                    },
                    (sucess) => console.log('sucess: ', sucess),
                    (error) => console.log('error:', error));
            });

  }

Not Generating PDF

Hi, I'm currently trying to generate a PDF from my Android device. Unfortunately, when I try to generate it nothing happens. This is the code I'm using:

let options = {
      documentSize: 'A4',
      type: 'share'
}

pdf.usingURL('http://192.168.1.171/table.php', options).then(() => alert('ok')).catch((err) => alert(err))

Any help will be greatly appreciated! :)

These are my cordova plugins installed:

cordova-pdf-generator 1.9.3 "PDFGenerator"
cordova-plugin-whitelist 1.3.3 "Whitelist"

Android Version:
Android Version 7.0

How to display variable from javascript into the pdf

This is the code I attempted to run

var orderID = 12345;
var rando = "abc"

window.onload = function() {

        document.getElementById('contact-number').innerHTML = orderID;
        document.getElementById('things').innerHTML = rando;

    }


    document.addEventListener('deviceready', () => {


        //generate the pdf.
        cordova.plugins.pdf.htmlToPDF({
                data: "<html> <h1>  Hello World  </h1> <h1> Order Number at <span id='contact-number'></span></h1> <h1> Random Variable </h1> <span id='things'></span></html>",

            },
            (sucess) => console.log('sucess: ', sucess),
            (error) => console.log('error:', error));
    });

Span id = "things" and span id contact-number returns nothing

Saving Base64

Hello,

Sorry for bugging you with issues - I'm now having trouble writing the Base64 generated by the plugin to a file - all I get are blank PDFs

This is what I'm doing to try and turn the Base64 into a PDF file that I can save on an iPad. I've tested it with other Base64 from elsewhere and had it working fine though.

Here's my code:

let thisFile = this.b64toBlob(success);
  
            this.file.writeFile(this.file.documentsDirectory, 'mytest.pdf', thisFile, true).then(_ => console.log('Should have successfully created file')).catch(err => console.log('File not created'));
       

b64toBlob(b64Data) {
    let contentType = "application/pdf"
    //contentType = contentType || '';
    var sliceSize = 512;
    b64Data = b64Data.replace(/^[^,]+,/, '');
    b64Data = b64Data.replace(/\s/g, '');
    var byteCharacters = window.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);
    }
    console.log('byteArrays ',byteArrays)
    var blob = new Blob(byteArrays, { type: contentType });
     //console.log('blob ', blob)
    return blob;
  }

Saved File name

I am getting "default" as file name when saving. How we can give file name with extension in this for "Generate & Share" button?

How can I access the PDF?

I'm a bit new to app development so bear with me! How would I access a PDF created with type:share? Where does it go in the file system? Should I get a popup with sharing options, like Save PDF to iBooks? Thanks!

Error when opening database after closing plugin view on Android

Hi,
we get an error when trying to access database after using this plugin on Android. The error shown is the following:

"Uncaught SecurityError: Failed to execute 'openDatabase' on 'Window': Access to the WebDatabase API is denied in this context."

How to reproduce:

1)Execute htmlToPdf function from cordova application
2)Exit the newly opened view
3)Try to open database with window.openDatabase(...). The error should now be shown in console.

How can we fix this?

Thanks.

pdf document without any margins

Hi,

I am trying to control the pdf page margin as my CSS & HTML removes any margins or padding but the resulting PDF or PDF Preview always shows white margin around my content, this screen shows what i am trying to do

white-margin

I also noticed that print attributes were not set in case of saving the PDF file and i tried to set it in File output by updating PrintAttributes in printManager but this did not fix my problem


        PrintAttributes attributes = new PrintAttributes.Builder()
        .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
        .setResolution(new PrintAttributes.Resolution("pdf", "pdf", 600, 600))
        .setMinMargins(PrintAttributes.Margins.NO_MARGINS).build();  

        printManager.print(PRINT_JOB_NAME, pdfPrinter, attributes);

file size

I'm creating a pdf that includes two jpgs (~120KB each) and 3 small text tables and the resulting pdf (attached) is 10.8MB (which is quite large as additional jpgs and tables need to be added). Is there an optimization feature available?
webview.pdf

Ios: Thread Warning

When trying to render a pdf of more then a few lines I am getting a warning on IOS:
THREAD WARNING: ['PDFService'] took '15.165771' ms. Plugin should use a background thread.

After the warning the entire app becomes unresponsive. Any suggestions?

Android Base64

Is it possible to get the base64 string when creating a PDF in android, also can we prvent the print preview from automatically being called.

Ideally I would like to be able to store the PDFs created in one folder with the app's external storage data, this way the end user can't save them in the wrong place and I can easily display a history of created PDFs.

Kind regards

Lee

Could not install from "node_modules/cordova-pdf-generator" as it does not contain a package.json file.

following these steps;

image

and/or

image

getting this error;

$ cordova plugin add cordova-pdf-generator
Error: Failed to fetch plugin file:node_modules/cordova-pdf-generator via registry.
Probably this is either a connection problem, or plugin spec is incorrect.
Check your connection and plugin name/version/URL.
Error: npm: Command failed with exit code 1 Error output:
npm ERR! code ENOLOCAL
npm ERR! Could not install from "node_modules/cordova-pdf-generator" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/noshu/.npm/_logs/2017-11-30T11_16_46_455Z-debug.log

also;

$ cordova plugins add node_modules/cordova-pdf-generator
Error: Registry returned 404 for GET on https://registry.npmjs.org/nexxdeli-app

also;

$ ionic cordova plugin add cordova-pdf-generator
> cordova plugin add cordova-pdf-generator --save
Error: Failed to fetch plugin file:node_modules/cordova-pdf-generator via registry.
Probably this is either a connection problem, or plugin spec is incorrect.
Check your connection and plugin name/version/URL.
Error: npm: Command failed with exit code 1 Error output:
npm ERR! code ENOLOCAL
npm ERR! Could not install from "node_modules/cordova-pdf-generator" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/noshu/.npm/_logs/2017-11-30T11_20_37_798Z-debug.log

[ERROR] An error occurred while running cordova plugin add cordova-pdf-generator --save (exit code 1).

environment;

$ cordova -v
7.0.1
$ ionic -v
3.18.0

Can't use local image

Hello,

I try to export a pdf with some local image in it. I know the file's path and the image is correctly showing in the Cordova App.

This is the part of the HTML with the image:

<img src="file:///storage/emulated/0/POC/myimage.jpg">

And this is the JS part :

pdf.htmlToPDF({
    data: pdfDatas,
    documentSize: "A4",
    landscape: "portrait",
    type: "base64"
});

But the script failed to show the image on the pdf. I've tried with a web image and there is no problem. Add or remove type: "base64" change nothing.

How can I correctly add local image in the pdf ?

Crashes app on Start

Why does the plugin crash the app when I make a call to it? Not working at all for me.

Problem with saving PDF

Hello guys , i had successfly installed this plugin in IONIC 3 project . everything work great , but how can save as PDF ? because in documentation they just print console.log(success) ??? !
if i look to my output console , this is the result

console.log: sucess: JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9DcmVhdG9yIChDaHJvbWl1bSkKL1Byb2R1Y2VyIChT a2lhL1BERiBtNTUpCi9DcmVhdGlvbkRhdGUgKEQ6MjAxNzEwMjUxODIzNDgrMDAnMDAnKQovTW9k RGF0ZSAoRDoyMDE3MTAyNTE4MjM0OCswMCcwMCcpPj4KZW5kb2JqCjIgMCBvYmoKPDwvRmlsdGVy
...............................

pdf with lots of pictures

In my project, customer does lots photos, describe each and generate document for printing with high res images.

HTML text with image binaries inside become critically big for plugin, and
depend of photos count/photos size app crashes during pdf generation.

I have decrease photos quality and size, but it pretty critical, because it show details of inspected stuff.

I use Ionic over IOS at Ipad Air 2

Ionic 2 app crashing when calling htmlToPDF

Hey Cesar, I already installed the plugin on my Ionic 2 project, but my app crashes when the htmlToPDF method is called, the OS just shows this message "Se ha detenido la Aplicacion"/ "The app has stopped".

Thanks.

Android Share reports success, doesn't do anything

Hi.

I've just installed the plugin and am testing it on Samsung Galaxy S6 6.0.1. Testing the function, I'm always getting success, but nothing appears on my screen:

window.pdf.htmlToPDF({
            url: "http://www.google.es",
            documentSize: "A4",
            landscape: "portrait",
            type: "share"
        }, function (data) { console.log('ok', data) }, function (data) { console.log('err', data) });

Output:

ok success

image

Additional data:
plugin version: 1.0.11
cordova: 6.5.0
device and os version: Samsung Galaxy S6 6.0.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.