-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathmd2pptx
executable file
·6296 lines (5119 loc) · 216 KB
/
md2pptx
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
#!/usr/bin/env python3
"""
md2pptx - Converts (a subset of) Markdown to Powerpoint (PPTX)
First argument is file to write to
Reads from stdin
"""
import re
import sys
import os
import csv
import time
import collections
import collections.abc
from pptx import Presentation
from pptx import __version__ as pptx_version
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor, MSO_THEME_COLOR
from pptx.enum.text import MSO_AUTO_SIZE, PP_ALIGN
from pptx.enum.shapes import PP_PLACEHOLDER, PP_MEDIA_TYPE
from pptx.enum.shapes import MSO_SHAPE, MSO_CONNECTOR
from pptx.enum.text import MSO_ANCHOR
from pptx.enum.action import PP_ACTION
from pptx.enum.dml import MSO_PATTERN
import struct
import datetime
import html.parser
from pptx.oxml.xmlchemy import OxmlElement
from pathlib import Path
import urllib.request
import tempfile
import copy
import platform
import shutil
import socket
from pptx.oxml import parse_xml
import uuid
import funnel
import runPython
from card import Card
from rectangle import Rectangle
from colour import *
from paragraph import *
from symbols import resolveSymbols
import globals
from processingOptions import *
from lxml import etree
from lxml.html import fromstring
# Try to import CairoSVG - which might not be installed.
# Flag availability or otherwise
try:
import cairosvg
from cairosvg import helpers
have_cairosvg = True
except:
have_cairosvg = False
# Try to import Pillow - which might not be installed.
# Flag availability or otherwise
try:
import PIL
have_pillow = True
except:
have_pillow = False
# Try to import graphviz - which might not be installed.
# Flag availability or otherwise
try:
import graphviz
have_graphviz = True
except:
have_graphviz = False
md2pptx_level = "5.2.2"
md2pptx_date = "31 December, 2024"
namespaceURL = {
"mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",
"p": "http://schemas.openxmlformats.org/presentationml/2006/main",
"p14": "http://schemas.microsoft.com/office/powerpoint/2010/main",
"p15": "http://schemas.microsoft.com/office/powerpoint/2012/main",
"a": "http://schemas.openxmlformats.org/drawingml/2006/main",
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
}
def namespacesFragment(prefixes):
xml = ""
for prefix in prefixes:
xml += 'xmlns:' + prefix + '="' + namespaceURL[prefix] +'" '
return xml
class SlideInfo:
def __init__(
self,
titleText,
subtitleText,
blockType,
bullets,
tableRows,
cards,
code,
sequence,
):
self.titleText = titleText
self.subtitleText = subtitleText
self.blockType = blockType
self.bullets = bullets
self.tableRows = tableRows
self.cards = cards
self.code = code
self.sequence = sequence
# Information about a single table. (A slide might have more than one - or none.)
class TableInfo:
def __init__(self, tableRows, tableCaption):
self.tableRows = []
self.tableCaption = ""
# Information about a video
class AudioVideoInfo:
def __init__(self, elementString):
audioVideoElement = fromstring(elementString)
if "src" in audioVideoElement.attrib.keys():
self.source = audioVideoElement.attrib["src"]
else:
self.source = ""
if audioVideoElement.tag == "audio":
# audio element doesn't have width or height attributes so make it square
self.width = 1024
self.height = 1024
else:
# video element can have width and height attributes
# Default is 4:3
if "width" in audioVideoElement.attrib.keys():
self.width = int(audioVideoElement.attrib["width"])
else:
self.width = 1024
if "height" in audioVideoElement.attrib.keys():
self.height = int(audioVideoElement.attrib["height"])
else:
self.height = 768
self.aspectRatio = self.width / self.height
if "poster" in audioVideoElement.attrib.keys():
self.poster = audioVideoElement.attrib["poster"]
else:
self.poster = None
# Get a picture's rId
def get_picture_rId(picture):
rId = picture._element.xpath("./p:blipFill/a:blip/@r:embed")[0]
return rId
# Adds a picture as a background
def add_background(presentation, slide, picture):
# Add the picture with zero dimensions
picture = slide.shapes.add_picture(picture,0,0,0,00)
# Get the RId for this tiny picture = as we'll need that to set the background
rId = get_picture_rId(picture)
# find the cSld element to attach the XML to
cSld =slide._element.xpath("./p:cSld")[0]
# Remove any pre-existing bg element
bg =slide._element.xpath("./p:bg")
if bg != []:
cSld.remove(bg)
# Confect the XML
xml = ""
xml += ' <p:bg ' + namespacesFragment(["a","p","r"]) + '>\n'
xml += ' <p:bgPr>\n'
xml += ' <a:blipFill xmlns:a="' + namespaceURL["a"] + '" dpi="0" rotWithShape="1">\n'
xml += ' <a:blip r:embed="' + rId +'">\n'
xml += ' <a:lum />\n'
xml += ' </a:blip>\n'
xml += ' <a:srcRect />\n'
xml += ' <a:stretch>\n'
xml += ' <a:fillRect t="0" b="0" />\n'
xml += ' </a:stretch>\n'
xml += ' </a:blipFill>\n'
xml += ' <a:effectLst/>\n'
xml += ' </p:bgPr>\n'
xml += ' </p:bg>\n'
# Parse this XML
parsed_xml = parse_xml(xml)
# Insert the parsed XML fragment as a child of the cSld element
cSld.insert(0, parsed_xml)
# Delete the original picture
deleteSimpleShape(picture)
# Find the extLst element - if it exists in presentation.xml
def findExtLst(prs):
for child in prs._element.getchildren():
if child.tag.endswith("}extLst"):
return child
return None
def addSlide(presentation, slideLayout, slideInfo=None):
slide = presentation.slides.add_slide(slideLayout)
slide.slideInfo = slideInfo
backgroundImage = globals.processingOptions.getCurrentOption("backgroundImage")
if backgroundImage != "":
add_background(presentation, slide, backgroundImage)
return slide
def createSectionsXML(prs):
sectionSlideLayout = globals.processingOptions.getCurrentOption("SectionSlideLayout")
xml = ' <p:ext ' + namespacesFragment(["p"])
# ext URI has to be {521415D9-36F7-43E2-AB2F-B90AF26B5E84} as it's a registered extension
xml += ' uri="{521415D9-36F7-43E2-AB2F-B90AF26B5E84}">\n'
xml += ' <p14:sectionLst ' + namespacesFragment(["p14"]) + '>\n'
sectionCount = 0
for slide in prs.slides:
slideID = str(slide.slide_id)
for idx, slide_layout in enumerate(prs.slide_layouts):
if slide.slide_layout == slide_layout:
layoutNumber = idx
break
if layoutNumber == sectionSlideLayout:
# Have a section to contribute
sectionCount += 1
# Confect section name from first part of section slide title
title = findTitleShape(slide)
sectionName = title.text.split("\n")[0]
# Clean up section name
sectionName = "".join(
letter
for letter in sectionName
if (
(letter.isalnum())
| (letter in "&-+")
| (letter in "!/*")
| (letter == " ")
)
)
sectionName = (
sectionName.replace("& ", "& ")
.replace("\r", " ")
.replace("\n", " ")
)
# section URI's just need to be a GUID wrapped in braces
xml += (
' <p14:section name="'
+ sectionName
+ '" id="{'
+ str(uuid.uuid4()).upper()
+ '}">\n'
)
# Only the first slide in the section is added - as section will continue until the next section
# anyway
xml += " <p14:sldIdLst>\n"
xml += ' <p14:sldId id="' + slideID + '" />\n'
xml += " </p14:sldIdLst>\n"
xml += " </p14:section>\n"
# Close out the section list
xml += " </p14:sectionLst>\n"
# Close out the sections extension
xml += " </p:ext>\n"
parsed_xml = parse_xml(xml)
return parsed_xml, sectionCount
def createExpandingSections(prs):
# Use the slides' layouts to create an XML fragment with sections in
xmlFragment, sectionCount = createSectionsXML(prs)
if sectionCount > 0:
# Have sections to insert as an XML fragment
if (extLstElement := findExtLst(prs)) is not None:
# Need to remove the extension list element before adding a new one
prs._element.remove(extLstElement)
# Insert a new extension list element
extLst = OxmlElement("p:extLst")
prs._element.insert(-1, extLst)
# Insert the fragment in the extension list in presentation.xml
extLst.insert(0, xmlFragment)
def deleteSlide(prs, slideNumber):
rId = prs.slides._sldIdLst[slideNumber].rId
prs.part.drop_rel(rId)
del prs.slides._sldIdLst[slideNumber]
def startswithOneOf(haystack, needleList):
for needle in needleList:
if haystack.startswith(needle):
return True
return False
# Splits a string into words, converting each word to an integer. Returns them as a
# sorted list
def sortedNumericList(string):
return sorted(list(map(int, set(string.split()))))
def substituteFooterVariables(footerText, liveFooters):
# Decide if the footer should be a live link to the section slide
wantLiveFooter = (
(prs.lastSectionSlide is not None)
& (footerText.find("<section") > -1)
& (liveFooters == "yes")
)
# Substitute any section title occurrences
sectionTitleLines = resolveSymbols(prs.lastSectionTitle).split("<br/>")
footerText = footerText.replace("<section>", sectionTitleLines[0])
footerText = footerText.replace("<section1>", sectionTitleLines[0])
if len(sectionTitleLines) > 1:
footerText = footerText.replace("<section2>", sectionTitleLines[1])
if len(sectionTitleLines) > 2:
footerText = footerText.replace("<section3>", sectionTitleLines[2])
# Substitute any presentation title occurrences
presTitleLines = resolveSymbols(prs.lastPresTitle).split("<br/>")
footerText = footerText.replace("<presTitle>", presTitleLines[0])
footerText = footerText.replace("<presTitle1>", presTitleLines[0])
if len(presTitleLines) > 1:
footerText = footerText.replace("<presTitle2>", presTitleLines[1])
if len(presTitleLines) > 2:
footerText = footerText.replace("<presTitle3>", presTitleLines[2])
# Substitute any presentation subtitle occurrences
presSubtitleLines = resolveSymbols(prs.lastPresSubtitle).split("<br/>")
footerText = footerText.replace("<presSubtitle>", presSubtitleLines[0])
footerText = footerText.replace("<presSubtitle1>", presSubtitleLines[0])
if len(presSubtitleLines) > 1:
footerText = footerText.replace("<presSubtitle2>", presSubtitleLines[1])
if len(presSubtitleLines) > 2:
footerText = footerText.replace("<presSubtitle3>", presSubtitleLines[2])
# Make newlines happen
footerText = footerText.replace("<br/>", "\n")
return footerText, wantLiveFooter
def _applyCellBorderStyling(
tcPr, linePosition, lineWidthMultiplier=1, lineCount=1, lineColour="000000"
):
# How wide, relatively speaking to make the lines
lineWidth = int(12700 * lineWidthMultiplier)
# Whether the line should be single or double
if lineCount == 2:
lineCountValue = "dbl"
else:
lineCountValue = "sng"
if linePosition == "l":
elementName = "a:lnL"
elif linePosition == "r":
elementName = "a:lnR"
elif linePosition == "t":
elementName = "a:lnT"
else:
elementName = "a:lnB"
lnX = OxmlElement(elementName)
lnX.attrib.update(
{"w": str(lineWidth), "cap": "flat", "cmpd": lineCountValue, "algn": "ctr"}
)
solidFill = OxmlElement("a:solidFill")
srgbClr = OxmlElement("a:srgbClr")
srgbClr.attrib.update({"val": lineColour})
solidFill.append(srgbClr)
lnX.append(solidFill)
tcPr.append(lnX)
def applyCellBorderStyling(
cell, cellBorderStyling, lineWidthMultiplier, lineCount, lineColour
):
if cellBorderStyling == "":
# No cell border styling required
return
# Get any existing cell properties element - or make one
tc = cell._tc
tcPr = tc.get_or_add_tcPr()
# Draw any cell borders. More than one might apply
if cellBorderStyling.find("l") > -1:
_applyCellBorderStyling(tcPr, "l", lineWidthMultiplier, lineCount, lineColour)
if cellBorderStyling.find("r") > -1:
_applyCellBorderStyling(tcPr, "r", lineWidthMultiplier, lineCount, lineColour)
if cellBorderStyling.find("t") > -1:
_applyCellBorderStyling(tcPr, "t", lineWidthMultiplier, lineCount, lineColour)
if cellBorderStyling.find("b") > -1:
_applyCellBorderStyling(tcPr, "b", lineWidthMultiplier, lineCount, lineColour)
# Apply table line styling
def applyTableLineStyling(
table,
processingOptions,
):
wholeTableLineStyling = processingOptions.getCurrentOption("addTableLines")
linedColumns = processingOptions.getCurrentOption("addTableColumnLines")
linedRows = processingOptions.getCurrentOption("addTableRowLines")
lastRow = len(table.rows) - 1
# Create blank cell styling matrix
cellStyling = []
for rowNumber, row in enumerate(table.rows):
rowStyling = []
for cell in row.cells:
rowStyling.append("")
cellStyling.append(rowStyling)
# apply any "whole table" styling - from addTableLines
if wholeTableLineStyling == "box":
# Line around the table
for rowNumber, row in enumerate(table.rows):
# Figure out whether row is top, middle, or bottom
if rowNumber == 0:
rowStyling = "t"
elif rowNumber == lastRow:
rowStyling = "b"
else:
rowStyling = ""
lastColumn = len(row.cells) - 1
for columnNumber, cell in enumerate(row.cells):
if columnNumber == 0:
columnStyling = "l"
elif columnNumber == lastColumn:
columnStyling = "r"
else:
columnStyling = ""
cellStyling[rowNumber][columnNumber] = rowStyling + columnStyling
elif wholeTableLineStyling == "all":
# All edges of all cells have lines
for rowNumber, row in enumerate(table.rows):
lastColumn = len(row.cells) - 1
for columnNumber, cell in enumerate(row.cells):
cellStyling[rowNumber][columnNumber] = "tlbr"
# Apply any row styling - from addTableColumnLines
for rowNumber, row in enumerate(table.rows):
if rowNumber + 1 in linedRows:
# Line after this row so below
for columnNumber, cell in enumerate(row.cells):
cellStyling[rowNumber][columnNumber] = (
cellStyling[rowNumber][columnNumber] + "b"
)
elif rowNumber in linedRows:
# Line before this row so above
for columnNumber, cell in enumerate(row.cells):
cellStyling[rowNumber][columnNumber] = (
cellStyling[rowNumber][columnNumber] + "t"
)
# Apply any column styling - from addTableRowLines
for rowNumber, row in enumerate(table.rows):
for columnNumber, cell in enumerate(row.cells):
if columnNumber + 1 in linedColumns:
# Line after this column so to right
cellStyling[rowNumber][columnNumber] = (
cellStyling[rowNumber][columnNumber] + "r"
)
elif columnNumber + 1 in linedColumns:
# Line after this column so to left
cellStyling[rowNumber][columnNumber] = (
cellStyling[rowNumber][columnNumber] + "r"
)
# Apply the styling from the matrix to all cells
for rowNumber, row in enumerate(table.rows):
for columnNumber, cell in enumerate(row.cells):
applyCellBorderStyling(
cell,
cellStyling[rowNumber][columnNumber],
globals.processingOptions.getCurrentOption("addTableLineWidth"),
globals.processingOptions.getCurrentOption("addTableLineCount"),
globals.processingOptions.getCurrentOption("addTableLineColour"),
)
def reportSlideTitle(slideNumber, indent, titleText):
print(str(slideNumber).rjust(4) + " " + (" " * indent) + titleText)
def reportGraphicFilenames(leftFilename, rightFilename=""):
if rightFilename == "":
print(" ---> " + leftFilename.ljust(30))
else:
print(" ---> " + leftFilename.ljust(30) + " , " + rightFilename)
# Given current indenting regime calculate what level the bullet / number is at
def calculateIndentationLevel(firstNonSpace, indentSpaces):
return int(firstNonSpace / indentSpaces)
# Calculate picture dimensions given its natural height and bounds
def scalePicture(maxPicWidth, maxPicHeight, imageWidth, imageHeight):
heightIfWidthUsed = maxPicWidth * imageHeight / imageWidth
widthIfHeightUsed = maxPicHeight * imageWidth / imageHeight
if heightIfWidthUsed > maxPicHeight:
# Use the height to scale
usingHeightToScale = True
picWidth = widthIfHeightUsed
picHeight = maxPicHeight
else:
# Use the width to scale
usingHeightToScale = False
picWidth = maxPicWidth
picHeight = heightIfWidthUsed
return (picWidth, picHeight, usingHeightToScale)
def parseMedia(cellString, graphicCount):
graphicTitle = ""
HTML = ""
audioVideoInfo = None
graphicHref = ""
GraphicFilename = ""
printableGraphicFilename = ""
graphicCount += 1
if videoRegexMatch := videoRegex.match(cellString):
# Cell contains a video
audioVideoInfo = AudioVideoInfo(cellString)
_, printableGraphicFilename = handleWhateverGraphicType(audioVideoInfo.source)
elif audioRegexMatch := audioRegex.match(cellString):
# Cell contains an audio
audioVideoInfo = AudioVideoInfo(cellString)
_, printableGraphicFilename = handleWhateverGraphicType(audioVideoInfo.source)
elif clickableGraphicMatch := clickableGraphicRegex.match(cellString):
# Cell contains a clickable graphic
graphicTitle = clickableGraphicMatch.group(1)
GraphicFilename = clickableGraphicMatch.group(2)
graphicHref = clickableGraphicMatch.group(3)
(
GraphicFilename,
printableGraphicFilename,
) = handleWhateverGraphicType(GraphicFilename)
elif graphicMatch := graphicRegex.match(cellString):
# Cell contains a non-clickable graphic
graphicTitle = graphicMatch.group(1)
GraphicFilename = graphicMatch.group(2)
(
GraphicFilename,
printableGraphicFilename,
) = handleWhateverGraphicType(GraphicFilename)
else:
# Not a graphic or video
GraphicFilename = ""
printableGraphicFilename = ""
HTML = cellString
graphicCount -= 1
return (
graphicTitle,
GraphicFilename,
printableGraphicFilename,
graphicHref,
HTML,
audioVideoInfo,
graphicCount,
)
# Send a shape to the back on a slide
def sendToBack(shapes, shape):
firstShapeElement = shapes[0]._element
firstShapeElement.addprevious(shape._element)
# Turn a paragraph into a numbered inList item
def makeNumberedListItem(p):
if (
p._element.getchildren()[0].tag
== "{http://schemas.openxmlformats.org/drawingml/2006/main}pPr"
):
pPr = p._element.getchildren()[0]
if len(pPr.getchildren()) > 0:
# Remove Default Text Run Properties element - if present
x = pPr.getchildren()[0]
if x.tag == "{http://schemas.openxmlformats.org/drawingml/2006/main}defRPr":
pPr.remove(x)
else:
pPr = OxmlElement("a:pPr")
p._element.insert(0, pPr)
buFont = OxmlElement("a:buFont")
buFont.set("typeface", "+mj-lt")
pPr.append(buFont)
buAutoNum = OxmlElement("a:buAutoNum")
buAutoNum.set("type", "arabicPeriod")
pPr.append(buAutoNum)
# Add a drop shadow to a shape
def createShadow(shape):
spPr = shape.fill._xPr
el = OxmlElement("a:effectLst")
spPr.append(el)
outerShdw = OxmlElement("a:outerShdw")
outerShdw.set("algn", "tl")
outerShdw.set("blurRad", "50800")
outerShdw.set("dir", "2700000")
outerShdw.set("dist", "95250")
outerShdw.set("rotWithShape", "0")
el.append(outerShdw)
prstClr = OxmlElement("a:prstClr")
prstClr.set("val", "black")
outerShdw.append(prstClr)
alpha = OxmlElement("a:alpha")
alpha.set("val", "40000")
prstClr.append(alpha)
# Clone a shape in a slide and return the new shape.
# (This is a deep copy so the new shape will have the same
# eg bullet style as the source shape)
def addClonedShape(slide, shape1):
# Clone the element for the shape
el1 = shape1.element
el2 = copy.deepcopy(el1)
# Insert the cloned element into the shape tree
slide.shapes._spTree.insert_element_before(el2, "p:extLst")
# Return the shape associated with this new element
return slide.shapes[-1]
# Following functions are workarounds for python-pptx not having these functions for the font object
def set_subscript(font):
if font.size is None:
font._element.set("baseline", "-50000")
return
if font.size < Pt(24):
font._element.set("baseline", "-50000")
else:
font._element.set("baseline", "-25000")
def set_superscript(font):
if font.size is None:
font._element.set("baseline", "60000")
return
if font.size < Pt(24):
font._element.set("baseline", "60000")
else:
font._element.set("baseline", "30000")
def setStrikethrough(font):
font._element.set("strike", "sngStrike")
def setHighlight(run, color):
# get run properties
rPr = run._r.get_or_add_rPr()
# Create highlight element
hl = OxmlElement("a:highlight")
# Create specify RGB Colour element with color specified
srgbClr = OxmlElement("a:srgbClr")
setattr(srgbClr, "val", color)
# Add colour specification to highlight element
hl.append(srgbClr)
# Add highlight element to run properties
rPr.append(hl)
return run
# Get the slide object the run is in
def SlideFromRun(run):
return run._parent._parent._parent._parent._parent
# Get the slide object the picture is in
def SlideFromPicture(picture):
return picture._parent._parent
# Creates a hyperlink to another slide and/or a tooltip - for a
# text run
# Note: To get just a tooltip make to_slide be the source slide
# so it links to itself.
def createRunHyperlinkOrTooltip(run, to_slide, tooltipText=""):
# Get hold of the shape the run is in
if run._parent._parent._parent.__class__.__name__ == "_Cell":
# Run in a table cell has to be handled differently
shape = (
run._parent._parent._parent._parent._parent._parent._parent._graphic_frame
)
else:
# Ordinary text run
shape = run._parent._parent._parent
if to_slide == None:
to_slide = SlideFromRun(run)
hl = run.hyperlink
sca = shape.click_action
sca_hl = sca.hyperlink
# Add a click action to generate an internal hyperlink address
sca.target_slide = to_slide
# Use that internal hyperlink address for the run
hl.address = sca_hl.address
# Also clone the hyperlink click action
hl._hlinkClick.action = sca_hl._hlink.action
if tooltipText != "":
hl._hlinkClick.set("tooltip", tooltipText)
# Also clone the hyperlink rId
hl._hlinkClick.rId = sca_hl._hlink.rId
# Delete the shape click action
sca.target_slide = None
# Creates a hyperlink to another slide or a URL and/or a tooltip - for a
# picture
# Note: To get just a tooltip make to_slide be the source slide
# so it links to itself.
def createPictureHyperlinkOrTooltip(picture, target, tooltipText=""):
if target == None:
# If neither a tooltip nor a target slide then return having
# done nothing
if tooltipText == "":
return
# Tooltip but no target slide
target = SlideFromPicture(picture)
picture.click_action.target_slide = target
elif target.__class__.__name__ == "str":
# Is a URL
picture.click_action.hyperlink.address = target
# URL might be a macro reference
if target[:11] == "ppaction://":
# URL is indeed a macro reference, so treat it as such
picture.click_action.hyperlink._hlink.set("action", target)
else:
# Target is a slide
picture.click_action.target_slide = target
if tooltipText != "":
picture.click_action.hyperlink._hlink.set("tooltip", tooltipText)
# If a tooltip has been set return it else return an empty string
def getPictureTooltip(picture):
if picture.click_action.hyperlink._hlink != None:
# There is a tooltip
return picture.click_action.hyperlink._hlink.get("tooltip")
else:
# There is no tooltip
return ""
# Create hyperlink and optional tooltip from a shape eg Chevron
def createShapeHyperlinkAndTooltip(shape, to_slide, tooltipText=""):
shape.click_action.target_slide = to_slide
hl = shape.click_action.hyperlink
hl._hlink.set("tooltip", tooltipText)
def getGraphicDimensions(fname):
"""Determine the image type of fhandle and return its size.
from draco"""
try:
with open(fname, "rb") as fhandle:
head = fhandle.read(24)
if len(head) != 24:
return -1, -1
fname2 = fname.lower()
if fname2.endswith(".png"):
check = struct.unpack(">i", head[4:8])[0]
if check != 0x0D0A1A0A:
return -1, -1
width, height = struct.unpack(">ii", head[16:24])
elif fname2.endswith(".gif"):
width, height = struct.unpack("<HH", head[6:10])
elif fname.endswith((".jpeg", ".jpg")):
try:
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xC0 <= ftype <= 0xCF:
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xFF:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack(">H", fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip 'precision' byte.
height, width = struct.unpack(">HH", fhandle.read(4))
except Exception: # IGNORE:W0703
return
else:
return -1, -1
return width, height
except EnvironmentError:
return -1, -1
def getVideoInfo(audioVideoInfo):
if audioVideoInfo.source.find("://") > -1:
# Video would be sourced from the web
try:
operUrl = urllib.request.urlopen(audioVideoInfo.source)
except urllib.error.HTTPError as e:
return -1, -1, "Web", None
except socket.error as s:
return -1, -1, "Web", None
data = operUrl.read()
return audioVideoInfo.width, audioVideoInfo.height, "Web", data
else:
# Video would be sourced from a local file
try:
fhandle = open(audioVideoInfo.source, "rb")
except EnvironmentError:
return -1, -1, "Local", None
return audioVideoInfo.width, audioVideoInfo.height, "Local", None
# Render a list of bullets
def renderText(shape, bullets):
baseTextDecrement = globals.processingOptions.getCurrentOption("baseTextDecrement")
baseTextSize = globals.processingOptions.getCurrentOption("baseTextSize")
tf = shape.text_frame
for bulletNumber, bullet in enumerate(bullets):
para0 = tf.paragraphs[0]
if bulletNumber == 0:
# Don't need to create paragraph
p = para0
else:
# We need a new paragraph
p = tf.add_paragraph()
# Set the paragraph's level - zero-indexed
p.level = int(bullet[0])
# Set the paragraph's font size, adjusted for level, if necessary
if baseTextSize > 0:
p.font.size = Pt(baseTextSize - p.level * baseTextDecrement)
addFormattedText(p, bullet[1])
if bullet[2] == "numbered":
makeNumberedListItem(p)
tf.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE
def findTitleShape(slide):
if slide.shapes.title == None:
# Have to use first shape as title
return slide.shapes[0]
else:
return slide.shapes.title
def findBodyShape(slide):
if len(slide.shapes) > 1:
return slide.shapes[1]
elif slide.shapes.title == None:
return slide.shapes[0]
else:
return None
# Returns a top, left, width, height for content to be rendered into
def getContentRect(presentation, slide, topOfContent, margin):
numbersHeight = globals.processingOptions.getCurrentOption("numbersHeight")
# Left and right are always defined by the margins
rectLeft = margin
rectWidth = presentation.slide_width - 2 * margin
if topOfContent == 0:
# There is no title on this slide
rectTop = margin
rectHeight = presentation.slide_height - margin - max(margin, numbersHeight)
else:
# There is a title on this slide
rectTop = topOfContent + margin
rectHeight = presentation.slide_height - rectTop - max(margin, numbersHeight)
return (rectLeft, rectWidth, rectTop, rectHeight)
# Finds the title and adds the text to it, returning title bottom, title shape, and
# flattened title