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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
|
#!/usr/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
"""
This is PythonPoint!
The idea is a simple markup languages for describing presentation
slides, and other documents which run page by page. I expect most
of it will be reusable in other page layout stuff.
Look at the sample near the top, which shows how the presentation
should be coded up.
The parser, which is in a separate module to allow for multiple
parsers, turns the XML sample into an object tree. There is a
simple class hierarchy of items, the inner levels of which create
flowable objects to go in the frames. These know how to draw
themselves.
The currently available 'Presentation Objects' are:
The main hierarchy...
PPPresentation
PPSection
PPSlide
PPFrame
PPAuthor, PPTitle and PPSubject are optional
Things to flow within frames...
PPPara - flowing text
PPPreformatted - text with line breaks and tabs, for code..
PPImage
PPTable - bulk formatted tabular data
PPSpacer
Things to draw directly on the page...
PPRect
PPRoundRect
PPDrawingElement - user base class for graphics
PPLine
PPEllipse
Features added by H. Turgut Uyar <uyar@cs.itu.edu.tr>
- TrueType support (actually, just an import in the style file);
this also enables the use of Unicode symbols
- para, image, table, line, rectangle, roundrect, ellipse, polygon
and string elements can now have effect attributes
(careful: new slide for each effect!)
- added printout mode (no new slides for effects, see item above)
- added a second-level bullet: Bullet2
- small bugfixes in handleHiddenSlides:
corrected the outlineEntry of included hidden slide
and made sure to include the last slide even if hidden
Recently added features are:
- file globbing
- package structure
- named colors throughout (using names from reportlab/lib/colors.py)
- handout mode with arbitrary number of columns per page
- stripped off pages hidden in the outline tree (hackish)
- new <notes> tag for speaker notes (paragraphs only)
- new <pycode> tag for syntax-colorized Python code
- reformatted pythonpoint.xml and monterey.xml demos
- written/extended DTD
- arbitrary font support
- print proper speaker notes (TODO)
- fix bug with partially hidden graphics (TODO)
- save in combined presentation/handout mode (TODO)
- add pyRXP support (TODO)
"""
__version__='3.3.0'
import os, sys, getopt, glob, re
from io import BytesIO
from reportlab import rl_config
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.lib.utils import isStr, isBytes, isUnicode
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfgen import canvas
from reportlab.platypus.doctemplate import SimpleDocTemplate
from reportlab.platypus.flowables import Flowable
from reportlab.platypus.xpreformatted import PythonPreformatted
from reportlab.platypus import Preformatted, Paragraph, Frame, \
Image, Table, TableStyle, Spacer
USAGE_MESSAGE = """\
PythonPoint - a tool for making presentations in PDF.
Usage:
pythonpoint.py [options] file1.xml [file2.xml [...]]
where options can be any of these:
-h / --help prints this message
-n / --notes leave room for comments
-v / --verbose verbose mode
-s / --silent silent mode (NO output)
--handout produce handout document
--printout produce printout document
--cols specify number of columns
on handout pages (default: 2)
To create the PythonPoint user guide, do:
pythonpoint.py pythonpoint.xml
"""
#####################################################################
# This should probably go into reportlab/lib/fonts.py...
#####################################################################
class FontNameNotFoundError(Exception):
pass
class FontFilesNotFoundError(Exception):
pass
##def findFontName(path):
## "Extract a Type-1 font name from an AFM file."
##
## f = open(path)
##
## found = 0
## while not found:
## line = f.readline()[:-1]
## if not found and line[:16] == 'StartCharMetrics':
## raise FontNameNotFoundError, path
## if line[:8] == 'FontName':
## fontName = line[9:]
## found = 1
##
## return fontName
##
##
##def locateFilesForFontWithName(name):
## "Search known paths for AFM/PFB files describing T1 font with given name."
##
## join = os.path.join
## splitext = os.path.splitext
##
## afmFile = None
## pfbFile = None
##
## found = 0
## while not found:
## for p in rl_config.T1SearchPath:
## afmFiles = glob.glob(join(p, '*.[aA][fF][mM]'))
## for f in afmFiles:
## T1name = findFontName(f)
## if T1name == name:
## afmFile = f
## found = 1
## break
## if afmFile:
## break
## break
##
## if afmFile:
## pfbFile = glob.glob(join(splitext(afmFile)[0] + '.[pP][fF][bB]'))[0]
##
## return afmFile, pfbFile
##
##
##def registerFont(name):
## "Register Type-1 font for future use."
##
## rl_config.warnOnMissingFontGlyphs = 0
## rl_config.T1SearchPath.append(r'C:\Programme\Python21\reportlab\test')
##
## afmFile, pfbFile = locateFilesForFontWithName(name)
## if not afmFile and not pfbFile:
## raise FontFilesNotFoundError
##
## T1face = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
## T1faceName = name
## pdfmetrics.registerTypeFace(T1face)
## T1font = pdfmetrics.Font(name, T1faceName, 'WinAnsiEncoding')
## pdfmetrics.registerFont(T1font)
def registerFont0(sourceFile, name, path):
"Register Type-1 font for future use, simple version."
rl_config.warnOnMissingFontGlyphs = 0
p = os.path.join(os.path.dirname(sourceFile), path)
afmFiles = glob.glob(p + '.[aA][fF][mM]')
pfbFiles = glob.glob(p + '.[pP][fF][bB]')
assert len(afmFiles) == len(pfbFiles) == 1, FontFilesNotFoundError
T1face = pdfmetrics.EmbeddedType1Face(afmFiles[0], pfbFiles[0])
T1faceName = name
pdfmetrics.registerTypeFace(T1face)
T1font = pdfmetrics.Font(name, T1faceName, 'WinAnsiEncoding')
pdfmetrics.registerFont(T1font)
#####################################################################
def checkColor(col):
"Converts a color name to an RGB tuple, if possible."
if isStr(col):
if col in dir(colors):
col = getattr(colors, col)
col = (col.red, col.green, col.blue)
return col
def handleHiddenSlides(slides):
"""Filters slides from a list of slides.
In a sequence of hidden slides all but the last one are
removed. Also, the slide before the sequence of hidden
ones is removed.
This assumes to leave only those slides in the handout
that also appear in the outline, hoping to reduce se-
quences where each new slide only adds one new line
to a list of items...
"""
itd = indicesToDelete = [s.outlineEntry == None for s in slides]
for i in range(len(itd)-1):
if itd[i] == 1:
if itd[i+1] == 0:
itd[i] = 0
if i > 0 and itd[i-1] == 0:
itd[i-1] = 1
itd[len(itd)-1] = 0
for i in range(len(itd)):
if slides[i].outlineEntry:
curOutlineEntry = slides[i].outlineEntry
if itd[i] == 1:
slides[i].delete = 1
else:
slides[i].outlineEntry = curOutlineEntry
slides[i].delete = 0
slides = [s for s in slides if s.delete == 0]
return slides
def makeSlideTable(slides, pageSize, docWidth, numCols):
"""Returns a table containing a collection of SlideWrapper flowables.
"""
slides = handleHiddenSlides(slides)
# Set table style.
tabStyle = TableStyle(
[('GRID', (0,0), (-1,-1), 0.25, colors.black),
('ALIGN', (0,0), (-1,-1), 'CENTRE')
])
# Build table content.
width = docWidth/numCols
height = width * pageSize[1]/pageSize[0]
matrix = []
row = []
for slide in slides:
sw = SlideWrapper(width, height, slide, pageSize)
if (len(row)) < numCols:
row.append(sw)
else:
matrix.append(row)
row = []
row.append(sw)
if len(row) > 0:
for i in range(numCols-len(row)):
row.append('')
matrix.append(row)
# Make Table flowable.
t = Table(matrix,
[width + 5]*len(matrix[0]),
[height + 5]*len(matrix))
t.setStyle(tabStyle)
return t
class SlideWrapper(Flowable):
"""A Flowable wrapping a PPSlide object.
"""
def __init__(self, width, height, slide, pageSize):
Flowable.__init__(self)
self.width = width
self.height = height
self.slide = slide
self.pageSize = pageSize
def __repr__(self):
return "SlideWrapper(w=%s, h=%s)" % (self.width, self.height)
def draw(self):
"Draw the slide in our relative coordinate system."
slide = self.slide
pageSize = self.pageSize
canv = self.canv
canv.saveState()
canv.scale(self.width/pageSize[0], self.height/pageSize[1])
slide.effectName = None
slide.drawOn(self.canv)
canv.restoreState()
class PPPresentation:
def __init__(self):
self.sourceFilename = None
self.filename = None
self.outDir = None
self.description = None
self.title = None
self.author = None
self.subject = None
self.notes = 0 # different printing mode
self.handout = 0 # prints many slides per page
self.printout = 0 # remove hidden slides
self.cols = 0 # columns per handout page
self.slides = []
self.effectName = None
self.showOutline = 1 #should it be displayed when opening?
self.compression = rl_config.pageCompression
self.pageDuration = None
#assume landscape
self.pageWidth = rl_config.defaultPageSize[1]
self.pageHeight = rl_config.defaultPageSize[0]
self.verbose = rl_config.verbose
def saveAsPresentation(self):
"""Write the PDF document, one slide per page."""
if self.verbose:
print('saving presentation...')
pageSize = (self.pageWidth, self.pageHeight)
if self.sourceFilename:
filename = os.path.splitext(self.sourceFilename)[0] + '.pdf'
if self.outDir: filename = os.path.join(self.outDir,os.path.basename(filename))
if self.verbose:
print(filename)
#canv = canvas.Canvas(filename, pagesize = pageSize)
outfile = BytesIO()
if self.notes:
#translate the page from landscape to portrait
pageSize= pageSize[1], pageSize[0]
canv = canvas.Canvas(outfile, pagesize = pageSize)
canv.setPageCompression(self.compression)
canv.setPageDuration(self.pageDuration)
if self.title:
canv.setTitle(self.title)
if self.author:
canv.setAuthor(self.author)
if self.subject:
canv.setSubject(self.subject)
slideNo = 0
for slide in self.slides:
#need diagnostic output if something wrong with XML
slideNo = slideNo + 1
if self.verbose:
print('doing slide %d, id = %s' % (slideNo, slide.id))
if self.notes:
#frame and shift the slide
#canv.scale(0.67, 0.67)
scale_amt = (min(pageSize)/float(max(pageSize)))*.95
#canv.translate(self.pageWidth / 6.0, self.pageHeight / 3.0)
#canv.translate(self.pageWidth / 2.0, .025*self.pageHeight)
canv.translate(.025*self.pageHeight, (self.pageWidth/2.0) + 5)
#canv.rotate(90)
canv.scale(scale_amt, scale_amt)
canv.rect(0,0,self.pageWidth, self.pageHeight)
slide.drawOn(canv)
canv.showPage()
#ensure outline visible by default
if self.showOutline:
canv.showOutline()
canv.save()
return self.savetofile(outfile, filename)
def saveAsHandout(self):
"""Write the PDF document, multiple slides per page."""
styleSheet = getSampleStyleSheet()
h1 = styleSheet['Heading1']
bt = styleSheet['BodyText']
if self.sourceFilename :
filename = os.path.splitext(self.sourceFilename)[0] + '.pdf'
outfile = BytesIO()
doc = SimpleDocTemplate(outfile, pagesize=rl_config.defaultPageSize, showBoundary=0)
doc.leftMargin = 1*cm
doc.rightMargin = 1*cm
doc.topMargin = 2*cm
doc.bottomMargin = 2*cm
multiPageWidth = rl_config.defaultPageSize[0] - doc.leftMargin - doc.rightMargin - 50
story = []
orgFullPageSize = (self.pageWidth, self.pageHeight)
t = makeSlideTable(self.slides, orgFullPageSize, multiPageWidth, self.cols)
story.append(t)
## #ensure outline visible by default
## if self.showOutline:
## doc.canv.showOutline()
doc.build(story)
return self.savetofile(outfile, filename)
def savetofile(self, pseudofile, filename):
"""Save the pseudo file to disk and return its content as a
string of text."""
pseudofile.flush()
content = pseudofile.getvalue()
pseudofile.close()
if filename :
outf = open(filename, "wb")
outf.write(content)
outf.close()
return content
def save(self):
"Save the PDF document."
if self.handout:
return self.saveAsHandout()
else:
return self.saveAsPresentation()
#class PPSection:
# """A section can hold graphics which will be drawn on all
# pages within it, before frames and other content are done.
# In other words, a background template."""
# def __init__(self, name):
# self.name = name
# self.graphics = []
#
# def drawOn(self, canv):
# for graphic in self.graphics:
### graphic.drawOn(canv)
#
# name = str(hash(graphic))
# internalname = canv._doc.hasForm(name)
#
# canv.saveState()
# if not internalname:
# canv.beginForm(name)
# graphic.drawOn(canv)
# canv.endForm()
# canv.doForm(name)
# else:
# canv.doForm(name)
# canv.restoreState()
definedForms = {}
class PPSection:
"""A section can hold graphics which will be drawn on all
pages within it, before frames and other content are done.
In other words, a background template."""
def __init__(self, name):
self.name = name
self.graphics = []
def drawOn(self, canv):
for graphic in self.graphics:
graphic.drawOn(canv)
continue
name = str(hash(graphic))
#internalname = canv._doc.hasForm(name)
if name in definedForms:
internalname = 1
else:
internalname = None
definedForms[name] = 1
if not internalname:
canv.beginForm(name)
canv.saveState()
graphic.drawOn(canv)
canv.restoreState()
canv.endForm()
canv.doForm(name)
else:
canv.doForm(name)
class PPNotes:
def __init__(self):
self.content = []
def drawOn(self, canv):
print(self.content)
class PPSlide:
def __init__(self):
self.id = None
self.title = None
self.outlineEntry = None
self.outlineLevel = 0 # can be higher for sub-headings
self.effectName = None
self.effectDirection = 0
self.effectDimension = 'H'
self.effectMotion = 'I'
self.effectDuration = 1
self.frames = []
self.notes = []
self.graphics = []
self.section = None
def drawOn(self, canv):
if self.effectName:
canv.setPageTransition(
effectname=self.effectName,
direction = self.effectDirection,
dimension = self.effectDimension,
motion = self.effectMotion,
duration = self.effectDuration
)
if self.outlineEntry:
#gets an outline automatically
self.showOutline = 1
#put an outline entry in the left pane
tag = self.title
canv.bookmarkPage(tag)
canv.addOutlineEntry(tag, tag, self.outlineLevel)
if self.section:
self.section.drawOn(canv)
for graphic in self.graphics:
graphic.drawOn(canv)
for frame in self.frames:
frame.drawOn(canv)
## # Need to draw the notes *somewhere*...
## for note in self.notes:
## print note
class PPFrame:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.content = []
self.showBoundary = 0
def drawOn(self, canv):
#make a frame
frame = Frame( self.x,
self.y,
self.width,
self.height
)
frame.showBoundary = self.showBoundary
#build a story for the frame
story = []
for thingy in self.content:
#ask it for any flowables
story.append(thingy.getFlowable())
#draw it
frame.addFromList(story,canv)
class PPPara:
"""This is a placeholder for a paragraph."""
def __init__(self):
self.rawtext = ''
self.style = None
def escapeAgain(self, text):
"""The XML has been parsed once, so '>' became '>'
in rawtext. We need to escape this to get back to
something the Platypus parser can accept"""
pass
def getFlowable(self):
p = Paragraph(
self.rawtext,
getStyles()[self.style],
self.bulletText
)
return p
class PPPreformattedText:
"""Use this for source code, or stuff you do not want to wrap"""
def __init__(self):
self.rawtext = ''
self.style = None
def getFlowable(self):
return Preformatted(self.rawtext, getStyles()[self.style])
class PPPythonCode:
"""Use this for colored Python source code"""
def __init__(self):
self.rawtext = ''
self.style = None
def getFlowable(self):
return PythonPreformatted(self.rawtext, getStyles()[self.style])
class PPImage:
"""Flowing image within the text"""
def __init__(self):
self.filename = None
self.width = None
self.height = None
def getFlowable(self):
return Image(self.filename, self.width, self.height)
class PPTable:
"""Designed for bulk loading of data for use in presentations."""
def __init__(self):
self.rawBlocks = [] #parser stuffs things in here...
self.fieldDelim = ',' #tag args can override
self.rowDelim = '\n' #tag args can override
self.data = None
self.style = None #tag args must specify
self.widths = None #tag args can override
self.heights = None #tag args can override
def getFlowable(self):
self.parseData()
t = Table(
self.data,
self.widths,
self.heights)
if self.style:
t.setStyle(getStyles()[self.style])
return t
def parseData(self):
"""Try to make sense of the table data!"""
rawdata = ''.join(self.rawBlocks).strip()
lines = rawdata.split(self.rowDelim)
#clean up...
lines = [line.strip() for line in lines]
self.data = []
for line in lines:
cells = line.split(self.fieldDelim)
self.data.append(cells)
#get the width list if not given
if not self.widths:
self.widths = [None] * len(self.data[0])
if not self.heights:
self.heights = [None] * len(self.data)
## import pprint
## print 'table data:'
## print 'style=',self.style
## print 'widths=',self.widths
## print 'heights=',self.heights
## print 'fieldDelim=',repr(self.fieldDelim)
## print 'rowDelim=',repr(self.rowDelim)
## pprint.pprint(self.data)
class PPSpacer:
def __init__(self):
self.height = 24 #points
def getFlowable(self):
return Spacer(72, self.height)
#############################################################
#
# The following are things you can draw on a page directly.
#
##############################################################
##class PPDrawingElement:
## """Base class for something which you draw directly on the page."""
## def drawOn(self, canv):
## raise NotImplementedError("Abstract base class!")
class PPFixedImage:
"""You place this on the page, rather than flowing it"""
def __init__(self):
self.filename = None
self.x = 0
self.y = 0
self.width = None
self.height = None
def drawOn(self, canv):
if self.filename:
x, y = self.x, self.y
w, h = self.width, self.height
canv.drawImage(self.filename, x, y, w, h)
class PPRectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.fillColor = None
self.strokeColor = (1,1,1)
self.lineWidth=0
def drawOn(self, canv):
canv.saveState()
canv.setLineWidth(self.lineWidth)
if self.fillColor:
r,g,b = checkColor(self.fillColor)
canv.setFillColorRGB(r,g,b)
if self.strokeColor:
r,g,b = checkColor(self.strokeColor)
canv.setStrokeColorRGB(r,g,b)
canv.rect(self.x, self.y, self.width, self.height,
stroke=(self.strokeColor!=None),
fill = (self.fillColor!=None)
)
canv.restoreState()
class PPRoundRect:
def __init__(self, x, y, width, height, radius):
self.x = x
self.y = y
self.width = width
self.height = height
self.radius = radius
self.fillColor = None
self.strokeColor = (1,1,1)
self.lineWidth=0
def drawOn(self, canv):
canv.saveState()
canv.setLineWidth(self.lineWidth)
if self.fillColor:
r,g,b = checkColor(self.fillColor)
canv.setFillColorRGB(r,g,b)
if self.strokeColor:
r,g,b = checkColor(self.strokeColor)
canv.setStrokeColorRGB(r,g,b)
canv.roundRect(self.x, self.y, self.width, self.height,
self.radius,
stroke=(self.strokeColor!=None),
fill = (self.fillColor!=None)
)
canv.restoreState()
class PPLine:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.fillColor = None
self.strokeColor = (1,1,1)
self.lineWidth=0
def drawOn(self, canv):
canv.saveState()
canv.setLineWidth(self.lineWidth)
if self.strokeColor:
r,g,b = checkColor(self.strokeColor)
canv.setStrokeColorRGB(r,g,b)
canv.line(self.x1, self.y1, self.x2, self.y2)
canv.restoreState()
class PPEllipse:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.fillColor = None
self.strokeColor = (1,1,1)
self.lineWidth=0
def drawOn(self, canv):
canv.saveState()
canv.setLineWidth(self.lineWidth)
if self.strokeColor:
r,g,b = checkColor(self.strokeColor)
canv.setStrokeColorRGB(r,g,b)
if self.fillColor:
r,g,b = checkColor(self.fillColor)
canv.setFillColorRGB(r,g,b)
canv.ellipse(self.x1, self.y1, self.x2, self.y2,
stroke=(self.strokeColor!=None),
fill = (self.fillColor!=None)
)
canv.restoreState()
class PPPolygon:
def __init__(self, pointlist):
self.points = pointlist
self.fillColor = None
self.strokeColor = (1,1,1)
self.lineWidth=0
def drawOn(self, canv):
canv.saveState()
canv.setLineWidth(self.lineWidth)
if self.strokeColor:
r,g,b = checkColor(self.strokeColor)
canv.setStrokeColorRGB(r,g,b)
if self.fillColor:
r,g,b = checkColor(self.fillColor)
canv.setFillColorRGB(r,g,b)
path = canv.beginPath()
(x,y) = self.points[0]
path.moveTo(x,y)
for (x,y) in self.points[1:]:
path.lineTo(x,y)
path.close()
canv.drawPath(path,
stroke=(self.strokeColor!=None),
fill=(self.fillColor!=None))
canv.restoreState()
class PPString:
def __init__(self, x, y):
self.text = ''
self.x = x
self.y = y
self.align = TA_LEFT
self.font = 'Times-Roman'
self.size = 12
self.color = (0,0,0)
self.hasInfo = 0 # these can have data substituted into them
def normalizeText(self):
"""It contains literal XML text typed over several lines.
We want to throw away
tabs, newlines and so on, and only accept embedded string
like '\n'"""
lines = self.text.split('\n')
newtext = []
for line in lines:
newtext.append(line.strip())
#accept all the '\n' as newlines
self.text = newtext
def drawOn(self, canv):
# for a string in a section, this will be drawn several times;
# so any substitution into the text should be in a temporary
# variable
if self.hasInfo:
# provide a dictionary of stuff which might go into
# the string, so they can number pages, do headers
# etc.
info = {}
info['title'] = canv._doc.info.title
info['author'] = canv._doc.info.author
info['subject'] = canv._doc.info.subject
info['page'] = canv.getPageNumber()
drawText = self.text % info
else:
drawText = self.text
if self.color is None:
return
lines = drawText.strip().split('\\n')
canv.saveState()
canv.setFont(self.font, self.size)
r,g,b = checkColor(self.color)
canv.setFillColorRGB(r,g,b)
cur_y = self.y
for line in lines:
if self.align == TA_LEFT:
canv.drawString(self.x, cur_y, line)
elif self.align == TA_CENTER:
canv.drawCentredString(self.x, cur_y, line)
elif self.align == TA_RIGHT:
canv.drawRightString(self.x, cur_y, line)
cur_y = cur_y - 1.2*self.size
canv.restoreState()
class PPDrawing:
def __init__(self):
self.drawing = None
def getFlowable(self):
return self.drawing
class PPFigure:
def __init__(self):
self.figure = None
def getFlowable(self):
return self.figure
def getSampleStyleSheet():
from tools.pythonpoint.styles.standard import getParagraphStyles
return getParagraphStyles()
def toolsDir():
import tools
return tools.__path__[0]
#make a singleton and a function to access it
_styles = None
def getStyles():
global _styles
if not _styles:
_styles = getSampleStyleSheet()
return _styles
def setStyles(newStyleSheet):
global _styles
_styles = newStyleSheet
_pyRXP_Parser = None
def validate(rawdata):
global _pyRXP_Parser
if not _pyRXP_Parser:
try:
import pyRXP
except ImportError:
return
from reportlab.lib.utils import open_and_read, rl_isfile
dtd = 'pythonpoint.dtd'
if not rl_isfile(dtd):
dtd = os.path.join(toolsDir(),'pythonpoint','pythonpoint.dtd')
if not rl_isfile(dtd): return
def eocb(URI,dtdText=open_and_read(dtd),dtd=dtd):
if os.path.basename(URI)=='pythonpoint.dtd': return dtd,dtdText
return URI
_pyRXP_Parser = pyRXP.Parser(eoCB=eocb)
return _pyRXP_Parser.parse(rawdata)
def _re_match(pat,text,flags=re.M|re.I):
if isBytes(text):
pat = pat.encode('latin1')
return re.match(pat,text,flags)
def process(datafile, notes=0, handout=0, printout=0, cols=0, verbose=0, outDir=None, datafilename=None, fx=1):
"Process one PythonPoint source file."
if not hasattr(datafile, "read"):
if not datafilename: datafilename = datafile
datafile = open(datafile,'rb')
else:
if not datafilename: datafilename = "PseudoFile"
rawdata = datafile.read()
if not isUnicode(rawdata):
encs = ['utf8','iso-8859-1']
m=_re_match(r'^\s*(<\?xml[^>]*\?>)',rawdata)
if m:
m1=_re_match(r"""^.*\sencoding\s*=\s*("[^"]*"|'[^']*')""",m.group(1))
if m1:
enc = m1.group(1)[1:-1]
if enc:
if enc in encs:
encs.remove(enc)
encs.insert(0,enc)
for enc in encs:
try:
udata = rawdata.decode(enc)
break
except:
pass
else:
raise ValueError('cannot decode input data')
else:
udata = rawdata
rawdata = udata
#if pyRXP present, use it to check and get line numbers for errors...
validate(rawdata)
return _process(rawdata, datafilename, notes, handout, printout, cols, verbose, outDir, fx)
def _process(rawdata, datafilename, notes=0, handout=0, printout=0, cols=0, verbose=0, outDir=None, fx=1):
#print 'inner process fx=%d' % fx
from tools.pythonpoint.stdparser import PPMLParser
parser = PPMLParser()
parser.fx = fx
parser.sourceFilename = datafilename
parser.feed(rawdata)
pres = parser.getPresentation()
pres.sourceFilename = datafilename
pres.outDir = outDir
pres.notes = notes
pres.handout = handout
pres.printout = printout
pres.cols = cols
pres.verbose = verbose
if printout:
pres.slides = handleHiddenSlides(pres.slides)
#this does all the work
pdfcontent = pres.save()
if verbose:
print('saved presentation %s.pdf' % os.path.splitext(datafilename)[0])
parser.close()
return pdfcontent
##class P:
## def feed(self, text):
## parser = stdparser.PPMLParser()
## d = pyRXP.parse(text)
##
##
##def process2(datafilename, notes=0, handout=0, cols=0):
## "Process one PythonPoint source file."
##
## import pyRXP, pprint
##
## rawdata = open(datafilename).read()
## d = pyRXP.parse(rawdata)
## pprint.pprint(d)
def handleOptions():
# set defaults
from reportlab import rl_config
options = {'cols':2,
'handout':0,
'printout':0,
'help':0,
'notes':0,
'fx':1,
'verbose':rl_config.verbose,
'silent':0,
'outDir': None}
args = sys.argv[1:]
args = [x for x in args if x and x[0]=='-'] + [x for x in args if not x or x[0]!='-']
try:
shortOpts = 'hnvsx'
longOpts = 'cols= outdir= handout help notes printout verbose silent nofx'.split()
optList, args = getopt.getopt(args, shortOpts, longOpts)
except getopt.error as msg:
options['help'] = 1
if not args and os.path.isfile('pythonpoint.xml'):
args = ['pythonpoint.xml']
# Remove leading dashes (max. two).
for i in range(len(optList)):
o, v = optList[i]
while o[0] == '-':
o = o[1:]
optList[i] = (o, v)
if o == 'cols': options['cols'] = int(v)
elif o=='outdir': options['outDir'] = v
if [ov for ov in optList if ov[0] == 'handout']:
options['handout'] = 1
if [ov for ov in optList if ov[0] == 'printout']:
options['printout'] = 1
if optList == [] and args == [] or \
[ov for ov in optList if ov[0] in ('h', 'help')]:
options['help'] = 1
if [ov for ov in optList if ov[0] in ('n', 'notes')]:
options['notes'] = 1
if [ov for ov in optList if ov[0] in ('x', 'nofx')]:
options['fx'] = 0
if [ov for ov in optList if ov[0] in ('v', 'verbose')]:
options['verbose'] = 1
#takes priority over verbose. Used by our test suite etc.
#to ensure no output at all
if [ov for ov in optList if ov[0] in ('s', 'silent')]:
options['silent'] = 1
options['verbose'] = 0
return options, args
def main():
options, args = handleOptions()
if options['help']:
print(USAGE_MESSAGE)
sys.exit(0)
if options['verbose'] and options['notes']:
print('speaker notes mode')
if options['verbose'] and options['handout']:
print('handout mode')
if options['verbose'] and options['printout']:
print('printout mode')
if not options['fx']:
print('suppressing special effects')
for fileGlobs in args:
files = glob.glob(fileGlobs)
if not files:
print(fileGlobs, "not found")
return
for datafile in files:
if os.path.isfile(datafile):
file = os.path.join(os.getcwd(), datafile)
notes, handout, printout, cols, verbose, fx = options['notes'], options['handout'], options['printout'], options['cols'], options['verbose'], options['fx']
process(file, notes, handout, printout, cols, verbose, options['outDir'], fx=fx)
else:
print('Data file not found:', datafile)
if __name__ == '__main__':
main()
|