1+ // Because of security restrictions, getImageFromUrl will
2+ // not load images from other domains. Chrome has added
3+ // security restrictions that prevent it from loading images
4+ // when running local files. Run with: chromium --allow-file-access-from-files --allow-file-access
5+ // to temporarily get around this issue.
6+ var getImageFromUrl = function ( url , callback ) {
7+ var img = new Image , data , ret = { data : null , pending : true } ;
8+
9+ img . onError = function ( ) {
10+ throw new Error ( 'Cannot load image: "' + url + '"' ) ;
11+ }
12+ img . onload = function ( ) {
13+ var canvas = document . createElement ( 'canvas' ) ;
14+ document . body . appendChild ( canvas ) ;
15+ canvas . width = img . width ;
16+ canvas . height = img . height ;
17+
18+ var ctx = canvas . getContext ( '2d' ) ;
19+ ctx . drawImage ( img , 0 , 0 ) ;
20+ // Grab the image as a jpeg encoded in base64, but only the data
21+ data = canvas . toDataURL ( 'image/jpeg' ) . slice ( 'data:image/jpeg;base64,' . length ) ;
22+ // Convert the data to binary form
23+ data = atob ( data )
24+ document . body . removeChild ( canvas ) ;
25+
26+ ret [ 'data' ] = data ;
27+ ret [ 'pending' ] = false ;
28+ if ( typeof callback === 'function' ) {
29+ callback ( data ) ;
30+ }
31+ }
32+ img . src = url ;
33+
34+ return ret ;
35+ }
36+
37+ // Since images are loaded asyncronously, we must wait to create
38+ // the pdf until we actually have the image data.
39+ // If we already had the jpeg image binary data loaded into
40+ // a string, we create the pdf without delay.
41+ var createPDF = function ( imgData ) {
42+ var doc = new jsPDF ( ) ;
43+
44+ doc . addImage ( imgData , 'JPEG' , 10 , 10 , 50 , 50 ) ;
45+ doc . addImage ( imgData , 'JPEG' , 70 , 10 , 100 , 120 ) ;
46+
47+ doc . save ( 'output.pdf' ) ;
48+
49+ }
50+
51+ getImageFromUrl ( 'thinking-monkey.jpg' , createPDF ) ;
0 commit comments