Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

want to access this js from our js under app/tenant/view/ind #2368


User avatar
0
avanekar02 created

Can you please tell me how i can instantiate this in our js page not frontend, i have attached the js file, i have created a folder under lib in the project and put it there.

the code would go as follows

var pptx = new PptxGenJS(); var slide = pptx.addNewSlide();

slide.addText('Hello world!', { x: 1.0, y: 1.0, font_size: 42, color: '00FF00' }); pptx.save('Demo-Simple');


4 Answer(s)
  • User Avatar
    0
    avanekar02 created

    /* PPTX Units are "DXA" (except for font sizing) ....: There are 1440 DXA per inch. 1 inch is 72 points. 1 DXA is 1/20th's of a point (20 DXA is 1 point). ....: There is also something called EMU's (914400 EMUs is 1 inch, 12700 EMUs is 1pt). SEE: <a class="postlink" href="https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/">https://startbigthinksmall.wordpress.co ... -open-xml/</a> | OBJECT LAYOUTS: 16x9 (10" x 5.625"), 16x10 (10" x 6.25"), 4x3 (10" x 7.5"), Wide (13.33" x 7.5") | REFS: * "Structure of a PresentationML document (Open XML SDK)" * @see: <a class="postlink" href="https://msdn.microsoft.com/en-us/library/office/gg278335.aspx">https://msdn.microsoft.com/en-us/librar ... 78335.aspx</a> * TableStyleId enumeration * @see: <a class="postlink" href="https://msdn.microsoft.com/en-us/library/office/hh273476(v=office.14">https://msdn.microsoft.com/en-us/librar ... =office.14</a>).aspx */

    // Polyfill for IE11 (<a class="postlink" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger">https://developer.mozilla.org/en-US/doc ... /isInteger</a>) Number.isInteger = Number.isInteger || function(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value; };

    // Detect Node.js var NODEJS = ( typeof module !== 'undefined' && module.exports );

    // [Node.js] <script> includes if ( NODEJS ) { var gObjPptxMasters = require('../dist/pptxgen.masters.js'); var gObjPptxShapes = require('../dist/pptxgen.shapes.js'); }

    var PptxGenJS = function(){ // CONSTANTS var APP_VER = "1.1.6"; var APP_REL = "20170119"; var LAYOUTS = { 'LAYOUT_4x3' : { name: 'screen4x3', width: 9144000, height: 6858000 }, 'LAYOUT_16x9' : { name: 'screen16x9', width: 9144000, height: 5143500 }, 'LAYOUT_16x10': { name: 'screen16x10', width: 9144000, height: 5715000 }, 'LAYOUT_WIDE' : { name: 'custom', width: 12191996, height: 6858000 } }; var BASE_SHAPES = { RECTANGLE: { 'displayName': 'Rectangle', 'name': 'rect', 'avLst': {} }, LINE: { 'displayName': 'Line', 'name': 'line', 'avLst': {} } }; var SLDNUMFLDID = '{F7021451-1387-4CA6-816F-3879F97B5CBC}'; var IMG_BROKEN = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAB3CAYAAAD1oOVhAAAGAUlEQVR4Xu2dT0xcRRzHf7tAYSsc0EBSIq2xEg8mtTGebVzEqOVIolz0siRE4gGTStqKwdpWsXoyGhMuyAVJOHBgqyvLNgonDkabeCBYW/8kTUr0wsJC+Wfm0bfuvn37Znbem9mR9303mJnf/Pb7ed95M7PDI5JIJPYJV5EC7e3t1N/fT62trdqViQCIu+bVgpIHEo/Hqbe3V/sdYVKHyWSSZmZm8ilVA0oeyNjYmEnaVC2Xvr6+qg5fAOJAz4DU1dURGzFSqZRVqtMpAFIGyMjICC0vL9PExIRWKADiAYTNshYWFrRCARAOEFZcCKWtrY0GBgaUTYkBRACIE4rKZwqACALR5RQAqQCIDqcASIVAVDsFQCSAqHQKgEgCUeUUAPEBRIVTAMQnEBvK5OQkbW9vk991CoAEAMQJxc86BUACAhKUUwAkQCBBOAVAAgbi1ykAogCIH6cAiCIgsk4BEIVAZJwCIIqBVLqiBxANQFgXS0tLND4+zl08AogmIG5OSSQS1gGKwgtANAIRcQqAaAbCe6YASBWA2E6xDyeyDUl7+AKQMkDYYevm5mZHabA/Li4uUiaTsYLau8QA4gLE/hU7wajyYtv1hReDAiAOxQcHBymbzark4BkbQKom/X8dp9Npmpqasn4BI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aBed1ByA8hTSXA4hmwXndAQhPIc3lAKJZcF53AMJTSHM5gGgWnNcdgPAU0lwOIJoF53UHIDyFNJcfSiCdnZ0Ui8U0SxlMd7lcjubn561gh+Y1scFIU/0o/3sgeLO12E2k7UXKYumgFoAYdg8ACIAYpoBh6cAhAGKYAoalA4cAiGEKGJYOHAIghilgWDpwCIAYpoBh6cAhAGKYAoalA4cAiGEKGJYOHAIghilgWDpwCIAYpoBh6ZQ4JB6PKzviYthnNy4d9h+1M5mMlVckkUjsG5dhiBMCEMPg/wuOfrZZ/RSywQAAAABJRU5ErkJggg=='; var EMU = 914400; // One (1) Inch - OfficeXML measures in EMU (English Metric Units) var ONEPT = 12700; // One (1) point (pt) var CRLF = '\r\n';

    // A: Create internal pptx object
    var gObjPptx = {};
    
    // B: Set Presentation Property Defaults
    gObjPptx.title = 'PptxGenJS Presentation';
    gObjPptx.fileName = 'Presentation';
    gObjPptx.fileExtn = '.pptx';
    gObjPptx.pptLayout = LAYOUTS['LAYOUT_16x9'];
    gObjPptx.slides = [];
    
    // C: Expose shape library to clients
    this.shapes  = (typeof gObjPptxShapes  !== 'undefined') ? gObjPptxShapes  : BASE_SHAPES;
    this.masters = (typeof gObjPptxMasters !== 'undefined') ? gObjPptxMasters : {};
    
    // D: Check for associated .js files and provide warings about anything missing
    if ( typeof gObjPptxShapes === 'undefined' ) gObjPptxShapes = BASE_SHAPES;
    
    
    /**
     * Export the .pptx file (using saveAs - dep. filesaver.js)
     */
    function doExportPresentation() {
    	var intSlideNum = 0, intRels = 0;
    
    	// STEP 1: Create new JSZip file
    	var zip = new JSZip();
    
    	// STEP 2: Add all required folders and files
    	zip.folder("_rels");
    	zip.folder("docProps");
    	zip.folder("ppt").folder("_rels");
    	zip.folder("ppt/media");
    	zip.folder("ppt/slideLayouts").folder("_rels");
    	zip.folder("ppt/slideMasters").folder("_rels");
    	zip.folder("ppt/slides").folder("_rels");
    	zip.folder("ppt/theme");
    
    	zip.file("[Content_Types].xml", makeXmlContTypes());
    	zip.file("_rels/.rels", makeXmlRootRels());
    	zip.file("docProps/app.xml", makeXmlApp());
    	zip.file("docProps/core.xml", makeXmlCore());
    	zip.file("ppt/_rels/presentation.xml.rels", makeXmlPresentationRels());
    
    	// Create a Layout/Master/Rel/Slide file for each SLIDE
    	for ( var idx=0; idx&lt;gObjPptx.slides.length; idx++ ) {
    		intSlideNum++;
    		zip.file(&quot;ppt/slideLayouts/slideLayout&quot;+ intSlideNum +&quot;.xml&quot;, makeXmlSlideLayout( intSlideNum ));
    		zip.file(&quot;ppt/slideLayouts/_rels/slideLayout&quot;+ intSlideNum +&quot;.xml.rels&quot;, makeXmlSlideLayoutRel( intSlideNum ));
    		zip.file(&quot;ppt/slides/slide&quot;+ intSlideNum +&quot;.xml&quot;, makeXmlSlide(gObjPptx.slides[idx]));
    		zip.file(&quot;ppt/slides/_rels/slide&quot;+ intSlideNum +&quot;.xml.rels&quot;, makeXmlSlideRel( intSlideNum ));
    	}
    	zip.file(&quot;ppt/slideMasters/slideMaster1.xml&quot;, makeXmlSlideMaster());
    	zip.file(&quot;ppt/slideMasters/_rels/slideMaster1.xml.rels&quot;, makeXmlSlideMasterRel());
    
    	// Add all images
    	for ( var idx=0; idx&lt;gObjPptx.slides.length; idx++ ) {
    		for ( var idy=0; idy&lt;gObjPptx.slides[idx].rels.length; idy++ ) {
    			var id = gObjPptx.slides[idx].rels[idy].rId - 1;
    			var data = gObjPptx.slides[idx].rels[idy].data;
    			var extn = gObjPptx.slides[idx].rels[idy].extn;
    
    			// A: Users will undoubtedly pass in string in various formats, so modify as needed
    			if      ( data.indexOf(&#39;,&#39;) == -1 &amp;&amp; data.indexOf(&#39;;&#39;) == -1 ) data = &#39;image/png;base64,&#39;+data;
    			else if ( data.indexOf(&#39;,&#39;) == -1 ) data = &#39;image/png;base64,&#39;+data;
    			else if ( data.indexOf(&#39;;&#39;) == -1 ) data = &#39;image/png;&#39;+data;
    
    			// B: Grab base64 encoding header (ex: &quot;data:image/png;base64&quot;)
    			var header = data.substring(0, data.indexOf(&quot;,&quot;));
    
    			// C: Set content and trim the leading base64 header (&#39;data:image/png;base64,&#39;) JSZip only needs the data after &#39;,&#39; (will error otherwiose)
    			var content = data.substring(data.indexOf(&quot;,&quot;) + 1);
    
    			// D: Add image
    			zip.file( &quot;ppt/media/image&quot;+id+&quot;.&quot;+extn, content, {base64:true} );
    		}
    	}
    
    	zip.file(&quot;ppt/theme/theme1.xml&quot;, makeXmlTheme());
    	zip.file(&quot;ppt/presentation.xml&quot;, makeXmlPresentation());
    	zip.file(&quot;ppt/presProps.xml&quot;,    makeXmlPresProps());
    	zip.file(&quot;ppt/tableStyles.xml&quot;,  makeXmlTableStyles());
    	zip.file(&quot;ppt/viewProps.xml&quot;,    makeXmlViewProps());
    
    	// STEP 3: Push the PPTX file to browser
    	var strExportName = ((gObjPptx.fileName.toLowerCase().indexOf(&#39;.ppt&#39;) &gt; -1) ? gObjPptx.fileName : gObjPptx.fileName+gObjPptx.fileExtn);
    	if ( NODEJS ) {
    		zip.generateAsync({type:'nodebuffer'}).then(function(content){ fs.writeFile(strExportName, content); });
    	}
    	else {
    		zip.generateAsync({type:'blob'}).then(function(content){ saveAs(content, strExportName); });
    	}
    }
    
    function componentToHex(c) {
    	var hex = c.toString(16);
    	return hex.length == 1 ? "0" + hex : hex;
    }
    
    /**
     * DESC: Used by `addSlidesForTable()` to convert RGB colors from jQuery selectors to Hex for Presentation colors
     */
    function rgbToHex(r, g, b) {
    	if (! Number.isInteger(r)) { try { console.warn('Integer expected!'); } catch(ex){} }
    	return (componentToHex(r) + componentToHex(g) + componentToHex(b)).toUpperCase();
    }
    
    function inch2Emu(inches) {
    	// FIRST: Provide Caller Safety: Numbers may get conv&lt;-&gt;conv during flight, so be kind and do some simple checks to ensure inches were passed
    	// Any value over 100 damn sure isnt inches, must be EMU already, so just return it
    	if (inches > 100) return inches;
    	if ( typeof inches == 'string' ) inches = Number( inches.replace(/in*/gi,'') );
    	return Math.round(EMU * inches);
    }
    
    
    
    				// C: Add padding [margin] (if any)
    				// NOTE: Margins translate: px->pt 1:1 (e.g.: a 20px padded cell looks the same in PPTX as 20pt Text Inset/Padding)
    				if ( $(cell).css('padding-left') ) {
    					objOpts.marginPt = [];
    					$.each(['padding-top', 'padding-right', 'padding-bottom', 'padding-left'],function(i,val){
    						objOpts.marginPt.push( Math.round($(cell).css(val).replace(/\D/gi,'') * ONEPT) );
    					});
    				}
    
    				// D: Add colspan (if any)
    				if ( $(cell).attr('colspan') ) objOpts.colspan = $(cell).attr('colspan');
    
    				// E: Add border (if any)
    				if ( $(cell).css('border-top-width') || $(cell).css('border-right-width') || $(cell).css('border-bottom-width') || $(cell).css('border-left-width') ) {
    					objOpts.border = [];
    					$.each(['top','right','bottom','left'], function(i,val){
    						var intBorderW = Math.round( Number($(cell).css('border-'+val+'-width').replace('px','')) );
    						var arrRGB = [];
    						arrRGB = $(cell).css('border-'+val+'-color').replace(/\s+/gi,'').replace('rgba(','').replace('rgb(','').replace(')','').split(',');
    						var strBorderC = rgbToHex( Number(arrRGB[0]), Number(arrRGB[1]), Number(arrRGB[2]) );
    						objOpts.border.push( {pt:intBorderW, color:strBorderC} );
    					});
    				}
    
    				// F: Massage cell text so we honor linebreak tag as a line break during line parsing
    				var $cell2 = $(cell).clone();
    				$cell2.html( $(cell).html().replace(/&lt;br[^&gt;]*>/gi,'\n') );
    
    				// LAST: Add cell
    				arrObjTabCells.push({
    					text: $.trim( $cell2.text() ),
    					opts: objOpts
    				});
    			});
    			switch (val) {
    				case 'thead': arrObjTabHeadRows.push( arrObjTabCells ); break;
    				case 'tbody': arrObjTabBodyRows.push( arrObjTabCells ); break;
    				case 'tfoot': arrObjTabFootRows.push( arrObjTabCells ); break;
    				default:
    			}
    		});
    	});
    
    	// STEP 4: Paginate data: Iterate over all table rows, divide into slides/pages based upon the row height>overall height
    	$.each([arrObjTabHeadRows,arrObjTabBodyRows,arrObjTabFootRows], function(iTab,tab){
    		var currRow = [];
    		$.each(tab, function(iRow,row){
    			// A: Reset ROW variables
    			var arrCellsLines = [], arrCellsLineHeights = [], emuRowH = 0, intMaxLineCnt = 0, intMaxColIdx = 0;
    
    			// B: Parse and store each cell's text into line array (*MAGIC HAPPENS HERE*)
    			$(row).each(function(iCell,cell){
    				// 1: Create a cell object for each table column
    				currRow.push({ text:'', opts:cell.opts });
    
    				// 2: Parse cell contents into lines (**MAGIC HAPENSS HERE**)
    				var lines = parseTextToLines($.trim(cell.text), cell.opts.font_size, (arrColW[iCell]/ONEPT));
    				arrCellsLines.push( lines );
    
    				// 3: Keep track of max line count within all row cells
    				if ( lines.length > intMaxLineCnt ) { intMaxLineCnt = lines.length; intMaxColIdx = iCell; }
    			});
    
    			// C: Calculate Line-Height
    			// FYI: Line-Height =~ font-size [px~=pt] * 1.65 / 100 = inches high
    			// FYI: 1px = 14288 EMU (0.156 inches) @96 PPI - I ended up going with 20000 EMU as margin spacing needed a bit more than 1:1
    			$(row).each(function(iCell,cell){
    				var lineHeight = inch2Emu(cell.opts.font_size * 1.65 / 100);
    				if ( Array.isArray(cell.opts.marginPt) && cell.opts.marginPt[0] ) lineHeight += cell.opts.marginPt[0] / intMaxLineCnt;
    				if ( Array.isArray(cell.opts.marginPt) && cell.opts.marginPt[2] ) lineHeight += cell.opts.marginPt[2] / intMaxLineCnt;
    				arrCellsLineHeights.push( Math.round(lineHeight) );
    			});
    
    			// D: AUTO-PAGING: Add text one-line-a-time to this row's cells until: lines are exhausted OR table H limit is hit
    			for (var idx=0; idx&lt;intMaxLineCnt; idx++) {
    				// 1: Add the current line to cell
    				for (var col=0; col&lt;arrCellsLines.length; col++) {
    					// A: Commit this slide to Presenation if table Height limit is hit
    					if ( emuTabCurrH + arrCellsLineHeights[intMaxColIdx] &gt; emuSlideTabH ) {
    						// 1: Add the current row to table
    						// NOTE: Edge cases can occur where we create a new slide only to have no more lines
    						// ....: and then a blank row sits at the bottom of a table!
    						// ....: Hence, we very all cells have text before adding this final row.
    						$.each(currRow, function(i,cell){
    							if (cell.text.length > 0 ) {
    								// IMPORTANT: use jQuery extend (deep copy) or cell will mutate!!
    								arrRows.push( $.extend(true, [], currRow) );
    								return false; // break out of .each loop
    							}
    						});
    						// 2: Add new Slide with current array of table rows
    						arrObjSlides.push( $.extend(true, [], arrRows) );
    						// 3: Empty rows for new Slide
    						arrRows.length = 0;
    						// 4: Reset curr table height for new Slide
    						emuTabCurrH = 0; // This row's emuRowH w/b added below
    						// 5: Empty current row's text (continue adding lines where we left off below)
    						$.each(currRow,function(i,cell){ cell.text = ''; });
    						// 6: Auto-Paging Options: addHeaderToEach
    						if ( opts.addHeaderToEach ) {
    							var headRow = [];
    							$.each(arrObjTabHeadRows[0], function(iCell,cell){
    								headRow.push({ text:cell.text, opts:cell.opts });
    								var lines = parseTextToLines(cell.text, cell.opts.font_size, (arrColW[iCell]/ONEPT));
    								if ( lines.length > intMaxLineCnt ) { intMaxLineCnt = lines.length; intMaxColIdx = iCell; }
    							});
    							arrRows.push( $.extend(true, [], headRow) );
    						}
    					}
    
    					// B: Add next line of text to this cell
    					if ( arrCellsLines[col][idx] ) currRow[col].text += arrCellsLines[col][idx];
    				}
    
    				// 2: Add this new rows H to overall (The cell with the longest line array is the one we use as the determiner for overall row Height)
    				emuTabCurrH += arrCellsLineHeights[intMaxColIdx];
    			}
    
    			// E: Flush row buffer - Add the current row to table, then truncate row cell array
    			// IMPORTANT: use jQuery extend (deep copy) or cell will mutate!!
    			arrRows.push( $.extend(true, [], currRow) );
    			currRow.length = 0;
    		}); // row loop
    	}); // tab loop
    	// Flush final row buffer to slide
    	arrObjSlides.push( $.extend(true,[],arrRows) );
    
    	// STEP 5: Create a SLIDE for each of our 1-N table pieces
    	$.each(arrObjSlides, function(i,slide){
    		// A: Create table row array
    		var arrTabRows = [];
    
    		// B: Create new Slide
    		var newSlide = ( opts.master && gObjPptxMasters ? api.addNewSlide(opts.master) : api.addNewSlide() );
    
    		// C: Create array of Rows
    		$.each(slide, function(i,row){
    			var arrTabRowCells = [];
    			$.each(row, function(i,cell){ arrTabRowCells.push( cell ); });
    			arrTabRows.push( arrTabRowCells );
    		});
    
    		// D: Add table to Slide
    		newSlide.addTable( arrTabRows, { x:(opts.x || arrInchMargins[3]), y:(opts.y || arrInchMargins[0]), cx:(emuSlideTabW/EMU), colW:arrColW } );
    
    		// E: Add any additional objects
    		if ( opts.addImage ) newSlide.addImage({ path:opts.addImage.url, x:opts.addImage.x, y:opts.addImage.y, w:opts.addImage.w, h:opts.addImage.h });
    		if ( opts.addText  ) newSlide.addText(  opts.addText.text,   (opts.addText.opts  || {}) );
    		if ( opts.addShape ) newSlide.addShape( opts.addShape.shape, (opts.addShape.opts || {}) );
    		if ( opts.addTable ) newSlide.addTable( opts.addTable.rows,  (opts.addTable.opts || {}) );
    	});
    }
    

    };

    // [Node.js] support if ( NODEJS ) { // A: Load 2 depdendencies var fs = require("fs"); var $ = require("jquery-node"); var JSZip = require("jszip"); var sizeOf = require("image-size");

    // B: Export module
    module.exports = new PptxGenJS();
    

    }

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    I think this is the framework you use <a class="postlink" href="https://github.com/gitbrent/PptxGenJS">https://github.com/gitbrent/PptxGenJS</a>.

    According to it's explanation, first you need to include these scripts <a class="postlink" href="https://github.com/gitbrent/PptxGenJS#client-side">https://github.com/gitbrent/PptxGenJS#client-side</a>. We already have jquery, so you need to include other 3 scripts.

    Then, in your page's javascript file, you can use it like this <a class="postlink" href="https://github.com/gitbrent/PptxGenJS#presentation-basics">https://github.com/gitbrent/PptxGenJS#p ... ion-basics</a>.

    Do you have an exception ?

  • User Avatar
    0
    avanekar02 created

    yes i followed all the steps and it works fine in the cshtml page, bu what i want is to call this way from the index.js page

    var slide = pptx.addNewSlide();

    because i am filling an array with values and finally when the user presses save i want to collect the data from our vm .array

    and create the slide add the text and then save as pptx.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Can you share your not working code. It is better if you can share full code if index.js.

    Thanks.