{"id":19762592,"url":"https://github.com/cesarvr/pdf-generator","last_synced_at":"2025-04-06T02:09:50.016Z","repository":{"id":43175416,"uuid":"52167803","full_name":"cesarvr/pdf-generator","owner":"cesarvr","description":"Cordova plugin to generate pdf in the client-side","archived":false,"fork":false,"pushed_at":"2021-06-02T09:36:03.000Z","size":2713,"stargazers_count":106,"open_issues_count":57,"forks_count":62,"subscribers_count":11,"default_branch":"master","last_synced_at":"2025-03-30T01:11:15.158Z","etag":null,"topics":["android","cordova","pdf","pdf-generation"],"latest_commit_sha":null,"homepage":null,"language":"Objective-C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cesarvr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-02-20T18:12:31.000Z","updated_at":"2024-07-18T20:27:03.000Z","dependencies_parsed_at":"2022-08-21T02:30:10.244Z","dependency_job_id":null,"html_url":"https://github.com/cesarvr/pdf-generator","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cesarvr%2Fpdf-generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cesarvr%2Fpdf-generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cesarvr%2Fpdf-generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cesarvr%2Fpdf-generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cesarvr","download_url":"https://codeload.github.com/cesarvr/pdf-generator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247423515,"owners_count":20936626,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["android","cordova","pdf","pdf-generation"],"created_at":"2024-11-12T04:05:18.879Z","updated_at":"2025-04-06T02:09:49.997Z","avatar_url":"https://github.com/cesarvr.png","language":"Objective-C","funding_links":[],"categories":[],"sub_categories":[],"readme":"# cordova-pdf-generator\n\n## Index \n\u003c!--ts--\u003e\n   * [Getting Started](#gstarted)\n   * [Features](#features)\n   * [How to Install](#install)\n   * [API](#api)\n   * [How Tos](#howto)\n   * [Demo App](#demo)\n\u003c!--te--\u003e\n\n\nSimple 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.   \n\nThe iOS HTML to PDF transformation is based in this work [BNHtmlPdfKit](https://github.com/brentnycum/BNHtmlPdfKit), I just add a new method to allow transformation between plain HTML to PDF.\n\n\n\u003ca name=\"gstarted\"/\u003e\n\n## Getting Started \n\n![Demo](https://raw.githubusercontent.com/cesarvr/pdf-generator/master/img/pdf-generator.gif)\n\nHere you can find a [starting guide](https://dzone.com/articles/how-to-write-a-html-to-pdf-app-for-androidios-usin).\n\n\n\u003ca name=\"features\"/\u003e\n\n## Features\n\n- Generates a PDF document using a URL or HTML.\n- Open-with menu, open the context menu and (push to cloud, print, save, mail, etc...).  \n- Return the Base64 file representation back, so you can upload the file to a server (IOS \u0026 Android only).\n\n\n## Supported Platforms\n\n* Android\n* iOS\n\n\u003ca name=\"install\"/\u003e\n\n## Installing the easy way (Cordova CLI)\n\n    cordova plugin add cordova-pdf-generator\n\n\n## Installing using Plugman\n\n    cordova platform add ios\n    plugman install --platform ios --project platforms/ios --plugin cordova-pdf-generator\n\n\n## Installing using NPM\n\n    npm install cordova-pdf-generator\n    cordova plugins add node_modules/cordova-pdf-generator\n\n\n## Installing the hard way.\n\nClone the plugin\n\n    $ git clone https://github.com/cesarvr/pdf-generator\n\nCreate a new Cordova Project\n\n    $ cordova create hello com.example.helloapp Hello\n\nInstall the plugin\n\n    $ cd hello\n    $ cordova plugin add ../pdf-generator\n\n\n\u003ca name=\"api\"/\u003e\n\n## API\n\nBefore using the plugin just make sure that the device is ready by listening to the onDeviceReady event:\n\n```js\ndocument.addEventListener('deviceready', function(){\n  // start using cordova plugin here.\n})\n\n```\n\n\n### Description\n\nThe plugin expose a global variable named **pdf**, this variable expose the following functions.\n\n#### pdf.fromURL( url, options )\n\nCreates a PDF using a URL, it download the document into an in memory Webkit object, and renders it into a PDF.\n\n- **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.\n\n\nExample:\n\n```js\nlet options = {\n                documentSize: 'A4',\n                type: 'base64'\n              }\n\npdf.fromURL('http://www.google.es', options)\n    .then(()=\u003e'ok')\n    .catch((err)=\u003econsole.err(err))\n```\n\n#### pdf.fromData( url, options )\n\nCreates a PDF using string with the HTML representation, it download the document into an in memory Webkit object, and renders it into a PDF.\n\n- **data** : Takes a string representing the HTML document, it load this in Webkit and creates a PDF.  \n\nExample:\n\n```js\nlet options = {\n                documentSize: 'A4',\n                type: 'base64'\n              }\n\npdf.fromData('\u003chtml\u003e\u003ch1\u003eHello World\u003c/h1\u003e\u003c/html\u003e', options)\n    .then((base64)=\u003e'ok')   // it will\n    .catch((err)=\u003econsole.err(err))\n```\n\n#### Options\n\n##### documentSize\n\n- Its take ```A4, A3, A2``` this specify the format of the paper, just available in iOS, in Android this option is ignored.\n\n##### type\n\n- ```base64``` it will return a Base64 representation of the PDF file. ```{ type: 'base64' } ``, is not type is provided this one is choosen by default. `\n\n```js\nlet options = {\n                documentSize: 'A4',\n                type: 'base64'\n              }\n\npdf.fromData('\u003chtml\u003e\u003ch1\u003eHello World\u003c/h1\u003e\u003c/html\u003e', options)\n    .then((base64)=\u003e console.log(base64) )   // returns base64:JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9DcmVh...\n    .catch((err)=\u003econsole.err(err))\n\n\n```\n\n\n\n- ```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.\n\n```js\nlet options = {\n                documentSize: 'A4',\n                type: 'share'\n              }\n\npdf.fromData( '\u003chtml\u003e\u003ch1\u003eHello World\u003c/h1\u003e\u003c/html\u003e', options)\n    .then((stats)=\u003e console.log('status', stats) )   // ok..., ok if it was able to handle the file to the OS.  \n    .catch((err)=\u003econsole.err(err))\n\n```\n\n\n\n##### filename\n\n- You can specify the name of the PDF file.  \n\n```js\nlet options = {\n                documentSize: 'A4',\n                type: 'share',\n                fileName: 'myFile.pdf'\n              }\n\npdf.fromData( '\u003chtml\u003e\u003ch1\u003eHello World\u003c/h1\u003e\u003c/html\u003e', options)\n    .then((stats)=\u003e console.log('status', stats) )   // ok..., ok if it was able to handle the file to the OS.  \n    .catch((err)=\u003econsole.err(err))\n\n```\n\n\n\u003ca name=\"howto\"/\u003e\n\n#### How Tos\n\n##### Loading an internal CSS, using raw HTML. \n```js \n\n# cssFile have to be the following: \n# iOS: www/\u003ccss-folder\u003e/\u003cyour-file.css\u003e\n# Android: file:///android_asset/www/\u003ccss-folder\u003e/\u003cyour-file.css\u003e\n\nfunction createPDF(cssFile) {\n  var opts = {\n      documentSize: \"A4\",\n      landscape: \"portrait\",\n      type: \"share\",\n      fileName: 'my-pdf.pdf'\n  }\n\n  var payload = _.template(' \u003chead\u003e\u003clink rel=\"stylesheet\" href=\"\u003c%=css_file%\u003e\"\u003e\u003c/head\u003e\u003cbody\u003e \u003ch1\u003e Hello World \u003c/h1\u003e\u003c/body\u003e')\n\n  pdf.fromData(payload({css_file: cssFile}),\n          opts)\n      .then(progressHide)\n      .catch(progressHide);\n}\n\n```\n\n\n\n##### Loading from Device Filesystem.\n\n```js\n\n      //Example: file:///android_asset/index.html\n\n      function printInternalFile(param) {\n\n        /* generate pdf using url. */\n        if(cordova.platformId === 'ios') {\n\n          // To use window.resolveLocalFileSystemURL, we need this plugin https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/\n          // You can add this by doing cordova plugin add cordova-plugin-file or\n          // cordova plugin add https://github.com/apache/cordova-plugin-file\n          window.resolveLocalFileSystemURL(cordova.file.applicationDirectory,\n            (url) =\u003e {\n              var file = param.replace('file:///android_asset/',url.nativeURL);\n\n              pdf.fromURL(file, {\n                  documentsize: 'a4',\n                  landscape: 'portrait',\n                  type: 'share'\n              })\n                .then((stats)=\u003e this.preparetogobackground )\n                .catch((err)=\u003e this.showerror)\n            },\n            (err) =\u003e\n            console.log('error', err, '  args -\u003e', arguments)\n          );\n        }else {\n              pdf.fromURL(param, {\n                  documentsize: 'a4',\n                  landscape: 'portrait',\n                  type: 'share'\n              })\n                .then((stats)=\u003e this.preparetogobackground )\n                .catch((err)=\u003e this.showerror)\n        }\n    }\n```\n\n##### Ionic/Angular 2 Example:\n\n```js\nimport { Component } from '@angular/core';\n\nimport { NavController } from 'ionic-angular';\n\ndeclare var cordova:any;    //global;\n\n@Component({\n  selector: 'page-home',\n  templateUrl: 'home.html'\n})\nexport class HomePage {\n\n  constructor(public navCtrl: NavController) {\n      const before = Date.now();\n\n            document.addEventListener('deviceready', () =\u003e {\n                console.log('DEVICE READY FIRED AFTER', (Date.now() - before), 'ms');\n\n                //generate the pdf.\n                cordova.plugins.pdf.fromData( '\u003chtml\u003e \u003ch1\u003e  Hello World  \u003c/h1\u003e \u003c/html\u003e', options )\n                .then(()=\u003e'ok')\n                .catch((err)=\u003econsole.err(err))\n  }\n\n}\n\n```\n\n##### Saving a pdf file directly into the file system\n\nIf 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`.\n\nHere is an example\n\n```js\nvar fileName = \"myPdfFile.pdf\";\n    \nvar options = {\n    documentSize: 'A4',\n    type: 'base64'                \n};\n\nvar pdfhtml = '\u003chtml\u003e\u003cbody style=\"font-size:120%\"\u003eThis is the pdf content\u003c/body\u003e\u003c/html\u003e';\n        \npdf.fromData(pdfhtml , options)\n    .then(function(base64){               \n        // To define the type of the Blob\n        var contentType = \"application/pdf\";\n            \n        // if cordova.file is not available use instead :\n        // var folderpath = \"file:///storage/emulated/0/Download/\";\n        var folderpath = cordova.file.externalRootDirectory + \"Download/\"; //you can select other folders\n        savebase64AsPDF(folderpath, fileName, base64, contentType);          \n    })  \n    .catch((err)=\u003econsole.err(err));\n\n```    \n\nYou will also need these two functions. Due to javascript functions hoisting you can declare them afterwards as here:\n\n```js\n/**\n * Convert a base64 string in a Blob according to the data and contentType.\n * \n * @param b64Data {String} Pure base64 string without contentType\n * @param contentType {String} the content type of the file i.e (application/pdf - text/plain)\n * @param sliceSize {Int} SliceSize to process the byteCharacters\n * @see http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript\n * @return Blob\n */\nfunction b64toBlob(b64Data, contentType, sliceSize) {\n        contentType = contentType || '';\n        sliceSize = sliceSize || 512;\n\n        var byteCharacters = atob(b64Data);\n        var byteArrays = [];\n\n        for (var offset = 0; offset \u003c byteCharacters.length; offset += sliceSize) {\n            var slice = byteCharacters.slice(offset, offset + sliceSize);\n\n            var byteNumbers = new Array(slice.length);\n            for (var i = 0; i \u003c slice.length; i++) {\n                byteNumbers[i] = slice.charCodeAt(i);\n            }\n\n            var byteArray = new Uint8Array(byteNumbers);\n\n            byteArrays.push(byteArray);\n        }\n\n      var blob = new Blob(byteArrays, {type: contentType});\n      return blob;\n}\n\n/**\n * Create a PDF file according to its database64 content only.\n * \n * @param folderpath {String} The folder where the file will be created\n * @param filename {String} The name of the file that will be created\n * @param content {Base64 String} Important : The content can't contain the following string (data:application/pdf;base64). Only the base64 string is expected.\n */\nfunction savebase64AsPDF(folderpath,filename,content,contentType){\n    // Convert the base64 string in a Blob\n    var DataBlob = b64toBlob(content,contentType);\n    \n    console.log(\"Starting to write the file :3\");\n    \n    window.resolveLocalFileSystemURL(folderpath, function(dir) {\n        console.log(\"Access to the directory granted succesfully\");\n        dir.getFile(filename, {create:true}, function(file) {\n            console.log(\"File created succesfully.\");\n            file.createWriter(function(fileWriter) {\n                console.log(\"Writing content to file\");\n                fileWriter.write(DataBlob);\n            }, function(){\n                alert('Unable to save file in path '+ folderpath);\n            });\n        });\n    });\n}\n```\n\n\n\n#### Deprecated\n\nHere are examples to use the deprecated methods.\n\nThis generates a pdf from a URL, it convert HTML to PDF and returns the file representation in base64.  \n\n```js\n document.addEventListener('deviceready', function() {\n\n        pdf.htmlToPDF({\n            url: 'http://www.google.es',\n            documentSize: 'A4',\n            landscape: 'portrait',\n            type: 'base64'\n        }, this.success, this.failure);\n\n });\n```\n\nThe same but giving HTML without URL.\n\n```js\n document.addEventListener('deviceready', function() {\n\n     pdf.htmlToPDF({\n            data: '\u003chtml\u003e \u003ch1\u003e  Hello World  \u003c/h1\u003e \u003c/html\u003e',\n            documentSize: 'A4',\n            landscape: 'portrait',\n            type: 'base64'\n        }, this.success, this.failure);\n\n });\n\n```\n\nOpening the pdf with other app menu.\n\n```js\n document.addEventListener('deviceready', function() {\n\n     pdf.htmlToPDF({\n            data: '\u003chtml\u003e \u003ch1\u003e  Hello World  \u003c/h1\u003e \u003c/html\u003e',\n            documentSize: 'A4',\n            landscape: 'portrait',\n            type: 'share' //use share to open the open-with-menu.\n        }, this.success, this.failure);\n\n });\n```\n\n\u003ca name=\"demo\"/\u003e\n\n# Demo\n\n- Cordova/Javascript [Demo](https://github.com/cesarvr/pdf-generator-example).\n- Ionic/Angular 2 [Example](https://github.com/cesarvr/ionic2-basic-example)\n\n\nInstall iOS or Android platform\n\n    cordova platform add ios\n    cordova platform add android\n\nRun the code\n\n    cordova run ios\n    cordova run android\n\n## More Info\n\n[here]:https://github.com/cesarvr/pdf-generator-example\n\nFor more information on setting up Cordova see [the documentation](http://cordova.apache.org/docs/en/4.0.0/guide_cli_index.md.html#The%20Command-Line%20Interface)\n\nFor more info on plugins see the [Plugin Development Guide](http://cordova.apache.org/docs/en/4.0.0/guide_hybrid_plugins_index.md.html#Plugin%20Development%20Guide)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcesarvr%2Fpdf-generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcesarvr%2Fpdf-generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcesarvr%2Fpdf-generator/lists"}