├── LICENSE ├── README.md ├── plugin.xml ├── src ├── android │ ├── Html2pdf.java │ └── libs │ │ └── iText-4.2.0-com.itextpdf.jar └── ios │ ├── Html2pdf.h │ ├── Html2pdf.m │ └── NDHTMLtoPDF │ ├── LICENSE │ └── README.md └── www └── Html2pdf.js /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License (html 2 pdf ios, see: https://github.com/iclems/iOS-htmltopdf) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so, 8 | subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 15 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 16 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN 17 | AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 18 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | 20 | 21 | 22 | Apache License 23 | Version 2.0, January 2004 24 | http://www.apache.org/licenses/ 25 | 26 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 27 | 28 | 1. Definitions. 29 | 30 | "License" shall mean the terms and conditions for use, reproduction, and 31 | distribution as defined by Sections 1 through 9 of this document. 32 | 33 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 34 | owner that is granting the License. 35 | 36 | "Legal Entity" shall mean the union of the acting entity and all other entities 37 | that control, are controlled by, or are under common control with that entity. 38 | For the purposes of this definition, "control" means (i) the power, direct or 39 | indirect, to cause the direction or management of such entity, whether by 40 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 41 | outstanding shares, or (iii) beneficial ownership of such entity. 42 | 43 | "You" (or "Your") shall mean an individual or Legal Entity exercising 44 | permissions granted by this License. 45 | 46 | "Source" form shall mean the preferred form for making modifications, including 47 | but not limited to software source code, documentation source, and configuration 48 | files. 49 | 50 | "Object" form shall mean any form resulting from mechanical transformation or 51 | translation of a Source form, including but not limited to compiled object code, 52 | generated documentation, and conversions to other media types. 53 | 54 | "Work" shall mean the work of authorship, whether in Source or Object form, made 55 | available under the License, as indicated by a copyright notice that is included 56 | in or attached to the work (an example is provided in the Appendix below). 57 | 58 | "Derivative Works" shall mean any work, whether in Source or Object form, that 59 | is based on (or derived from) the Work and for which the editorial revisions, 60 | annotations, elaborations, or other modifications represent, as a whole, an 61 | original work of authorship. For the purposes of this License, Derivative Works 62 | shall not include works that remain separable from, or merely link (or bind by 63 | name) to the interfaces of, the Work and Derivative Works thereof. 64 | 65 | "Contribution" shall mean any work of authorship, including the original version 66 | of the Work and any modifications or additions to that Work or Derivative Works 67 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 68 | by the copyright owner or by an individual or Legal Entity authorized to submit 69 | on behalf of the copyright owner. For the purposes of this definition, 70 | "submitted" means any form of electronic, verbal, or written communication sent 71 | to the Licensor or its representatives, including but not limited to 72 | communication on electronic mailing lists, source code control systems, and 73 | issue tracking systems that are managed by, or on behalf of, the Licensor for 74 | the purpose of discussing and improving the Work, but excluding communication 75 | that is conspicuously marked or otherwise designated in writing by the copyright 76 | owner as "Not a Contribution." 77 | 78 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 79 | of whom a Contribution has been received by Licensor and subsequently 80 | incorporated within the Work. 81 | 82 | 2. Grant of Copyright License. 83 | 84 | Subject to the terms and conditions of this License, each Contributor hereby 85 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 86 | irrevocable copyright license to reproduce, prepare Derivative Works of, 87 | publicly display, publicly perform, sublicense, and distribute the Work and such 88 | Derivative Works in Source or Object form. 89 | 90 | 3. Grant of Patent License. 91 | 92 | Subject to the terms and conditions of this License, each Contributor hereby 93 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 94 | irrevocable (except as stated in this section) patent license to make, have 95 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 96 | such license applies only to those patent claims licensable by such Contributor 97 | that are necessarily infringed by their Contribution(s) alone or by combination 98 | of their Contribution(s) with the Work to which such Contribution(s) was 99 | submitted. If You institute patent litigation against any entity (including a 100 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 101 | Contribution incorporated within the Work constitutes direct or contributory 102 | patent infringement, then any patent licenses granted to You under this License 103 | for that Work shall terminate as of the date such litigation is filed. 104 | 105 | 4. Redistribution. 106 | 107 | You may reproduce and distribute copies of the Work or Derivative Works thereof 108 | in any medium, with or without modifications, and in Source or Object form, 109 | provided that You meet the following conditions: 110 | 111 | You must give any other recipients of the Work or Derivative Works a copy of 112 | this License; and 113 | You must cause any modified files to carry prominent notices stating that You 114 | changed the files; and 115 | You must retain, in the Source form of any Derivative Works that You distribute, 116 | all copyright, patent, trademark, and attribution notices from the Source form 117 | of the Work, excluding those notices that do not pertain to any part of the 118 | Derivative Works; and 119 | If the Work includes a "NOTICE" text file as part of its distribution, then any 120 | Derivative Works that You distribute must include a readable copy of the 121 | attribution notices contained within such NOTICE file, excluding those notices 122 | that do not pertain to any part of the Derivative Works, in at least one of the 123 | following places: within a NOTICE text file distributed as part of the 124 | Derivative Works; within the Source form or documentation, if provided along 125 | with the Derivative Works; or, within a display generated by the Derivative 126 | Works, if and wherever such third-party notices normally appear. The contents of 127 | the NOTICE file are for informational purposes only and do not modify the 128 | License. You may add Your own attribution notices within Derivative Works that 129 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 130 | provided that such additional attribution notices cannot be construed as 131 | modifying the License. 132 | You may add Your own copyright statement to Your modifications and may provide 133 | additional or different license terms and conditions for use, reproduction, or 134 | distribution of Your modifications, or for any such Derivative Works as a whole, 135 | provided Your use, reproduction, and distribution of the Work otherwise complies 136 | with the conditions stated in this License. 137 | 138 | 5. Submission of Contributions. 139 | 140 | Unless You explicitly state otherwise, any Contribution intentionally submitted 141 | for inclusion in the Work by You to the Licensor shall be under the terms and 142 | conditions of this License, without any additional terms or conditions. 143 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 144 | any separate license agreement you may have executed with Licensor regarding 145 | such Contributions. 146 | 147 | 6. Trademarks. 148 | 149 | This License does not grant permission to use the trade names, trademarks, 150 | service marks, or product names of the Licensor, except as required for 151 | reasonable and customary use in describing the origin of the Work and 152 | reproducing the content of the NOTICE file. 153 | 154 | 7. Disclaimer of Warranty. 155 | 156 | Unless required by applicable law or agreed to in writing, Licensor provides the 157 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 158 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 159 | including, without limitation, any warranties or conditions of TITLE, 160 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 161 | solely responsible for determining the appropriateness of using or 162 | redistributing the Work and assume any risks associated with Your exercise of 163 | permissions under this License. 164 | 165 | 8. Limitation of Liability. 166 | 167 | In no event and under no legal theory, whether in tort (including negligence), 168 | contract, or otherwise, unless required by applicable law (such as deliberate 169 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 170 | liable to You for damages, including any direct, indirect, special, incidental, 171 | or consequential damages of any character arising as a result of this License or 172 | out of the use or inability to use the Work (including but not limited to 173 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 174 | any and all other commercial damages or losses), even if such Contributor has 175 | been advised of the possibility of such damages. 176 | 177 | 9. Accepting Warranty or Additional Liability. 178 | 179 | While redistributing the Work or Derivative Works thereof, You may choose to 180 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 181 | other liability obligations and/or rights consistent with this License. However, 182 | in accepting such obligations, You may act only on Your own behalf and on Your 183 | sole responsibility, not on behalf of any other Contributor, and only if You 184 | agree to indemnify, defend, and hold each Contributor harmless for any liability 185 | incurred by, or claims asserted against, such Contributor by reason of your 186 | accepting any such warranty or additional liability. 187 | 188 | END OF TERMS AND CONDITIONS 189 | 190 | APPENDIX: How to apply the Apache License to your work 191 | 192 | To apply the Apache License to your work, attach the following boilerplate 193 | notice, with the fields enclosed by brackets "[]" replaced with your own 194 | identifying information. (Don't include the brackets!) The text should be 195 | enclosed in the appropriate comment syntax for the file format. We also 196 | recommend that a file or class name and description of purpose be included on 197 | the same "printed page" as the copyright notice for easier identification within 198 | third-party archives. 199 | 200 | Copyright [yyyy] [name of copyright owner] 201 | 202 | Licensed under the Apache License, Version 2.0 (the "License"); 203 | you may not use this file except in compliance with the License. 204 | You may obtain a copy of the License at 205 | 206 | http://www.apache.org/licenses/LICENSE-2.0 207 | 208 | Unless required by applicable law or agreed to in writing, software 209 | distributed under the License is distributed on an "AS IS" BASIS, 210 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 211 | See the License for the specific language governing permissions and 212 | limitations under the License. 213 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Html 2 Pdf 2 | ============= 3 | 4 | This is a pdf creation plugin for PCordova 6.1.1+ supporting Android (>4.1) and iOS(>=6.0). 5 | It creates a pdf from the given html and stores it on the device. 6 | 7 | There is one method: 8 | 9 | * create(html, filePath, successCallback, errorCallback) 10 | 11 | Installation 12 | ====== 13 | You may use phonegap CLI as follows: 14 | 15 |
16 | ➜ phonegap local plugin add https://github.com/moderna/cordova-plugin-html2pdf.git
17 | [phonegap] adding the plugin: https://github.com/moderna/cordova-plugin-html2pdf.git
18 | [phonegap] successfully added the plugin
19 | 
20 | 21 | This Plugin requires iText.jar to be added to your project. Here is the last open source version (4.2.0) of it: 22 | 23 | * GitHub: https://github.com/ymasory/iText-4.2.0 24 | * Download .jar:: https://github.com/ymasory/iText-4.2.0/downloads 25 | 26 | It has been confirmed to work with cordova 3.3.0+ 27 | 28 | Usage 29 | ==== 30 | ```javascript 31 | document.addEventListener('deviceready', onDeviceReady); 32 | function onDeviceReady() 33 | { 34 | var success = function(status) { 35 | alert('Message: ' + status); 36 | } 37 | 38 | var error = function(status) { 39 | alert('Error: ' + status); 40 | } 41 | 42 | window.html2pdf.create( 43 | "

Some

html content.

", 44 | "~/Documents/test.pdf", // on iOS, 45 | // "test.pdf", on Android (will be stored in /mnt/sdcard/at.modalog.cordova.plugin.html2pdf/test.pdf) 46 | success, 47 | error 48 | ); 49 | } 50 | ``` -------------------------------------------------------------------------------- /plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Html2pdf 8 | https://github.com/moderna/cordova-plugin-html2pdf.git 9 | html,pdf,android,ios 10 | MIT 11 | Modern Alchemists OG 12 | 13 | <p>Cordova 6.1.1+ plugin for android and ios which converts the given html to a pdf document and stores it on the device.</p> 14 | 15 | This Plugin requires iText.jar to be added to your project. Here is the last open source version (4.2.0) of it: 16 | 17 | GitHub: https://github.com/ymasory/iText-4.2.0 18 | Download .jar:: https://github.com/ymasory/iText-4.2.0/downloads 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/android/Html2pdf.java: -------------------------------------------------------------------------------- 1 | package at.modalog.cordova.plugin.html2pdf; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | 7 | import org.apache.cordova.CallbackContext; 8 | import org.apache.cordova.CordovaPlugin; 9 | import org.apache.cordova.PluginResult; 10 | 11 | import org.json.JSONArray; 12 | import org.json.JSONException; 13 | 14 | import com.itextpdf.text.Document; 15 | import com.itextpdf.text.DocumentException; 16 | import com.itextpdf.text.Element; 17 | import com.itextpdf.text.Image; 18 | import com.itextpdf.text.PageSize; 19 | import com.itextpdf.text.pdf.PdfWriter; 20 | 21 | import android.R.bool; 22 | import android.annotation.TargetApi; 23 | import android.app.Activity; 24 | import android.content.ActivityNotFoundException; 25 | import android.content.Context; 26 | import android.content.Intent; 27 | import android.content.pm.PackageManager; 28 | import android.graphics.Bitmap; 29 | import android.graphics.Canvas; 30 | import android.media.MediaScannerConnection; 31 | import android.media.MediaScannerConnection.OnScanCompletedListener; 32 | import android.net.Uri; 33 | import android.os.Build; 34 | import android.os.Environment; 35 | import android.os.Handler; 36 | import android.print.PrintAttributes; 37 | import android.print.PrintDocumentAdapter; 38 | import android.print.PrintManager; 39 | import android.printservice.PrintJob; 40 | import android.view.View; 41 | import android.view.ViewGroup; 42 | import android.view.ViewGroup.LayoutParams; 43 | import android.webkit.WebSettings; 44 | import android.webkit.WebView; 45 | import android.webkit.WebViewClient; 46 | import android.util.Log; 47 | 48 | @TargetApi(19) 49 | public class Html2pdf extends CordovaPlugin 50 | { 51 | private static final String LOG_TAG = "Html2Pdf"; 52 | private CallbackContext callbackContext; 53 | 54 | // change your path on the sdcard here 55 | private String publicTmpDir = ".at.modalog.cordova.plugin.html2pdf"; // prepending a dot "." would make it hidden 56 | private String tmpPdfName = "print.pdf"; 57 | 58 | // set to true to see the webview (useful for debugging) 59 | private final boolean showWebViewForDebugging = false; 60 | 61 | /** 62 | * Constructor. 63 | */ 64 | public Html2pdf() { 65 | 66 | } 67 | 68 | @Override 69 | public boolean execute (String action, JSONArray args, CallbackContext callbackContext) throws JSONException 70 | { 71 | try 72 | { 73 | if( action.equals("create") ) 74 | { 75 | if( showWebViewForDebugging ) 76 | { 77 | Log.v(LOG_TAG,"java create pdf from html called"); 78 | Log.v(LOG_TAG, "File: " + args.getString(1)); 79 | // Log.v(LOG_TAG, "Html: " + args.getString(0)); 80 | Log.v(LOG_TAG, "Html start:" + args.getString(0).substring(0, 30)); 81 | Log.v(LOG_TAG, "Html end:" + args.getString(0).substring(args.getString(0).length() - 30)); 82 | } 83 | 84 | if( args.getString(1) != null && args.getString(1) != "null" ) 85 | this.tmpPdfName = args.getString(1); 86 | 87 | final Html2pdf self = this; 88 | final String content = args.optString(0, ""); 89 | this.callbackContext = callbackContext; 90 | 91 | cordova.getActivity().runOnUiThread( new Runnable() { 92 | public void run() 93 | { 94 | if( Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT ) // Android 4.4 95 | { 96 | /* 97 | * None-Kitkat pdf creation (Android < 4.4) 98 | */ 99 | 100 | self.loadContentIntoWebView(content); 101 | } 102 | else 103 | { 104 | /* 105 | * Kitkat pdf creation by using the android print framework (Android >= 4.4) 106 | */ 107 | 108 | // Create a WebView object specifically for printing 109 | WebView page = new WebView(cordova.getActivity()); 110 | page.getSettings().setJavaScriptEnabled(false); 111 | page.setDrawingCacheEnabled(true); 112 | // Auto-scale the content to the webview's width. 113 | page.getSettings().setLoadWithOverviewMode(true); 114 | page.getSettings().setUseWideViewPort(true); 115 | page.setInitialScale(0); 116 | // Disable android text auto fit behaviour 117 | page.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); 118 | if( showWebViewForDebugging ) 119 | { 120 | page.setVisibility(View.VISIBLE); 121 | } else { 122 | page.setVisibility(View.INVISIBLE); 123 | } 124 | 125 | // self.cordova.getActivity().addContentView(webView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 126 | page.setWebViewClient( new WebViewClient() 127 | { 128 | public boolean shouldOverrideUrlLoading(WebView view, String url) { 129 | return false; 130 | } 131 | 132 | @Override 133 | public void onPageFinished(WebView view, String url) 134 | { 135 | 136 | // Get a PrintManager instance 137 | PrintManager printManager = (PrintManager) self.cordova.getActivity() 138 | .getSystemService(Context.PRINT_SERVICE); 139 | 140 | // Get a print adapter instance 141 | PrintDocumentAdapter printAdapter = view.createPrintDocumentAdapter(); 142 | 143 | // Get a print builder attributes instance 144 | PrintAttributes.Builder builder = new PrintAttributes.Builder(); 145 | builder.setMinMargins(PrintAttributes.Margins.NO_MARGINS); 146 | // builder.setMediaSize(PrintAttributes.MediaSize.ISO_A4); 147 | // builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR); 148 | // builder.setResolution(new PrintAttributes.Resolution("default", self.tmpPdfName, 600, 600)); 149 | 150 | // send success result to cordova 151 | PluginResult result = new PluginResult(PluginResult.Status.OK); 152 | result.setKeepCallback(false); 153 | self.callbackContext.sendPluginResult(result); 154 | 155 | // Create & send a print job 156 | File filePdf = new File(self.tmpPdfName); 157 | printManager.print(filePdf.getName(), printAdapter, builder.build()); 158 | 159 | 160 | 161 | } 162 | }); 163 | 164 | // Reverse engineer base url (assets/www) from the cordova webView url 165 | String baseURL = self.webView.getUrl(); 166 | baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1); 167 | 168 | // Load content into the print webview 169 | if( showWebViewForDebugging ) 170 | { 171 | cordova.getActivity().addContentView(page, new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 172 | } 173 | page.loadDataWithBaseURL(baseURL, content, "text/html", "utf-8", null); 174 | } 175 | } 176 | }); 177 | 178 | 179 | // send "no-result" result to delay result handling 180 | PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); 181 | pluginResult.setKeepCallback(true); 182 | callbackContext.sendPluginResult(pluginResult); 183 | 184 | return true; 185 | } 186 | return false; 187 | } 188 | catch (JSONException e) 189 | { 190 | // TODO: signal JSON problem to JS 191 | //callbackContext.error("Problem with JSON"); 192 | return false; 193 | } 194 | } 195 | 196 | 197 | /** 198 | * 199 | * Clean up and close all open files. 200 | * 201 | */ 202 | @Override 203 | public void onDestroy() 204 | { 205 | // ToDo: clean up. 206 | } 207 | 208 | // -------------------------------------------------------------------------- 209 | // LOCAL METHODS 210 | // -------------------------------------------------------------------------- 211 | 212 | 213 | /** 214 | * Loads the html content into a WebView, saves it as a single multi page pdf file and 215 | * calls startPdfApp() once it´s done. 216 | */ 217 | private void loadContentIntoWebView (String content) 218 | { 219 | Activity ctx = cordova.getActivity(); 220 | final WebView page = new Html2PdfWebView(ctx); 221 | final Html2pdf self = this; 222 | 223 | if( showWebViewForDebugging ) 224 | { 225 | page.setVisibility(View.VISIBLE); 226 | } else { 227 | page.setVisibility(View.INVISIBLE); 228 | } 229 | page.getSettings().setJavaScriptEnabled(false); 230 | page.setDrawingCacheEnabled(true); 231 | // Don´t auto-scale the content to the webview's width. 232 | page.getSettings().setLoadWithOverviewMode(false); 233 | page.getSettings().setUseWideViewPort(false); 234 | page.setInitialScale(100); 235 | // Disable android text auto fit behaviour 236 | page.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); 237 | 238 | page.setWebViewClient( new WebViewClient() { 239 | @Override 240 | public void onPageFinished(final WebView page, String url) { 241 | new Handler().postDelayed( new Runnable() { 242 | @Override 243 | public void run() 244 | { 245 | // slice the web screenshot into pages and save as pdf 246 | Bitmap b = getWebViewAsBitmap(page); 247 | if( b != null ) 248 | { 249 | File tmpFile = self.saveWebViewAsPdf(b); 250 | 251 | b.recycle(); 252 | 253 | // add pdf as stream to the print intent 254 | Intent pdfViewIntent = new Intent(Intent.ACTION_VIEW); 255 | pdfViewIntent.setDataAndNormalize(Uri.fromFile(tmpFile)); 256 | pdfViewIntent.setType("application/pdf"); 257 | 258 | // remove the webview 259 | if( !self.showWebViewForDebugging ) 260 | { 261 | ViewGroup vg = (ViewGroup)(page.getParent()); 262 | vg.removeView(page); 263 | } 264 | 265 | // add file to media scanner 266 | MediaScannerConnection.scanFile( 267 | self.cordova.getActivity(), 268 | new String[]{tmpFile.getAbsolutePath()}, 269 | null, 270 | new OnScanCompletedListener() { 271 | @Override 272 | public void onScanCompleted(String path, Uri uri) { 273 | Log.v(LOG_TAG, "file '" + path + "' was scanned seccessfully: " + uri); 274 | } 275 | } 276 | ); 277 | 278 | // start the pdf viewer app (trigger the pdf view intent) 279 | PluginResult result; 280 | boolean success = false; 281 | if( self.canHandleIntent(self.cordova.getActivity(), pdfViewIntent) ) 282 | { 283 | try 284 | { 285 | self.cordova.startActivityForResult(self, pdfViewIntent, 0); 286 | success = true; 287 | } 288 | catch( ActivityNotFoundException e ) 289 | { 290 | success = false; 291 | } 292 | } 293 | if( success ) 294 | { 295 | // send success result to cordova 296 | result = new PluginResult(PluginResult.Status.OK); 297 | result.setKeepCallback(false); 298 | self.callbackContext.sendPluginResult(result); 299 | } 300 | else 301 | { 302 | // send error 303 | result = new PluginResult(PluginResult.Status.ERROR, "activity_not_found"); 304 | result.setKeepCallback(false); 305 | self.callbackContext.sendPluginResult(result); 306 | } 307 | } 308 | } 309 | }, 500); 310 | } 311 | }); 312 | 313 | // Set base URI to the assets/www folder 314 | String baseURL = webView.getUrl(); 315 | baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1); 316 | 317 | /** We make it this small on purpose (is resized after page load has finished). 318 | * Making it small in the beginning has some effects on the html (body 319 | * width will always remain 100 if not set explicitly). 320 | */ 321 | if( !showWebViewForDebugging ) 322 | { 323 | ctx.addContentView(page, new ViewGroup.LayoutParams(100, 100)); 324 | } 325 | else 326 | { 327 | ctx.addContentView(page, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 328 | } 329 | page.loadDataWithBaseURL(baseURL, content, "text/html", "utf-8", null); 330 | } 331 | 332 | public static final String MIME_TYPE_PDF = "application/pdf"; 333 | 334 | /** 335 | * Check if the supplied context can handle the given intent. 336 | * 337 | * @param context 338 | * @param intent 339 | * @return boolean 340 | */ 341 | public boolean canHandleIntent(Context context, Intent intent) 342 | { 343 | PackageManager packageManager = context.getPackageManager(); 344 | return (packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0); 345 | } 346 | 347 | /** 348 | * Takes a WebView and returns a Bitmap representation of it (takes a "screenshot"). 349 | * @param WebView 350 | * @return Bitmap 351 | */ 352 | Bitmap getWebViewAsBitmap(WebView view) 353 | { 354 | Bitmap b; 355 | 356 | // prepare drawing cache 357 | view.setDrawingCacheEnabled(true); 358 | view.buildDrawingCache(); 359 | 360 | //Get the dimensions of the view so we can re-layout the view at its current size 361 | //and create a bitmap of the same size 362 | int width = ((Html2PdfWebView) view).getContentWidth(); 363 | int height = view.getContentHeight(); 364 | 365 | if( width == 0 || height == 0 ) 366 | { 367 | // return error answer to cordova 368 | String msg = "Width or height of webview content is 0. Webview to bitmap conversion failed."; 369 | Log.e(LOG_TAG, msg ); 370 | PluginResult result = new PluginResult(PluginResult.Status.ERROR, msg); 371 | result.setKeepCallback(false); 372 | callbackContext.sendPluginResult(result); 373 | 374 | return null; 375 | } 376 | 377 | Log.v(LOG_TAG, "Html2Pdf.getWebViewAsBitmap -> Content width: " + width + ", height: " + height ); 378 | 379 | //Cause the view to re-layout 380 | view.measure(width, height); 381 | view.layout(0, 0, width, height); 382 | 383 | //Create a bitmap backed Canvas to draw the view into 384 | b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 385 | Canvas c = new Canvas(b); 386 | 387 | // draw the view into the canvas 388 | view.draw(c); 389 | 390 | return b; 391 | } 392 | 393 | /** 394 | * Slices the screenshot into pages, merges those into a single pdf 395 | * and saves it in the public accessible /sdcard dir. 396 | */ 397 | private File saveWebViewAsPdf(Bitmap screenshot) { 398 | try { 399 | 400 | File sdCard = Environment.getExternalStorageDirectory(); 401 | File dir = new File (sdCard.getAbsolutePath() + "/" + this.publicTmpDir + "/"); 402 | dir.mkdirs(); 403 | File file; 404 | FileOutputStream stream; 405 | 406 | // creat nomedia file to avoid indexing tmp files 407 | File noMediaFile = new File(dir.getAbsolutePath() + "/", ".nomedia"); 408 | if( !noMediaFile.exists() ) 409 | { 410 | noMediaFile.createNewFile(); 411 | } 412 | 413 | double pageWidth = PageSize.A4.getWidth() * 0.85; // width of the image is 85% of the page 414 | double pageHeight = PageSize.A4.getHeight() * 0.80; // max height of the image is 80% of the page 415 | double pageHeightToWithRelation = pageHeight / pageWidth; // e.g.: 1.33 (4/3) 416 | 417 | Bitmap currPage; 418 | int totalSize = screenshot.getHeight(); 419 | int currPos = 0; 420 | int currPageCount = 0; 421 | int sliceWidth = screenshot.getWidth(); 422 | int sliceHeight = (int) Math.round(sliceWidth * pageHeightToWithRelation); 423 | while( totalSize > currPos && currPageCount < 100 ) // max 100 pages 424 | { 425 | currPageCount++; 426 | 427 | Log.v(LOG_TAG, "Creating page nr. " + currPageCount ); 428 | 429 | // slice bitmap 430 | currPage = Bitmap.createBitmap(screenshot, 0, currPos, sliceWidth, (int) Math.min( sliceHeight, totalSize - currPos )); 431 | 432 | // save page as png 433 | stream = new FileOutputStream( new File(dir, "pdf-page-"+currPageCount+".png") ); 434 | currPage.compress(Bitmap.CompressFormat.PNG, 100, stream); 435 | stream.close(); 436 | 437 | // move current position indicator 438 | currPos += sliceHeight; 439 | 440 | currPage.recycle(); 441 | } 442 | 443 | // create pdf 444 | Document document = new Document(); 445 | File filePdf = new File(sdCard.getAbsolutePath() + "/" + this.tmpPdfName); // change the output name of the pdf here 446 | // create dirs if necessary 447 | if( this.tmpPdfName.contains("/") ) 448 | { 449 | File filePdfDir = new File(filePdf.getAbsolutePath().substring(0, filePdf.getAbsolutePath().lastIndexOf("/"))); // get the dir portion 450 | filePdfDir.mkdirs(); 451 | } 452 | PdfWriter.getInstance(document,new FileOutputStream(filePdf)); 453 | document.open(); 454 | for( int i=1; i<=currPageCount; ++i ) 455 | { 456 | file = new File(dir, "pdf-page-"+i+".png"); 457 | Image image = Image.getInstance (file.getAbsolutePath()); 458 | image.scaleToFit( (float)pageWidth, 9999); 459 | image.setAlignment(Element.ALIGN_CENTER); 460 | document.add(image); 461 | document.newPage(); 462 | } 463 | document.close(); 464 | 465 | // delete tmp image files 466 | for( int i=1; i<=currPageCount; ++i ) 467 | { 468 | file = new File(dir, "pdf-page-"+i+".png"); 469 | file.delete(); 470 | } 471 | 472 | return filePdf; 473 | 474 | } catch (IOException e) { 475 | Log.e(LOG_TAG, "ERROR: " + e.getMessage()); 476 | e.printStackTrace(); 477 | // return error answer to cordova 478 | PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); 479 | result.setKeepCallback(false); 480 | callbackContext.sendPluginResult(result); 481 | } catch (DocumentException e) { 482 | Log.e(LOG_TAG, "ERROR: " + e.getMessage()); 483 | e.printStackTrace(); 484 | // return error answer to cordova 485 | PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); 486 | result.setKeepCallback(false); 487 | callbackContext.sendPluginResult(result); 488 | } 489 | 490 | Log.v(LOG_TAG, "Uncaught ERROR!"); 491 | 492 | return null; 493 | } 494 | 495 | 496 | } 497 | 498 | class Html2PdfWebView extends WebView { 499 | public Html2PdfWebView(Context context) { 500 | super(context); 501 | } 502 | 503 | public int getContentWidth() 504 | { 505 | return this.computeHorizontalScrollRange(); 506 | } 507 | } 508 | -------------------------------------------------------------------------------- /src/android/libs/iText-4.2.0-com.itextpdf.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moderna/cordova-plugin-html2pdf/3a11923dda5f9efab02a7e388ed05250ac7ff218/src/android/libs/iText-4.2.0-com.itextpdf.jar -------------------------------------------------------------------------------- /src/ios/Html2pdf.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 3 | * Html 2 Pdf iOS Code: Clément Wehrung (https://github.com/iclems/iOS-htmltopdf) 4 | * Cordova 3.3 Plugin & Html 2 Pdf Android Code: Modern Alchemists OG (http://modalog.at) 5 | */ 6 | 7 | #import 8 | 9 | #import 10 | 11 | #import "AppDelegate.h" 12 | 13 | #define kPaperSizeA4 CGSizeMake(595.2,841.8) 14 | #define kPaperSizeLetter CGSizeMake(612,792) 15 | 16 | @interface Html2pdf : CDVPlugin 17 | { 18 | } 19 | 20 | // read / write 21 | -(void) create: (CDVInvokedUrlCommand*)command; 22 | 23 | // retain command for async repsonses 24 | @property (nonatomic, strong) CDVInvokedUrlCommand* command; 25 | @property (nonatomic, strong) NSString* filePath; 26 | @property (nonatomic, assign) CGSize pageSize; 27 | @property (nonatomic, assign) UIEdgeInsets pageMargins; 28 | @property (retain) UIDocumentInteractionController* documentController; 29 | 30 | @end 31 | -------------------------------------------------------------------------------- /src/ios/Html2pdf.m: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 Modern Alchemists OG 3 | 4 | Licensed to the Apache Software Foundation (ASF) under one 5 | or more contributor license agreements. See the NOTICE file 6 | distributed with this work for additional information 7 | regarding copyright ownership. The ASF licenses this file 8 | to you under the Apache License, Version 2.0 (the 9 | "License"); you may not use this file except in compliance 10 | with the License. You may obtain a copy of the License at 11 | 12 | http://www.apache.org/licenses/LICENSE-2.0 13 | 14 | Unless required by applicable law or agreed to in writing, 15 | software distributed under the License is distributed on an 16 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | KIND, either express or implied. See the License for the 18 | specific language governing permissions and limitations 19 | under the License. 20 | */ 21 | 22 | /* 23 | * Html 2 Pdf iOS Code: Clément Wehrung (https://github.com/iclems/iOS-htmltopdf) 24 | */ 25 | 26 | #import "Html2pdf.h" 27 | 28 | @interface Html2pdf (Private) 29 | 30 | - (BOOL) saveHtml:(NSString*)html asPdf:(NSString*)filePath; 31 | 32 | @end 33 | 34 | @interface UIPrintPageRenderer (PDF) 35 | 36 | - (NSData*) printToPDF; 37 | 38 | @end 39 | 40 | @implementation Html2pdf 41 | 42 | @synthesize command, filePath, pageSize, pageMargins, documentController; 43 | 44 | - (void)create:(CDVInvokedUrlCommand*)command 45 | { 46 | self.command = command; 47 | 48 | NSArray* arguments = command.arguments; 49 | 50 | NSLog(@"Creating pdf from html has been started."); 51 | 52 | NSString* html = [arguments objectAtIndex:0]; 53 | self.filePath = [[arguments objectAtIndex:1] stringByExpandingTildeInPath]; 54 | 55 | // Set the base URL to be the www directory. 56 | NSString* wwwFilePath = [[NSBundle mainBundle] pathForResource:@"www" ofType:nil]; 57 | NSURL* baseURL = [NSURL fileURLWithPath:wwwFilePath]; 58 | 59 | // define page size and margins 60 | self.pageSize = kPaperSizeA4; 61 | self.pageMargins = UIEdgeInsetsMake(10, 5, 10, 5); 62 | 63 | // Load page into a webview and use its formatter to print the page 64 | UIWebView* webPage = [[UIWebView alloc] init]; 65 | webPage.delegate = self; 66 | webPage.frame = CGRectMake(0, 0, 1, 1); // Make web view small ... 67 | webPage.alpha = 0.0; // ... and invisible. 68 | [self.webView.superview addSubview:webPage]; 69 | 70 | [webPage loadHTMLString:html baseURL:baseURL]; 71 | } 72 | 73 | - (void)success 74 | { 75 | NSString* resultMsg = [NSString stringWithFormat:@"HTMLtoPDF did succeed (%@)", self.filePath]; 76 | NSLog(@"%@",resultMsg); 77 | 78 | // create acordova result 79 | CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK 80 | messageAsString:[resultMsg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 81 | 82 | // send cordova result 83 | [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; 84 | } 85 | 86 | - (void)error:(NSString*)message 87 | { 88 | NSString* resultMsg = [NSString stringWithFormat:@"HTMLtoPDF did fail (%@)", message]; 89 | NSLog(@"%@",resultMsg); 90 | 91 | // create cordova result 92 | CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR 93 | messageAsString:[resultMsg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 94 | 95 | // send cordova result 96 | [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; 97 | } 98 | 99 | - (void)webViewDidFinishLoad:(UIWebView *)webView 100 | { 101 | NSLog(@"Html2Pdf webViewDidFinishLoad"); 102 | 103 | UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init]; 104 | 105 | [render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0]; 106 | 107 | CGRect printableRect = CGRectMake(self.pageMargins.left, 108 | self.pageMargins.top, 109 | self.pageSize.width - self.pageMargins.left - self.pageMargins.right, 110 | self.pageSize.height - self.pageMargins.top - self.pageMargins.bottom); 111 | 112 | CGRect paperRect = CGRectMake(0, 0, self.pageSize.width, self.pageSize.height); 113 | 114 | [render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"]; 115 | [render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"]; 116 | 117 | if (filePath) { 118 | [[render printToPDF] writeToFile: filePath atomically: YES]; 119 | } 120 | 121 | 122 | // remove webPage 123 | [webView stopLoading]; 124 | webView.delegate = nil; 125 | [webView removeFromSuperview]; 126 | webView = nil; 127 | 128 | // trigger success response 129 | [self success]; 130 | 131 | // show "open pdf with ..." menu 132 | NSURL* url = [NSURL fileURLWithPath:filePath]; 133 | self.documentController = [UIDocumentInteractionController interactionControllerWithURL:url]; 134 | 135 | documentController.delegate = self; 136 | 137 | UIView* view = self.webView.superview; 138 | CGRect rect = view.frame; // open in top center 139 | rect.size.height *= 0.02; 140 | 141 | BOOL isValid = [documentController presentOpenInMenuFromRect:rect inView:view animated:YES]; 142 | 143 | if (!isValid) { 144 | NSString* messageString = [NSString stringWithFormat:@"No PDF reader was found on your device. Please download a PDF reader (eg. iBooks or Acrobat)."]; 145 | 146 | UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:messageString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 147 | [alertView show]; 148 | //[alertView release]; // p. leak 149 | } 150 | 151 | } 152 | 153 | - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error 154 | { 155 | NSLog(@"webViewDidFailLoadWithError"); 156 | 157 | // trigger error response 158 | [self error:[error description]]; 159 | } 160 | 161 | 162 | @end 163 | 164 | 165 | @implementation UIPrintPageRenderer (PDF) 166 | 167 | - (NSData*) printToPDF 168 | { 169 | NSMutableData *pdfData = [NSMutableData data]; 170 | 171 | UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil ); 172 | 173 | [self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)]; 174 | 175 | CGRect bounds = UIGraphicsGetPDFContextBounds(); 176 | 177 | for ( int i = 0 ; i < self.numberOfPages ; i++ ) 178 | { 179 | UIGraphicsBeginPDFPage(); 180 | 181 | [self drawPageAtIndex: i inRect: bounds]; 182 | } 183 | 184 | UIGraphicsEndPDFContext(); 185 | 186 | return pdfData; 187 | } 188 | 189 | @end -------------------------------------------------------------------------------- /src/ios/NDHTMLtoPDF/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Clément Wehrung 2 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 3 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 4 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/ios/NDHTMLtoPDF/README.md: -------------------------------------------------------------------------------- 1 | iOS-htmltopdf 2 | ============= 3 | 4 | This class enables simple URL-based PDF creation. Pages are created the exact same way they would be if the user printed the content on an iOS device (very similar as well as OS X print output). 5 | 6 | Example code: 7 | 8 | ``` 9 | self.PDFCreator = [NDHTMLtoPDF createPDFWithURL: 10 | [NSURL URLWithString:@"http://url.com"] 11 | pathForPDF:[@"~/Documents/demo.pdf" stringByExpandingTildeInPath] 12 | delegate:self 13 | pageSize:kPaperSizeA4 14 | margins:UIEdgeInsetsMake(10, 5, 10, 5)]; 15 | ``` 16 | 17 | or using block syntax 18 | 19 | ``` 20 | self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:[NSURL URLWithString:@"http:/url.com"] 21 | pathForPDF:[@"~/Documents/blocksDemo.pdf" stringByExpandingTildeInPath] 22 | pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5) 23 | successBlock:^(NDHTMLtoPDF *htmlToPDF) { 24 | NSLog(@"HTMLtoPDF did succeed (%@ / %@)", htmlToPDF, htmlToPDF.PDFpath); 25 | } errorBlock:^(NDHTMLtoPDF *htmlToPDF) { 26 | NSLog(@"HTMLtoPDF did fail (%@)", htmlToPDF); 27 | }]; 28 | ``` 29 | 30 | You can also use the alternative following code to generate PDF directly from HTML string, without using an URL. This is useful if you want your PDF generator to work offline or if you don't want to write first your code into a local file (you can then use NSURL with a local file through fileURLWithPath:) : 31 | 32 | ``` 33 | + (id)createPDFWithHTML:(NSString*)HTML pathForPDF:(NSString*)PDFpath delegate:(id )delegate pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins; 34 | + (id)createPDFWithHTML:(NSString*)HTML baseURL:(NSURL*)baseURL pathForPDF:(NSString*)PDFpath delegate:(id )delegate pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins; 35 | + (id)createPDFWithHTML:(NSString*)HTML pathForPDF:(NSString*)PDFpath pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins successBlock:(NDHTMLtoPDFCompletionBlock)successBlock errorBlock:(NDHTMLtoPDFCompletionBlock)errorBlock; 36 | + (id)createPDFWithHTML:(NSString*)HTML baseURL:(NSURL*)baseURL pathForPDF:(NSString*)PDFpath pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins successBlock:(NDHTMLtoPDFCompletionBlock)successBlock errorBlock:(NDHTMLtoPDFCompletionBlock)errorBlock; 37 | ``` 38 | 39 | A paper size is only defined by a rect (e.g. kPaperSizeA4 CGSizeMake(595.2,841.8)). 40 | 41 | Please, be sure to create a property (e.g. `PDFCreator`) as NDHTMLtoPDF works asynchronously using UIWebView. 42 | 43 | Feel free to contact me if you have any question ! 44 | 45 | @cwehrung 46 | 47 | cwehrung@nurves.com 48 | 49 | Clément Wehrung 50 | -------------------------------------------------------------------------------- /www/Html2pdf.js: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////// 2 | // Html2pdf.js 3 | // Copyright (C) 2014 Modern Alchemits OG 4 | // 5 | ////////////////////////////////////////// 6 | var exec = require('cordova/exec'); 7 | 8 | var Html2pdf = 9 | { 10 | create : function( html, filePath, success, error ) 11 | { 12 | exec(success, error, "Html2pdf", "create", [html, filePath]) 13 | } 14 | } 15 | 16 | module.exports = Html2pdf; 17 | --------------------------------------------------------------------------------