Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70429

Canvas2image or html2pdf download div convert to image or pdf

$
0
0

@ivan wrote:

Hello, I would appreciate if someone could help me, since I am a little desperate and I'm a bit of a novice yet ...

I have a div with content referenced by id. That div by the library makes jsPDF download (browser) .pdf content div. It also creates an image within the the contents of the div.

I like that image could download it to the device (iOS and Android) and / or download the pdf generated and / or attach the image generated in an email. The idea really is to share what I've generated in the div somehow. I tried using the plugin file and nothing ngcordova now testing the plugin canvas2image but neither.

I use this to convert to pdf use this div: https://github.com/SajithDulanjaya/HTML2PDF

I show code:

index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <script src="lib/ngCordova/dist/ng-cordova.js"></script> <!-- ngCordova -->

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="lib/html_to_pdf/Blob.js"></script>
    <script src="lib/html_to_pdf/canvas-toBlob.js"></script>
    <script src="lib/html_to_pdf/FileSaver.min.js"></script>
    <script src="lib/html_to_pdf/jspdf.min.js"></script>
    <script src="lib/html_to_pdf/jspdf.plugin.addimage.js"></script>
    <script src="lib/html_to_pdf/jspdf.plugin.png_support.js"></script>
    <script src="lib/html_to_pdf/png.js"></script>
    <script src="lib/html_to_pdf/rasterizeHTML.allinone.js"></script>
    <script src="lib/html_to_pdf/zlib.js"></script>
    <script src="js/app.js"></script>
</head>
<body ng-app="html2pdf" ng-controller="html2pdfCtrl">

<ion-pane>
    <ion-header-bar class="bar-royal">
        <h1 class="title">HTML to PDF Demo</h1>
    </ion-header-bar>
    <ion-content>

        <div align="center" id="thehtml">
            
            <!-- html code... -->

        </div>

        <center>
            <button class="button icon-left ion-archive button-royal" ng-click="generatePDF()">Generate PDF</button>

            <button id="save" class="button icon-left ion-archive button-royal" ng-click="saveResult()">Download image<button>


        </center>

        <center><canvas id="thecanvas" width="790px" height="1200px"></canvas></center>

    </ion-content>
</ion-pane>
</body>
</html>

app.js:

angular.module("html2pdf", ["ionic", 'ngCordova'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.controller("html2pdfCtrl", function($scope, $log, $cordovaInAppBrowser, $cordovaEmailComposer, $cordovaFileOpener2, $ionicLoading) {

  var images;

  $scope.generatePDF = function() {

    /*
     * rasterizeHTML to get html into a canvas
     */
    var canvas = document.getElementById("thecanvas"),
      context = canvas.getContext('2d'),
      html_container = document.getElementById("thehtml"),
      html = html_container.innerHTML;

    rasterizeHTML.drawHTML(html).then(function(renderResult) {
      context.drawImage(renderResult.image, 25, 10);
      try {
        console.log(canvas.toDataURL());
        var content = canvas.toDataURL('image/png');

        console.log("content: " + content); // ivan
        //window.open(content,'_blank','location=yes'); // ivan
        //window.open(canvas.toDataURL('image/png'),'_blank','location=yes'); // ivan

        console.log("generating pdf...");
        //Generating pdf file
        var doc = new jsPDF();
        //Setting properties
        doc.setProperties({
          title: 'Calcey',
          subject: 'Test Subject',
          author: 'Calcey',
          creator: 'Calcey'
        });
        //Adding html content as a png image into the pdf file
        doc.addImage(content, 'PNG', 0, 0);
        doc.setFontSize(10);
        doc.text(188, 290, 'Page ' + 01);
        var data = doc.output();
        var buffer = new ArrayBuffer(data.length);
        var array = new Uint8Array(buffer);

        for (var i = 0; i < data.length; i++) {
          array[i] = data.charCodeAt(i);
        }

        var blob = new Blob(
          [array], {
            type: 'application/pdf',
            encoding: 'raw'
          }
        );

        //Save generated pdf inside local file system
        saveAs(blob, "pdf_output");


        //Accessing the file system through cordova file plugin
        console.log("file system...");
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {

            console.log(fileSystem.name);
            console.log(fileSystem.root.name);
            console.log(fileSystem.root.fullPath);


            fileSystem.root.getFile("pdf_output.pdf", {
              create: true
            }, function(entry) {
              var fileEntry = entry;
              console.log(entry);


              entry.createWriter(function(writer) {
                writer.onwrite = function(evt) {
                  console.log("write success");
                };
                console.log("writing to file");

                //Writing the pdf
                writer.write(blob);

              }, function(error) {
                console.log(error);
              });

            }, function(error) {
              console.log(error);
            });
          },
          function(event) {
            console.log(evt.target.error.code);
          });

        saveAs(blob, "filename");



      } catch (e) {
        console.log("e vale" + e);
        //window.open(e,'_blank','location=yes'); // ivan
      };

      //window.open(content, '_blank', 'location=yes'); // ivan
      images = content;
      console.log("images value: ", images);

    });

    // funcion email
    $scope.sendEmail = function() {
      // 1
      var bodyText = "<h2>Look at this images!</h2>";


      // 4
      window.plugin.email.open({
          to: ["demo@email.com"], // email addresses for TO field
          //cc:          Array, // email addresses for CC field
          //bcc:         Array, // email addresses for BCC field
          //attachments: images, // file paths or base64 data streams
          attachments: [
            'file://img/ionic.png',
            // 'base64:images',
          ],
          subject: "Just some images", // subject of the email
          body: bodyText, // email body (for HTML, set isHtml to true)
          isHtml: true, // indicats if the body is HTML or plain text
        }, function() {
          console.log('email view dismissed');
        },
        this);
    }

  }

  // v2

  // Not use
  var saveButton = document.getElementById("save");
  // Canvas2ImagePlugin
  $scope.saveResult = function() {
    // Actions...
    console.log("Download canvas image...");

    var canvas = document.createElement('thecanvas');
    var ctx = canvas.getContext('2d');
    void ctx.drawImage(this, 0, 0, img.width, img.height);
    var dataURI = canvas.toDataURL().replace(/data:image\/png;base64,/, '');

    function successCallback(result) {
      q.resolve('file:///' + result);
    }

    function failureCallback(err) {
      console.error(err);
      q.reject(err);
    }
    cordova.exec(successCallback, failureCallback, "Canvas2ImagePlugin", "saveImageDataToLibrary", [dataURI]);

  }
  // /v2

})

Thanks you very much.

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70429

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>