forked from stefslon/exportToPPTX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexportToPPTX.m
More file actions
executable file
·2989 lines (2594 loc) · 131 KB
/
exportToPPTX.m
File metadata and controls
executable file
·2989 lines (2594 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function varargout = exportToPPTX(varargin)
% exportToPPTX Creates PowerPoint 2007 (PPTX) slides
%
% exportToPPTX allows user to create PowerPoint 2007 (PPTX) files
% without using COM-objects automation. Proper XML files are created and
% packed into PPTX file that can be read and displayed by PowerPoint.
%
% Note about PowerPoint 2003 and older:
% To open these PPTX files in older PowerPoint software you will need
% to get a free office compatibility pack from Microsoft:
% http://www.microsoft.com/en-us/download/details.aspx?id=3
%
% Basic command syntax:
% exportToPPTX('command',parameters,...)
%
% List of available commands:
%
% new
% Creates new PowerPoint presentation. Actual PowerPoint files
% are not written until 'save' command is called. No required
% inputs. This command does not return any values.
%
% Additional options:
% Dimensions two element vector specifying presentation's
% width and height in inches. Default size is
% 10 x 7.5 in.
% Author specify presentation's author. Default is
% exportToPPTX.
% Title specify presentation's title. Default is
% "Blank".
% Subject specify presentation's subject line. Default is
% empty (blank).
% Comments specify presentation's comments. Default is
% empty (blank).
% BackgroundColor Three element vector specifying RGB
% value in the range from 0 to 1. By default
% background is white.
%
% open
% Opens existing PowerPoint presentation. Requires file name of
% the PowerPoint file to be open. This command does not return
% any values.
%
% addslide
% Adds a slide to the presentation. No additional inputs
% required. Returns newly created slide ID (sequential slide
% number signifying total slides in the deck, not neccessarily
% slide order).
%
% Additional options:
% Position Specify position at which to insert new slide.
% The value must be between 1 and the total
% number of slides.
% BackgroundColor Three element vector specifying RGB
% value in the range from 0 to 1. By default
% background is white.
% Master Master layout ID or name. By default first
% master layout is used.
% Layout Slide template layout ID or name. By default
% first slide template layout is used.
%
% addpicture
% Adds picture to the current slide. Requires figure or axes
% handle or image filename or CDATA to be supplied. Images
% supplied as handles or CDATA matricies are saved in PNG format.
% This command does not return any values.
%
% Additional options:
% Scale Controls how image is placed on the slide
% noscale - No scaling (place figure as is in the
% center of the slide)
% maxfixed - Max size while preserving aspect
% ratio (default)
% max - Max size with no aspect ratio preservation
% Position Four element vector: x, y, width, height (in
% inches) or template placeholder ID or name.
% When exact position is specified Scale property
% is ignored. Coordinates x=0, y=0 are in the
% upper left corner of the slide.
% LineWidth Width of the picture's edge line, a single
% value (in points). Edge is not drawn by
% default. Unless either LineWidth or EdgeColor
% are specified.
% EdgeColor Color of the picture's edge, a three element
% vector specifying RGB value. Edge is not drawn
% by default. Unless either LineWidth or
% EdgeColor are specified.
%
% addtext
% Adds textbox to the current slide. Requires text of the box to
% be added. This command does not return any values.
%
% Additional options:
% Position Four element vector: x, y, width, height (in
% inches) or template placeholder ID or name.
% Coordinates x=0, y=0 are in the upper left corner
% of the slide.
% Color Three element vector specifying RGB value in the
% range from 0 to 1. Default text color is black.
% BackgroundColor Three element vector specifying RGB
% value in the range from 0 to 1. By default
% background is transparent.
% FontSize Specifies the font size to use for text.
% Default font size is 12.
% FontName Specifies font name to be used. Default is
% whatever is template defined font is.
% Specifying FixedWidth for font name will use
% monospaced font defined on the system.
% FontWeight Weight of text characters:
% normal - use regular font (default)
% bold - use bold font
% FontAngle Character slant:
% normal - no character slant (default)
% italic - use slanted font
% Rotation Determines the orientation of the textbox.
% Specify values of rotation in degrees (positive
% angles cause counterclockwise rotation).
% HorizontalAlignment Horizontal alignment of text:
% left - left-aligned text (default)
% center - centered text
% right - right-aligned text
% VerticalAlignment Vertical alignment of text:
% top - top-aligned text (default)
% middle - align to the middle of the textbox
% bottom - bottom-aligned text
% LineWidth Width of the textbox's edge line, a single
% value (in points). Edge is not drawn by
% default. Unless either LineWidth or EdgeColor
% are specified.
% EdgeColor Color of the textbox's edge, a three element
% vector specifying RGB value. Edge is not drawn
% by default. Unless either LineWidth or
% EdgeColor are specified.
%
% addnote
% Add notes information to the current slide. Requires text of
% the notes to be added. This command does not return any values.
% Note: repeat calls overwrite previous information.
%
% Additional options:
% FontWeight Weight of text characters:
% normal - use regular font (default)
% bold - use bold font
% FontAngle Character slant:
% normal - no character slant (default)
% italic - use slanted font
%
% addshape
% Add lines or closed shapes to the current slide. Requires X
% and Y data to be supplied. This command does not return any values.
%
% Additional options:
% ClosedShape Specifies whether the shape is automatically
% closed or not. Default value is false.
% LineWidth Width of the line, a single value (in points).
% Default line width is 1 point. Set LineWidth to
% zero have no edge drawn.
% LineColor Color of the drawn line, a three element
% vector specifying RGB value. Default color is
% black.
% LineStyle Style of the drawn line. Default style is a solid
% line. The following styles are available:
% - (solid), : (dotted), -. (dash dot), -- (dashes)
% BackgroundColor Shape fill color, a three element
% vector specifying RGB value. By default shapes
% are drawn transparent.
%
% addtable
% Adds PowerPoint table to the current slide. Requires table
% content to be supplied in the form of a cell matrix. This
% command does not return any values.
%
% All of the 'addtext' (textbox) additional options apply to the
% table as well.
%
% save
% Saves current presentation. If PowerPoint was created with
% 'new' command, then filename to save to is required. If
% PowerPoint was opened, then by default it will write changes
% back to the same file. If another filename is provided, then
% changes will be written to the new file (effectively a 'Save
% As' operation). Returns full name of the presentation file
% written.
%
% close
% Cleans temporary files and closes current presentation. No
% additional inputs required. No outputs.
%
% saveandclose
% Shortcut to save and close at the same time. No additional
% inputs required. No outputs.
%
% query
% Returns current status either to the command window (if no
% output arguments) or to the output variable. If no presentation
% is currently open, returned value is null.
%
%
% Any textual inputs (addtext, addnote) support basic markdown
% formatting: bulleted lists (lines start with "-"), numbered lists
% (lines start with "#"), bolded text (enclosed in "**"),
% italicized text (enclosed in "*"), underlined text (enclosed in
% "_").
%
%
% A very simple example (see examples_exportToPPTX.m for more):
%
% exportToPPTX('new');
% exportToPPTX('addslide');
% exportToPPTX('addtext','Hello World!');
% exportToPPTX('addpicture',figH);
% exportToPPTX('saveandclose','example');
%
% Author: S.Slonevskiy, 02/11/2013
% File bug reports at:
% https://github.com/stefslon/exportToPPTX/issues
% Versions:
% 02/11/2013, Initial version
% 03/12/2013, Throw a more descriptive error if there is one when writing PPTX file
% Move all constants into PPTXInfo.CONST structure
% Support additional input types for addPicture
% Add additional textbox and image formatting options
% 05/01/2013, Fix a bug with multiple images overwritting each other on slide
% Fix a crash with new PPTX after old one was closed
% 05/24/2013, When setting text alignment, allow for shortcuts 'Horiz' and 'Vert'
% Allow custom Title, Subject, Author entries
% Fix a bug with missing field in the PPTXInfo
% 08/06/2013, Add 'addnote' functionality
% Some bug fixes
% 09/28/2013, Fix broken relationships and add theme2.xml to support Office 2010
% 10/03/2013, Add support for single letter colors
% Bug: fix 'saveandclose' command which crashed before
% Bug: remove syntax supported only by newer MatLab versions
% Bug: fix paragraph breaks in notes fields
% Bug: escape XML entities in notes field
% 04/11/2014, Add option to insert slide at a custom position
% Add markdown to any textual inputs
% 06/13/2014, Bug: multiple entries for new file extensions
% Bug: characters inside the word accidentially being treated as markdown
% Preliminary support for adding video files to the slide
% 03/21/2015, Bug: fixed addPicture input checks to work with HG2
% 06/23/2015, Add 'addshape' functionality
% Add 'OnClick' property to the textbox
% 07/03/2015, Add support for templates (see examples2_exportToPPTX.m for usage examples)
% Add 'addtable' functionality
% Fix tabbing in markdown
% Note default image scaling has been changed from 'noscale' to 'maxfixed'
% 10/20/2015, Add BackgroundColor support to the table
% Fix warning when using word position in the addtext/addtable commands
% Fix negative number being treated a bullet list item
% 02/06/2017, Change by Richard D. Thompson II
% Add support to customizing an individual cell in a table by allowing
% the value passed in to be a cell array of items that are supported
% by `addtext`
%% Keep track of the current PPTX presentation
persistent PPTXInfo
%% Constants
% - EMUs (English Metric Units) are defined as 1/360,000 of a centimeter
% and thus there are 914,400 EMUs per inch, and 12,700 EMUs per point
PPTXInfo.CONST.IN_TO_EMU = 914400;
PPTXInfo.CONST.PT_TO_EMU = 12700;
PPTXInfo.CONST.DEG_TO_EMU = 60000;
PPTXInfo.CONST.FONT_PX_TO_PPTX = 100;
PPTXInfo.CONST.DEFAULT_DIMENSIONS = [10 7.5]; % in inches
%% Initialize PPTXInfo (if it's not initialized yet)
if ~isfield(PPTXInfo,'fileOpen'),
PPTXInfo.fileOpen = false;
end
%% Parse inputs
if nargin==0,
action = 'query';
else
action = varargin{1};
end
%% Set blank outputs
if nargout>0,
varargout = cell(1,nargout);
end
%% Do what we are told to do...
switch lower(action),
case 'new',
%% Check if there is PPTX already in progress
if PPTXInfo.fileOpen,
error('exportToPPTX:fileStillOpen','PPTX file %s already in progress. Save and close first, before starting new file.',PPTXInfo.fullName);
end
%% Check for additional input parameters
PPTXInfo.dimensions = getPVPair(varargin,'Dimensions',round(PPTXInfo.CONST.DEFAULT_DIMENSIONS));
PPTXInfo.dimensions = PPTXInfo.dimensions.*PPTXInfo.CONST.IN_TO_EMU;
if numel(PPTXInfo.dimensions)~=2,
error('exportToPPTX:badDimensions','Slide dimensions vector must have two values only: width x height');
end
PPTXInfo.author = getPVPair(varargin,'Author','exportToPPTX');
PPTXInfo.title = getPVPair(varargin,'Title','Blank');
PPTXInfo.subject = getPVPair(varargin,'Subject','');
PPTXInfo.description = getPVPair(varargin,'Comments','');
PPTXInfo.bgColor = getPVPair(varargin,'BackgroundColor',[]);
if ~isempty(PPTXInfo.bgColor),
if ~isnumeric(PPTXInfo.bgColor) || numel(PPTXInfo.bgColor)~=3,
error('exportToPPTX:badProperty','Bad property value found in BackgroundColor');
end
end
%% Obtain temp folder name
tempName = tempname;
while exist(tempName,'dir'),
tempName = tempname;
end
%% Create temp folder to hold all PPTX files
mkdir(tempName);
PPTXInfo.tempName = tempName;
%% Create new (empty) PPTX files structure
PPTXInfo.fullName = [];
PPTXInfo.createdDate = datestr(now,'yyyy-mm-ddTHH:MM:SS');
initBlankPPTX(PPTXInfo);
%% Load important XML files into memory
PPTXInfo = loadAndParseXMLFiles(PPTXInfo);
%% No outputs
case 'open',
%% Check if there is PPTX already in progress
if PPTXInfo.fileOpen,
error('exportToPPTX:fileStillOpen','PPTX file %s already in progress. Save and close first, before starting new file.',PPTXInfo.fullName);
end
%% Inputs
if nargin<2,
error('exportToPPTX:minInput','Second argument required: filename to create or open');
end
fileName = varargin{2};
%% Check input validity
[filePath,fileName,fileExt] = fileparts(fileName);
if isempty(filePath),
filePath = pwd;
end
if ~strncmpi(fileExt,'.pptx',5),
fileExt = cat(2,fileExt,'.pptx');
end
fullName = fullfile(filePath,cat(2,fileName,fileExt));
PPTXInfo.fullName = fullName;
%% Obtain temp folder name
tempName = tempname;
while exist(tempName,'dir'),
tempName = tempname;
end
%% Create temp folder to hold all PPTX files
mkdir(tempName);
PPTXInfo.tempName = tempName;
%% Check destination location/file
if exist(fullName,'file'),
% Open
openExistingPPTX(PPTXInfo);
else
error('exportToPPTX:fileNotFound','PPTX to open not found. Start new PPTX using new command');
end
%% Load important XML files into memory
PPTXInfo = loadAndParseXMLFiles(PPTXInfo);
%% No outputs
case 'addslide',
%% Check if there is PPT to add to
if ~PPTXInfo.fileOpen,
error('exportToPPTX:addSlideFail','No PPTX in progress. Start new or open PPTX file using new or open commands');
end
%% Create new blank slide
if nargin>1,
PPTXInfo = addSlide(PPTXInfo,varargin{2:end});
else
PPTXInfo = addSlide(PPTXInfo);
end
%% Outputs
if nargout>0,
varargout{1} = PPTXInfo.currentSlide;
end
case 'switchslide',
%% Check if there is PPT to add to
if ~PPTXInfo.fileOpen,
error('exportToPPTX:switchSlideFail','No PPTX in progress. Start new or open PPTX file using new or open commands');
end
%% Inputs
if nargin<2,
error('exportToPPTX:minInput','Second argument required: slide ID to switch to');
end
%% Switch to an existing slide
PPTXInfo = switchSlide(PPTXInfo,varargin{2});
%% Outputs
if nargout>0,
varargout{1} = PPTXInfo.currentSlide;
end
case 'addpicture',
%% Check if there is PPT to add to
if ~PPTXInfo.fileOpen,
error('exportToPPTX:addPictureFail','No PPTX in progress. Start new or open PPTX file using new or open commands');
end
%% Inputs
if nargin<2,
error('exportToPPTX:minInput','Second argument required: figure handle or filename or CDATA');
end
imgData = varargin{2};
%% Add image
if nargin>2,
PPTXInfo = addPicture(PPTXInfo,imgData,varargin{3:end});
else
PPTXInfo = addPicture(PPTXInfo,imgData);
end
case 'addshape',
%% Check if there is PPT to add to
if ~PPTXInfo.fileOpen,
error('exportToPPTX:addShapeFail','No PPTX in progress. Start new or open PPTX file using new or open commands');
end
%% Inputs
if nargin<3,
error('exportToPPTX:minInput','Two input argument required: X and Y data');
end
xData = varargin{2};
yData = varargin{3};
% Input error checking
if isempty(xData) || isempty(yData),
% Error condition
error('exportToPPTX:badInput','addShape command requires non-empty X and Y data');
end
if size(xData)~=size(yData),
% Error condition
error('exportToPPTX:badInput','addShape command requires X and Y data sizes to match');
end
if numel(xData)==1 || numel(yData)==1,
% Error condition
error('exportToPPTX:badInput','addShape command requires at least two X and Y data point');
end
% If needed, reshape data (dim 1 = segments of a single line, dim 2 = different lines)
if size(xData,1)==1,
xData = reshape(xData,[],1);
yData = reshape(yData,[],1);
end
% Convert to PPTX coordinates
xData = round(xData*PPTXInfo.CONST.IN_TO_EMU);
yData = round(yData*PPTXInfo.CONST.IN_TO_EMU);
%% Add custom geometry (lines in this case)
if nargin>3,
PPTXInfo = addCustGeom(PPTXInfo,xData,yData,varargin{4:end});
else
PPTXInfo = addCustGeom(PPTXInfo,xData,yData);
end
case 'addnote',
%% Check if there is PPT to add to
if ~PPTXInfo.fileOpen,
error('exportToPPTX:addNoteFail','No PPTX in progress. Start new or open PPTX file using new or open commands');
end
%% Inputs
if nargin<2,
error('exportToPPTX:minInput','Second argument required: text for the notes field');
end
notesText = varargin{2};
%% Add notes data
if nargin>2,
PPTXInfo = addNotes(PPTXInfo,notesText,varargin{3:end});
else
PPTXInfo = addNotes(PPTXInfo,notesText);
end
case 'addtext',
%% Check if there is PPT to add to
if ~PPTXInfo.fileOpen,
error('exportToPPTX:addTextFail','No PPTX in progress. Start new or open PPTX file using new or open commands');
end
%% Inputs
if nargin<2,
error('exportToPPTX:minInput','Second argument required: textbox contents');
end
boxText = varargin{2};
%% Add textbox
if nargin>2,
PPTXInfo = addTextbox(PPTXInfo,boxText,varargin{3:end});
else
PPTXInfo = addTextbox(PPTXInfo,boxText);
end
case 'addtable',
%% Check if there is PPT to add to
if ~PPTXInfo.fileOpen,
error('exportToPPTX:addTableFail','No PPTX in progress. Start new or open PPTX file using new or open commands');
end
%% Inputs
if nargin<2,
error('exportToPPTX:minInput','Second argument required: table contents');
end
tableData = varargin{2};
%% Add table
if nargin>2,
PPTXInfo = addTable(PPTXInfo,tableData,varargin{3:end});
else
PPTXInfo = addTable(PPTXInfo,tableData);
end
case 'saveandclose',
%% Check if there is PPT to save
if ~PPTXInfo.fileOpen,
warning('exportToPPTX:noFileOpen','No PPTX in progress. Nothing to save.');
return;
end
%% Inputs
if nargin<2 && isempty(PPTXInfo.fullName),
error('exportToPPTX:minInput','For new presentation filename to save to is required');
end
fullName = exportToPPTX('save',varargin{2:end});
exportToPPTX('close');
%% Output
if nargout>0,
varargout{1} = fullName;
end
case 'save',
%% Check if there is PPT to save
if ~PPTXInfo.fileOpen,
warning('exportToPPTX:noFileOpen','No PPTX in progress. Nothing to save.');
return;
end
%% Inputs
if nargin<2 && isempty(PPTXInfo.fullName),
error('exportToPPTX:minInput','For new presentation filename to save to is required');
end
if nargin>=2,
fileName = varargin{2};
else
fileName = PPTXInfo.fullName;
end
%% Check input validity
[filePath,fileName,fileExt] = fileparts(fileName);
if isempty(filePath),
filePath = pwd;
end
if ~strncmpi(fileExt,'.pptx',5),
fileExt = cat(2,fileExt,'.pptx');
end
fullName = fullfile(filePath,cat(2,fileName,fileExt));
PPTXInfo.fullName = fullName;
%% Add some more useful information
PPTXInfo.revNumber = PPTXInfo.revNumber+1;
PPTXInfo.updatedDate = datestr(now,'yyyy-mm-ddTHH:MM:SS');
%% Commit changes to PPTX file
writePPTX(PPTXInfo);
%% Output
if nargout>0,
varargout{1} = PPTXInfo.fullName;
end
case 'close',
%% Check if there is PPT to add to
if ~PPTXInfo.fileOpen,
warning('exportToPPTX:noFileOpen','No PPTX in progress. Nothing to close.');
return;
end
try
cleanUp(PPTXInfo);
PPTXInfo.fileOpen = false;
catch
end
% Remove fields from PPTXInfo
clear PPTXInfo
case 'query',
if nargout==0,
if ~PPTXInfo.fileOpen,
fprintf('No file open\n');
else
fprintf('File: %s\n',PPTXInfo.fullName);
fprintf('Dimensions: %.2f x %.2f in\n',PPTXInfo.dimensions./PPTXInfo.CONST.IN_TO_EMU);
fprintf('Slides: %d\n',PPTXInfo.numSlides);
fprintf('Current slide: %d\n',PPTXInfo.currentSlide);
if ~isempty(PPTXInfo.SlideMaster),
for imast=1:numel(PPTXInfo.SlideMaster),
fprintf('Master #%d: %s\n',imast,PPTXInfo.SlideMaster(imast).name);
if ~isempty(PPTXInfo.SlideMaster(imast).Layout),
for ilay=1:numel(PPTXInfo.SlideMaster(imast).Layout),
placeHolders = sprintf('%s, ',PPTXInfo.SlideMaster(imast).Layout(ilay).place{:});
if ~isempty(placeHolders),
placeHolders = sprintf('(%s)',placeHolders(1:end-2));
end
fprintf('\tLayout #%d: %s %s\n',ilay,PPTXInfo.SlideMaster(imast).Layout(ilay).name,placeHolders);
end
else
fprintf('\tNo layouts defined.\n');
end
end
else
fprintf('No master layouts defined.\n');
end
end
else
if PPTXInfo.fileOpen,
ret.fullName = PPTXInfo.fullName;
ret.dimensions = PPTXInfo.dimensions./PPTXInfo.CONST.IN_TO_EMU;
ret.numSlides = PPTXInfo.numSlides;
ret.currentSlide = PPTXInfo.currentSlide;
if ~isempty(PPTXInfo.SlideMaster),
for imast=1:numel(PPTXInfo.SlideMaster),
ret.master(imast).name = PPTXInfo.SlideMaster(imast).name;
if ~isempty(PPTXInfo.SlideMaster(imast).Layout),
for ilay=1:numel(PPTXInfo.SlideMaster(imast).Layout),
ret.master(imast).layout(ilay).name = PPTXInfo.SlideMaster(imast).Layout(ilay).name;
ret.master(imast).layout(ilay).placeholders = PPTXInfo.SlideMaster(imast).Layout(ilay).place;
end
else
ret.master(imast).layout = [];
end
end
else
ret.master = [];
end
varargout{1} = ret;
end
end
otherwise,
% Error condition
error('exportToPPTX:badInput','Unrecognized command ''%s''. See help for available commands',lower(action));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function addTxBodyNode(PPTXInfo,fileXML,txBody,inputText,varargin)
% Input: PPTXInfo (for constants), fileXML to modify, rootNode XML node to attach text to, regular text string
% Output: modified XML file
switch lower(getPVPair(varargin,'Horiz','')),
case 'left',
hAlign = {'algn','l'};
case 'right',
hAlign = {'algn','r'};
case 'center',
hAlign = {'algn','ctr'};
case '',
hAlign = {};
otherwise,
error('exportToPPTX:badProperty','Bad property value found in HorizontalAlignment');
end
switch lower(getPVPair(varargin,'Vert','')),
case 'top',
vAlign = {'anchor','t'};
case 'bottom',
vAlign = {'anchor','b'};
case 'middle',
vAlign = {'anchor','ctr'}';
case '',
vAlign = {};
otherwise,
error('exportToPPTX:badProperty','Bad property value found in VerticalAlignment');
end
switch lower(getPVPair(varargin,'FontAngle','')),
case {'italic','oblique'},
fItal = {'i','1'};
case 'normal',
fItal = {'i','0'};
case '',
fItal = {};
otherwise,
error('exportToPPTX:badProperty','Bad property value found in FontAngle');
end
switch lower(getPVPair(varargin,'FontWeight','')),
case {'bold','demi'},
fBold = {'b','1'};
case {'normal','light'},
fBold = {'b','0'};
case '',
fBold = {};
otherwise,
error('exportToPPTX:badProperty','Bad property value found in FontWeight');
end
fCol = validateColor(getPVPair(varargin,'Color',[]));
fSizeVal = getPVPair(varargin,'FontSize',[]);
if ~isnumeric(fSizeVal),
error('exportToPPTX:badProperty','Bad property value found in FontSize');
elseif ~isempty(fSizeVal),
fSize = {'sz',fSizeVal*PPTXInfo.CONST.FONT_PX_TO_PPTX};
else
fSize = {};
end
fNameVal = getPVPair(varargin,'FontName',[]);
if isempty(fNameVal),
fName = '';
elseif ~ischar(fNameVal),
error('exportToPPTX:badProperty','Bad property value found in FontName');
elseif strncmpi(fNameVal,'FixedWidth',10),
fName = get(0,'FixedWidthFontName');
else
fName = fNameVal;
end
jumpSlide = getPVPair(varargin,'OnClick',[]);
if ~isempty(jumpSlide) && (jumpSlide<1 || jumpSlide>PPTXInfo.numSlides || numel(jumpSlide)>1),
% Error condition
error('exportToPPTX:badInput','OnClick slide number must be between 1 and the total number of slides');
end
% Formatting notes:
% p:sp input to this function
% p:nvSpPr non-visual shape props (handled outside)
% p:spPr visual shape props (also handled outside)
% p:txBody <---- created by this subfunction
% a:bodyPr
% a:lstStyle
% a:p paragraph node (one in each ipara loop)
% a:pPr paragraph properties (text alignment, bullet (a:buChar), number (a:buAutoNum) )
% a:r run node (one in each irun loop)
% a:rPr run formatting (bold, italics, font size, etc.)
% a:solidFill text coloring
% a:srfbClr
% a:t text node
% Bad news for text auto-fit: font sizes and line spacing are determined by
% PowerPoint based on fonts measurements. If fontScale and lnSpcReduction
% are filled out in the OpenXML file then PowerPoint doesn't re-render
% those textboxes and simply uses OpenXML values. This means that in order
% for auto-fit to work in this tool font measurements have to be done in
% here.
bodyPr = addNode(fileXML,txBody,'a:bodyPr',{'wrap','square','rtlCol','0',vAlign{:}});
% addNode(fileXML,bodyPr,'a:normAutofit');%,{'fontScale','50.000%','lnSpcReduction','50.000%'}); % autofit flag
addNode(fileXML,txBody,'a:lstStyle');
% Break text into paragraphs and add each paragraph as a separate a:p node
if ischar(inputText),
paraText = regexp(inputText,'\n','split');
else
paraText = inputText;
end
numParas = numel(paraText);
defMargin = 0.3; % inches
for ipara=1:numParas,
ap = addNode(fileXML,txBody,'a:p');
pPr = addNode(fileXML,ap,'a:pPr',hAlign);
% Check for paragraph level markdown: bulletted lists, numbered lists
if ~isempty(paraText{ipara}),
% Make a copy of paragraph text for modification
addParaText = paraText{ipara};
% Re-init here and modify if further down than one level
useMargin = defMargin;
% Check for tabs before removing them
if double(paraText{ipara}(1))==9, % 9=tab characeter
firstNonTabIdx = find(double(paraText{ipara})~=9,1);
numTabs = firstNonTabIdx-1;
useMargin = useMargin*(numTabs+1);
setNodeAttribute(pPr,{'lvl',numTabs});
end
% Clean up (remove extra whitespaces)
addParaText = strtrim(addParaText);
% Bullet and/or number are allowed only if there is a space between
% dash and text that follows (this guards against negative numbers
% showing up as bullets)
if length(paraText{ipara})>=2 && isequal(paraText{ipara}(1:2),'- '),
% if paraText{ipara}(1)=='-' && numParas>1 && ...
% ( (~isempty(paraText{max(ipara-1,1)}) && ipara-1>=1 && paraText{max(ipara-1,1)}(1)=='-') || ...
% (~isempty(paraText{min(ipara+1,numParas)}) && ipara+1<=numParas && paraText{min(ipara+1,numParas)}(1)=='-') ),
addParaText(1) = []; % remove the actual character
setNodeAttribute(pPr,{'marL',useMargin*PPTXInfo.CONST.IN_TO_EMU,'indent',-defMargin*PPTXInfo.CONST.IN_TO_EMU});
addNode(fileXML,pPr,'a:buChar',{'char',''}); % TODO: add character control here
end
if length(paraText{ipara})>=2 && isequal(paraText{ipara}(1:2),'# '),
% if paraText{ipara}(1)=='#' && numParas>1 && ...
% ( (~isempty(paraText{max(ipara-1,1)}) && paraText{max(ipara-1,1)}(1)=='#') || ...
% (~isempty(paraText{min(ipara+1,numParas)}) && paraText{min(ipara+1,numParas)}(1)=='#') ),
addParaText(1) = []; % remove the actual character
setNodeAttribute(pPr,{'marL',useMargin*PPTXInfo.CONST.IN_TO_EMU,'indent',-defMargin*PPTXInfo.CONST.IN_TO_EMU});
addNode(fileXML,pPr,'a:buAutoNum',{'type','arabicPeriod'}); % TODO: add numeral control here
end
% Clean up again in case there were more spaces between markdown
% character and beginning of the text
addParaText = strtrim(addParaText);
% Check for run level markdown: bold, italics, underline
[fmtStart,fmtStop,tokStr,splitStr] = regexpi(addParaText,'\<(*{2}|*{1}|_{1})([ ,:.\w]+)(?=\1)\1\>','start','end','tokens','split');
allRuns = cat(2,1,reshape(cat(1,fmtStart,fmtStop),1,[]));
runTypes = cat(2,-1,reshape(cat(1,1:numel(fmtStart),-(2:numel(splitStr))),1,[]));
numRuns = numel(allRuns);
for irun=1:numRuns,
fItalR = fItal;
fBoldR = fBold;
fUnderR = {}; % u="sng"
if runTypes(irun)<0,
runText = splitStr{-runTypes(irun)};
else
runText = tokStr{runTypes(irun)}{2};
runFormat = tokStr{runTypes(irun)}{1};
if strcmpi(runFormat,'*'), fItalR = {'i','1'}; end
if strcmpi(runFormat,'**'), fBoldR = {'b','1'}; end
if strcmpi(runFormat,'_'), fUnderR = {'u','sng'}; end
end
ar = addNode(fileXML,ap,'a:r'); % run node
rPr = addNode(fileXML,ar,'a:rPr',{'lang','en-US','dirty','0','smtClean','0',fItalR{:},fBoldR{:},fUnderR{:},fSize{:}});
if ~isempty(fCol),
sf = addNode(fileXML,rPr,'a:solidFill');
addNode(fileXML,sf,'a:srgbClr',{'val',fCol});
end
if ~isempty(fName),
addNode(fileXML,rPr,'a:latin',{'typeface',fName});
addNode(fileXML,rPr,'a:cs',{'typeface',fName});
end
if ~isempty(jumpSlide),
addNode(fileXML,rPr,'a:hlinkClick',{'r:id',PPTXInfo.Slide(jumpSlide).rId,'action','ppaction://hlinksldjump'});
nodeAttribute = getNodeAttribute(PPTXInfo.XML.SlideRel,'Relationship','Id');
if ~any(strcmpi(nodeAttribute,PPTXInfo.Slide(jumpSlide).rId)),
addNode(PPTXInfo.XML.SlideRel,'Relationships','Relationship', ...
{'Id',PPTXInfo.Slide(jumpSlide).rId, ...
'Type','http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide', ...
'Target',PPTXInfo.Slide(jumpSlide).file});
end
end
at = addNode(fileXML,ar,'a:t');
addNodeValue(fileXML,at,runText);
end
else
% Empty paragraph, do nothing
end
% Add end paragraph
endParaRPr = addNode(fileXML,ap,'a:endParaRPr',{'lang','en-US','dirty','0'});
if ~isempty(fName),
addNode(fileXML,endParaRPr,'a:latin',{'typeface',fName});
addNode(fileXML,endParaRPr,'a:cs',{'typeface',fName});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function propValue = getPVPair(inputArr,propName,defValue)
% Inputs: input cell array (varargin), property name, default value
% Output: value specified on the input, otherwise default value
if numel(inputArr)>=2 && any(strncmpi(inputArr,propName,length(propName))),
idx = find(strncmpi(inputArr,propName,length(propName)));
propValue = inputArr{idx+1};
else
propValue = defValue;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function colorStr = validateColor(bCol)
if ~isempty(bCol)
if isnumeric(bCol) && numel(bCol)==3,
rgbCol = bCol;
elseif ischar(bCol) && numel(bCol)==1,
switch bCol,
case 'b', % blue
rgbCol = [0 0 1];
case 'g', % green
rgbCol = [0 1 0];
case 'r', % red
rgbCol = [1 0 0];
case 'c', % cyan
rgbCol = [0 1 1];
case 'm', % magenta
rgbCol = [1 0 1];
case 'y', % yellow
rgbCol = [1 1 0];
case 'k', % black
rgbCol = [0 0 0];
case 'w', % white
rgbCol = [1 1 1];
otherwise,
error('exportToPPTX:badProperty','Unknown color code');
end
else
error('exportToPPTX:badProperty','Bad color property value found. Color must be either a three element RGB value or a single color character');
end
colorStr = sprintf('%s',dec2hex(round(rgbCol*255),2).');
else
colorStr = '';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function retCode = writeTextFile(fileName,fileContent)
% Inputs: name of the file, file contents (cell array)
% Outputs: 1 if file was successfully written, 0 otherwise
fId = fopen(fileName,'w','n','UTF-8');
if fId~=-1,
fprintf(fId,'%s\n',fileContent{:});
fclose(fId);
retCode = 1;
else
retCode = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PPTXInfo = loadAndParseXMLFiles(PPTXInfo)