def run(pagesize=None, verbose=1, outDir=None): import os from reportlab.tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize from reportlab.tools.docco import rl_doc_utils from reportlab.lib.utils import open_and_read, _RL_DIR if not outDir: outDir = os.path.join(_RL_DIR,'docs') destfn = os.path.join(outDir,'graphguide.pdf') doc = RLDocTemplate(destfn,pagesize = pagesize or defaultPageSize) #this builds the story setStory() G = {} exec 'from reportlab.tools.docco.rl_doc_utils import *' in G, G doc = RLDocTemplate(destfn,pagesize = pagesize or defaultPageSize) for f in ( 'ch1_intro', 'ch2_concepts', 'ch3_shapes', 'ch4_widgets', 'ch5_charts', ): exec open_and_read(f+'.py',mode='t') in G, G del G story = getStory() if verbose: print 'Built story contains %d flowables...' % len(story) doc.build(story) if verbose: print 'Saved "%s"' % destfn
def run(pagesize=None, verbose=0, outDir=None): import os from reportlab.tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize from reportlab.tools.docco import rl_doc_utils from reportlab.lib.utils import open_and_read, _RL_DIR if not outDir: outDir = os.path.join(_RL_DIR, 'docs') destfn = os.path.join(outDir, 'userguide.pdf') doc = RLDocTemplate(destfn, pagesize=pagesize or defaultPageSize) #this builds the story setStory() G = {} exec 'from reportlab.tools.docco.rl_doc_utils import *' in G, G for f in ( 'ch1_intro', 'ch2_graphics', 'ch2a_fonts', 'ch3_pdffeatures', 'ch4_platypus_concepts', 'ch5_paragraphs', 'ch6_tables', 'ch7_custom', 'ch9_future', 'app_demos', ): exec open_and_read(f + '.py', mode='t') in G, G del G story = getStory() if verbose: print 'Built story contains %d flowables...' % len(story) doc.build(story) if verbose: print 'Saved "%s"' % destfn
def run(pagesize=None, verbose=0, outDir=None): import os from reportlab.tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize from reportlab.tools.docco import rl_doc_utils from reportlab.lib.utils import open_and_read, _RL_DIR if not outDir: outDir = os.path.join(_RL_DIR,'docs') destfn = os.path.join(outDir,'userguide.pdf') doc = RLDocTemplate(destfn,pagesize = pagesize or defaultPageSize) #this builds the story setStory() G = {} exec 'from reportlab.tools.docco.rl_doc_utils import *' in G, G for f in ( 'ch1_intro', 'ch2_graphics', 'ch2a_fonts', 'ch3_pdffeatures', 'ch4_platypus_concepts', 'ch5_paragraphs', 'ch6_tables', 'ch7_custom', 'ch9_future', 'app_demos', ): exec open_and_read(f+'.py',mode='t') in G, G del G story = getStory() if verbose: print 'Built story contains %d flowables...' % len(story) doc.build(story) if verbose: print 'Saved "%s"' % destfn
def run(pagesize=None, verbose=0, outDir=None): import sys, os from reportlab.lib.utils import open_and_read cwd = os.getcwd() docsDir = os.path.dirname(os.path.dirname(sys.argv[0]) or cwd) topDir = os.path.dirname(docsDir) if not outDir: outDir = docsDir G = {} sys.path.insert(0, topDir) from reportlab.pdfbase.pdfmetrics import registerFontFamily from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf')) registerFontFamily('Vera', normal='Vera', bold='VeraBd', italic='VeraIt', boldItalic='VeraBI') from tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize, H1, H2, H3, H4 from tools.docco import rl_doc_utils exec 'from tools.docco.rl_doc_utils import *' in G, G destfn = os.path.join(outDir, 'reportlab-userguide.pdf') doc = RLDocTemplate(destfn, pagesize=pagesize or defaultPageSize) #this builds the story setStory() for f in ( 'ch1_intro', 'ch2_graphics', 'ch2a_fonts', 'ch3_pdffeatures', 'ch4_platypus_concepts', 'ch5_paragraphs', 'ch6_tables', 'ch7_custom', 'graph_intro', 'graph_concepts', 'graph_charts', 'graph_shapes', 'graph_widgets', 'app_demos', ): exec open_and_read(f + '.py', mode='t') in G, G del G story = getStory() if verbose: print 'Built story contains %d flowables...' % len(story) doc.multiBuild(story) if verbose: print 'Saved "%s"' % destfn
def run(pagesize=None, verbose=0, outDir=None): import sys,os from reportlab.lib.utils import open_and_read cwd = os.getcwd() docsDir=os.path.dirname(os.path.dirname(sys.argv[0]) or cwd) topDir=os.path.dirname(docsDir) if not outDir: outDir=docsDir G = {} sys.path.insert(0,topDir) from reportlab.pdfbase.pdfmetrics import registerFontFamily from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf')) registerFontFamily('Vera',normal='Vera',bold='VeraBd',italic='VeraIt',boldItalic='VeraBI') from tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize, H1, H2, H3, H4 from tools.docco import rl_doc_utils exec 'from tools.docco.rl_doc_utils import *' in G, G destfn = os.path.join(outDir,'reportlab-userguide.pdf') doc = RLDocTemplate(destfn,pagesize = pagesize or defaultPageSize) #this builds the story setStory() for f in ( 'ch1_intro', 'ch2_graphics', 'ch2a_fonts', 'ch3_pdffeatures', 'ch4_platypus_concepts', 'ch5_paragraphs', 'ch6_tables', 'ch7_custom', 'graph_intro', 'graph_concepts', 'graph_charts', 'graph_shapes', 'graph_widgets', 'app_demos', ): exec open_and_read(f+'.py',mode='t') in G, G del G story = getStory() if verbose: print 'Built story contains %d flowables...' % len(story) doc.multiBuild(story) if verbose: print 'Saved "%s"' % destfn
def checkFileForTabs(self, filename): txt = open_and_read(filename, 'r') chunks = string.split(txt, '\t') tabCount = len(chunks) - 1 if tabCount: #raise Exception, "File %s contains %d tab characters!" % (filename, tabCount) self.output.write("file %s contains %d tab characters!\n" % (filename, tabCount))
def checkFileForTabs(self, filename): txt = open_and_read(filename, "r") chunks = string.split(txt, "\t") tabCount = len(chunks) - 1 if tabCount: # raise Exception, "File %s contains %d tab characters!" % (filename, tabCount) self.output.write("file %s contains %d tab characters!\n" % (filename, tabCount))
def eoCB(s, targets=targets, dtdDirs=dtdDirs): from reportlab.lib.utils import open_and_read, rl_isfile bn = os.path.basename(s) if bn in targets: for d in dtdDirs: fn = os.path.join(d, bn) if rl_isfile(fn): return fn, open_and_read(fn, 't') return s
def eoCB(s,targets=targets,dtdDirs=dtdDirs): from reportlab.lib.utils import open_and_read, rl_isfile bn = os.path.basename(s) if bn in targets: for d in dtdDirs: fn = os.path.join(d,bn) if rl_isfile(fn): return fn, open_and_read(fn,'t') return s
def _rel_open_and_read(fn): from reportlab.lib.utils import open_and_read from reportlab.lib.testutils import testsFolder cwd = os.getcwd() os.chdir(testsFolder) try: return open_and_read(fn) finally: os.chdir(cwd)
def run(pagesize=None, verbose=0, outDir=None): import sys, os from reportlab.lib.utils import open_and_read cwd = os.getcwd() docsDir = os.path.dirname(os.path.dirname(sys.argv[0]) or cwd) topDir = os.path.dirname(docsDir) if not outDir: outDir = docsDir G = {} sys.path.insert(0, topDir) from reportlab.pdfbase.pdfmetrics import registerFontFamily from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont("Vera", "Vera.ttf")) pdfmetrics.registerFont(TTFont("VeraBd", "VeraBd.ttf")) pdfmetrics.registerFont(TTFont("VeraIt", "VeraIt.ttf")) pdfmetrics.registerFont(TTFont("VeraBI", "VeraBI.ttf")) registerFontFamily("Vera", normal="Vera", bold="VeraBd", italic="VeraIt", boldItalic="VeraBI") from tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize, H1, H2, H3, H4 from tools.docco import rl_doc_utils exec("from tools.docco.rl_doc_utils import *", G, G) destfn = os.path.join(outDir, "reportlab-userguide.pdf") doc = RLDocTemplate(destfn, pagesize=pagesize or defaultPageSize) # this builds the story setStory() for f in ( "ch1_intro", "ch2_graphics", "ch2a_fonts", "ch3_pdffeatures", "ch4_platypus_concepts", "ch5_paragraphs", "ch6_tables", "ch7_custom", "graph_intro", "graph_concepts", "graph_charts", "graph_shapes", "graph_widgets", "app_demos", ): exec(open_and_read(f + ".py", mode="t"), G, G) del G story = getStory() if verbose: print("Built story contains %d flowables..." % len(story)) doc.multiBuild(story) if verbose: print('Saved "%s"' % destfn)
def xml2rad(xml, validating=1, eoCB=None): '''convert xml to radxml form''' if validating: from reportlab.lib.utils import isCompactDistro, open_and_read if not eoCB and isCompactDistro(): eoCB = lambda x, open_and_read=open_and_read: (x, open_and_read(x)) import pyRXPU rad = pyRXPU.Parser().parse(xml,eoCB=eoCB) else: from reportlab.lib import rparsexml rad = rparsexml.parsexml0(xml)[0][2][0] return rad
def xml2rad(xml, validating=1, eoCB=None): '''convert xml to radxml form''' if validating: from reportlab.lib.utils import isCompactDistro, open_and_read if not eoCB and isCompactDistro(): eoCB = lambda x, open_and_read=open_and_read: (x, open_and_read(x)) import pyRXPU rad = pyRXPU.Parser().parse(xml, eoCB=eoCB) else: from reportlab.lib import rparsexml rad = rparsexml.parsexml0(xml)[0][2][0] return rad
def testAscii(self): "Test if Python files are pure ASCII ones." from reportlab.lib.testutils import RL_HOME allPyFiles = GlobDirectoryWalker(RL_HOME, '*.py') for path in allPyFiles: fileContent = open_and_read(path,'r') nonAscii = u''.join(list(set([c for c in fileContent if ord(c)>127]))) truncPath = path[path.find('reportlab'):] args = (truncPath, repr(map(ord, nonAscii))) msg = "File %s contains characters: %s." % args assert len(nonAscii) == 0, msg
def run(pagesize=None, verbose=0, outDir=None): import os from reportlab.tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize from reportlab.tools.docco import rl_doc_utils from reportlab.lib.utils import open_and_read, _RL_DIR if not outDir: outDir = '../manuals/'#os.path.join(_RL_DIR,'docs') if not os.path.isdir(outDir): os.mkdir(outDir) destfn = os.path.join(outDir,'X4 - Installazione.pdf') doc = RLDocTemplate(destfn,pagesize = pagesize or defaultPageSize) doc.title = 'X4 Setup' doc.subject = 'Manuale di installazione di X4GA' doc.author = 'Astra S.r.l.' #this builds the story setStory() G = {} exec 'from reportlab.tools.docco.rl_doc_utils import *' in G, G for f in ( 'ch1_intro', 'ch2_dbengine', 'ch3_workstation', #'ch3_pdffeatures', #'ch4_platypus_concepts', #'ch5_paragraphs', #'ch6_tables', #'ch7_custom', #'ch9_future', #'app_demos', ): exec open_and_read(f+'.py',mode='t') in G, G del G story = getStory() if verbose: print 'Built story contains %d flowables...' % len(story) doc.build(story) if verbose: print 'Saved "%s"' % destfn
def run(pagesize=None, verbose=0, outDir=None): import os from reportlab.tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize from reportlab.tools.docco import rl_doc_utils from reportlab.lib.utils import open_and_read, _RL_DIR if not outDir: outDir = '../manuals/' #os.path.join(_RL_DIR,'docs') if not os.path.isdir(outDir): os.mkdir(outDir) destfn = os.path.join(outDir, 'X4 - Installazione.pdf') doc = RLDocTemplate(destfn, pagesize=pagesize or defaultPageSize) doc.title = 'X4 Setup' doc.subject = 'Manuale di installazione di X4GA' doc.author = 'Astra S.r.l.' #this builds the story setStory() G = {} exec 'from reportlab.tools.docco.rl_doc_utils import *' in G, G for f in ( 'ch1_intro', 'ch2_dbengine', 'ch3_workstation', #'ch3_pdffeatures', #'ch4_platypus_concepts', #'ch5_paragraphs', #'ch6_tables', #'ch7_custom', #'ch9_future', #'app_demos', ): exec open_and_read(f + '.py', mode='t') in G, G del G story = getStory() if verbose: print 'Built story contains %d flowables...' % len(story) doc.build(story) if verbose: print 'Saved "%s"' % destfn
def main(fn): import os from reportlab.lib.utils import open_and_read from reportlab.lib.pdfencrypt import encryptPdfInMemory pdf_bytes = open_and_read(fn) ofn = os.path.splitext(os.path.basename(fn))[0] with open(ofn + '-encrypted.pdf', 'wb') as f: f.write( encryptPdfInMemory(pdf_bytes, 'master', 'user', canModify=0, canCopy=0, strength=128))
def checkFileForTrailingSpaces(self, filename): txt = open_and_read(filename, 'r') initSize = len(txt) badLines = 0 badChars = 0 for line in string.split(txt, '\n'): stripped = string.rstrip(line) spaces = len(line) - len(stripped) # OK, so they might be trailing tabs, who cares? if spaces: badLines = badLines + 1 badChars = badChars + spaces if badChars <> 0: self.output.write("file %s contains %d trailing spaces, or %0.2f%% wastage\n" % (filename, badChars, 100.0*badChars/initSize))
def checkFileForTrailingSpaces(self, filename): txt = open_and_read(filename, 'r') initSize = len(txt) badLines = 0 badChars = 0 for line in string.split(txt, '\n'): stripped = string.rstrip(line) spaces = len(line) - len(stripped) # OK, so they might be trailing tabs, who cares? if spaces: badLines = badLines + 1 badChars = badChars + spaces if badChars != 0: self.output.write("file %s contains %d trailing spaces, or %0.2f%% wastage\n" % (filename, badChars, 100.0*badChars/initSize))
def _loadGlyphs(self, pfbFileName): """Loads in binary glyph data, and finds the four length measurements needed for the font descriptor""" assert rl_isfile(pfbFileName), 'file %s not found' % pfbFileName d = open_and_read(pfbFileName, 'b') s1, l1 = _pfbCheck(0,d,PFB_ASCII,pfbFileName) s2, l2 = _pfbCheck(l1,d,PFB_BINARY,pfbFileName) s3, l3 = _pfbCheck(l2,d,PFB_ASCII,pfbFileName) _pfbCheck(l3,d,PFB_EOF,pfbFileName) self._binaryData = d[s1:l1]+d[s2:l2]+d[s3:l3] self._length = len(self._binaryData) self._length1 = l1-s1 self._length2 = l2-s2 self._length3 = l3-s3
def testAscii(self): "Test if Python files are pure ASCII ones." from reportlab.lib.testutils import RL_HOME allPyFiles = GlobDirectoryWalker(RL_HOME, '*.py') for path in allPyFiles: fileContent = open_and_read(path, 'r') nonAscii = filter(lambda c: ord(c) > 127, fileContent) nonAscii = unique(nonAscii) truncPath = path[string.find(path, 'reportlab'):] args = (truncPath, repr(map(ord, nonAscii))) msg = "File %s contains characters: %s." % args ## if nonAscii: ## print msg assert nonAscii == '', msg
def _loadGlyphs(self, pfbFileName): """Loads in binary glyph data, and finds the four length measurements needed for the font descriptor""" pfbFileName = bruteForceSearchForFile(pfbFileName) assert rl_isfile(pfbFileName), 'file %s not found' % pfbFileName d = open_and_read(pfbFileName, 'b') s1, l1 = _pfbCheck(0,d,PFB_ASCII,pfbFileName) s2, l2 = _pfbCheck(l1,d,PFB_BINARY,pfbFileName) s3, l3 = _pfbCheck(l2,d,PFB_ASCII,pfbFileName) _pfbCheck(l3,d,PFB_EOF,pfbFileName) self._binaryData = d[s1:l1]+d[s2:l2]+d[s3:l3] self._length = len(self._binaryData) self._length1 = l1-s1 self._length2 = l2-s2 self._length3 = l3-s3
def testAscii(self): "Test if Python files are pure ASCII ones." from reportlab.lib.testutils import RL_HOME allPyFiles = GlobDirectoryWalker(RL_HOME, '*.py') for path in allPyFiles: fileContent = open_and_read(path,'r') nonAscii = filter(lambda c: ord(c)>127, fileContent) nonAscii = unique(nonAscii) truncPath = path[string.find(path, 'reportlab'):] args = (truncPath, repr(map(ord, nonAscii))) msg = "File %s contains characters: %s." % args ## if nonAscii: ## print msg assert nonAscii == '', msg
def epsBBox(fn,bbpat=re.compile(r'^\s*%%boundingbox:\s*(.*)\s*$',re.I|re.M)): ''' read an eps file and attempt to obtain its bounding box >>> cleanup() >>> x=pdfConvert('zzzdingo.pdf',scale=0.5,device='eps',outfile='zzzdingo.eps') >>> assert x and os.path.isfile(os.path.basename(x[0])) >>> print epsBBox('zzzdingo.eps') [0, 0, 100, 50] ''' text = open_and_read(fn) m=bbpat.search(text) if not m: raise ValueError('Cannot find bounding box in "%s"' % fn) bb = m.group(1).strip().split() if len(bb)!=4: raise ValueError('Not enough bounding box entries "%s" found in "%s"' % (m.group(0).strip(),fn)) try: return list(map(float,bb)) except: raise ValueError('Bad bounding box entries "%s" found in "%s"' % (m.group(0).strip(),fn))
def open(self, fileName): """Parse and resolve a PDF file as much as possible""" from reportlab.lib.utils import open_and_read self.rawContent = open_and_read(fileName) self._parse()
def includePdfFlowables(fileName, pages=None, dx=0, dy=0, sx=1, sy=1, degrees=0, orientation=None, isdata=False, #True if this is a preprocessed data file leadingBreak=True, #True/False or 'notattop' template=None, outlineText=None, outlineLevel=0, outlineClosed=0, pdfBoxType = None, autoCrop = False, pageSize=None, callback=None, user_data=None, ): ''' includePdfFlowables creates a list of story flowables that represents an included PDF. Arguments meaning fileName string name of a .pdf or .data file pages If None all pages will be used, else this argument can be a string like '1,2,4-6,12-10,15' or an explicit list of integers eg [1,2,7]. dx,dy, translation together all these make up a transformation sx,sy, scaling matrix degrees, rotation orientation None or integer degrees eg 0 90 270 or 'portrait'/'landscape' isdata True if fileName argument refers to a .data file (as produced by pageCatcher) leadingBreak True/False or 'notattop' specifies whether a leading page break should be used; 'notattop' means a page break will not be used if the story is at the top of a frame. template If specified the index or name of a template to be used. outlineText Any outline text to be used (default None) outlineLevel The level of any outline text. outlineClosed True/False if the outline should be closed or open. pdfBoxType which box to use or None or [x0,y0, x1,y1] autoCrop True/False crop/don't crop with CropBox (default is False) boxname use for cropping [x0,y0, x1,y1] crop area pageSize default None ie leave page size alone 'set' adjust page size to incoming box 'fit' scale incoming box to fit page size 'orthfit' orthogonally scale incoming box to fit 'center' or 'centre' center the incoming box in the existing page size [x0,y0, x1,y1] use this as the page size callback draw time callback with signature callback(canvas,key,obj,pdf_data,user_data) canvas the canvas being drawn on key may be 'raw-pre'|'transformed-pre'|'transformed-post'|'raw-post' obj the flowable calling the callback pdf_data ('fileName',pageNumber) user_data user data passed down to the flowable from IncludePdfFlowable. user_data information to be passed to the callback ''' try: orientation=int(orientation) orientation = orientation % 360 except: if orientation=='portrait': orientation = 0 elif orientation=='landscape': orientation = 90 elif orientation!='auto' and orientation!=None: raise ValueError('Bad value %r for orientation attribute' % orientation) iptrans = IPTrans(sx,sy,dx,dy,degrees) if iptrans.trivial(): iptrans = None pages = expandPageNumbers(pages) # this one is unusual in that it returns a list of objects to # go into the story. output = [] output_append = output.append if template: output_append(NextPageTemplate(template)) try: if isdata: pickledStuff = pickle.loads(open_and_read(fileName)) formNames = pickledStuff[None] else: #read in the PDF file right now and get the pickled object # and names pdfContent = open_and_read(fileName) prefix = fileName2Prefix(fileName) (formNames, pickledStuff) = storeFormsInMemory( pdfContent, prefix=prefix, all=1, BBoxes=0, extractText=0, fformname=None) except: annotateException('\nerror storing %r in memory\n' % fileName) #if explicit pages requested, slim it down. if pages: newNames = [] for pgNo in pages: newNames.append(formNames[pgNo-1]) formNames = newNames #make object 1 for story loader = LoadPdfFlowable(pickledStuff,isdata) output_append(loader) #now do first page. This is special as it might #have an outline formName = formNames[0] if leadingBreak: output_append((leadingBreak=='notattop' and NotAtTopPageBreak or PageBreak)()) if outlineText: output_append(OutlineEntry(outlineLevel, outlineText, outlineClosed)) if pageSize=='fit': class PageSizeHandler(object): '''simple class to allow communications between first and last ShowPdfFlowables''' _oldPageSize = [None] def __init__(self,first): self.first = first def oldPageSize(self,v): self._oldPageSize[0] = v oldPageSize = property(lambda self: self._oldPageSize[0],oldPageSize) pageSizeHandler = PageSizeHandler(True) else: pageSizeHandler = None output_append(ShowPdfFlowable(formName,orientation=orientation,iptrans=iptrans, callback=callback, pdf_data=(fileName,pages[0] if pages else 1), user_data=user_data, pdfBoxType=pdfBoxType, autoCrop=autoCrop, pageSize=pageSize, pageSizeHandler=pageSizeHandler, )) #now make a shower for each laterpage, and a page break for i,formName in enumerate(formNames[1:]): i += 1 output_append(PageBreak()) output_append(ShowPdfFlowable(formName,orientation=orientation,iptrans=iptrans, callback=callback, pdf_data=(fileName,pages[i] if pages else i), user_data=user_data, pdfBoxType=pdfBoxType, autoCrop=autoCrop, pageSize=pageSize, pageSizeHandler=None, )) if pageSize=='fit': output[-1]._pageSizeHandler = PageSizeHandler(False) return output
def test10(self): "test open and read of a simple relative file" from reportlab.lib.utils import open_and_read, getStringIO b = getStringIO(open_and_read('../docs/images/Edit_Prefs.gif')) b = open_and_read(b)
def test10(self): "test open and read of a simple relative file" from reportlab.lib.utils import open_and_read, getStringIO b = getStringIO(_rel_open_and_read('../docs/images/Edit_Prefs.gif')) b = open_and_read(b)
def test7(self): "test open and read of a simple relative file" from reportlab.lib.utils import open_and_read b = open_and_read('../docs/images/Edit_Prefs.gif')
def eocb(URI, dtdText=open_and_read(dtd), dtd=dtd): if os.path.basename(URI) == "pythonpoint.dtd": return dtd, dtdText return URI
def includePdfFlowables(fileName, pages=None, dx=0, dy=0, sx=1, sy=1, degrees=0, orientation=None, isdata=False, #True if this is a preprocessed data file leadingBreak=True, #True/False or 'notattop' template=None, outlineText=None, outlineLevel=0, outlineClosed=0, pdfBoxType = None, autoCrop = False, pageSize=None, callback=None, user_data=None, ): ''' includePdfFlowables creates a list of story flowables that represents an included PDF. Arguments meaning fileName string name of a .pdf or .data file or an object with a read method pages If None all pages will be used, else this argument can be a string like '1,2,4-6,12-10,15' or an explicit list of integers eg [1,2,7]. dx,dy, translation together all these make up a transformation sx,sy, scaling matrix degrees, rotation orientation None or integer degrees eg 0 90 270 or 'portrait'/'landscape' isdata True if fileName argument refers to a .data file (as produced by pageCatcher) leadingBreak True/False or 'notattop' specifies whether a leading page break should be used; 'notattop' means a page break will not be used if the story is at the top of a frame. template If specified the index or name of a template to be used. outlineText Any outline text to be used (default None) outlineLevel The level of any outline text. outlineClosed True/False if the outline should be closed or open. pdfBoxType which box to use or None or [x0,y0, x1,y1] autoCrop True/False crop/don't crop with CropBox (default is False) boxname use for cropping [x0,y0, x1,y1] crop area pageSize default None ie leave page size alone 'set' adjust page size to incoming box 'fit' scale incoming box to fit page size 'orthfit' orthogonally scale incoming box to fit 'center' or 'centre' center the incoming box in the existing page size [x0,y0, x1,y1] use this as the page size callback draw time callback with signature callback(canvas,key,obj,pdf_data,user_data) canvas the canvas being drawn on key may be 'raw-pre'|'transformed-pre'|'transformed-post'|'raw-post' obj the flowable calling the callback pdf_data ('fileName',pageNumber) user_data user data passed down to the flowable from IncludePdfFlowable. user_data information to be passed to the callback ''' try: orientation=int(orientation) orientation = orientation % 360 except: if orientation=='portrait': orientation = 0 elif orientation=='landscape': orientation = 90 elif orientation!='auto' and orientation!=None: raise ValueError('Bad value %r for orientation attribute' % orientation) iptrans = IPTrans(sx,sy,dx,dy,degrees) if iptrans.trivial(): iptrans = None pages = expandPageNumbers(pages) # this one is unusual in that it returns a list of objects to # go into the story. output = [] output_append = output.append if template: output_append(NextPageTemplate(template)) try: if isdata: pickledStuff = pickle.loads(open_and_read(fileName)) formNames = pickledStuff[None] else: #read in the PDF file right now and get the pickled object # and names pdfContent = open_and_read(fileName) prefix = fileName2Prefix(fileName if isStr(fileName) else pdfContent) (formNames, pickledStuff) = storeFormsInMemory( pdfContent, prefix=prefix, all=1,#if pages else 0 #here is where things go wrong #pagenumbers = pages, BBoxes=0, extractText=0, fformname=None) except: annotateException('\nerror storing %r in memory\n' % fileName) #if explicit pages requested, slim it down. if pages: #and isdata: newNames = [] for pgNo in pages: newNames.append(formNames[pgNo-1]) formNames = newNames #make object 1 for story loader = LoadPdfFlowable(pickledStuff,isdata) output_append(loader) #now do first page. This is special as it might #have an outline formName = formNames[0] if leadingBreak: output_append((leadingBreak=='notattop' and NotAtTopPageBreak or PageBreak)()) if outlineText: output_append(OutlineEntry(outlineLevel, outlineText, outlineClosed)) if pageSize=='fit': class PageSizeHandler(object): '''simple class to allow communications between first and last ShowPdfFlowables''' _oldPageSize = [None] def __init__(self,first): self.first = first def oldPageSize(self,v): self._oldPageSize[0] = v oldPageSize = property(lambda self: self._oldPageSize[0],oldPageSize) pageSizeHandler = PageSizeHandler(True) else: pageSizeHandler = None output_append(ShowPdfFlowable(formName,orientation=orientation,iptrans=iptrans, callback=callback, pdf_data=(fileName,pages[0] if pages else 1), user_data=user_data, pdfBoxType=pdfBoxType, autoCrop=autoCrop, pageSize=pageSize, pageSizeHandler=pageSizeHandler, )) #now make a shower for each laterpage, and a page break for i,formName in enumerate(formNames[1:]): i += 1 output_append(PageBreak()) output_append(ShowPdfFlowable(formName,orientation=orientation,iptrans=iptrans, callback=callback, pdf_data=(fileName,pages[i] if pages else i), user_data=user_data, pdfBoxType=pdfBoxType, autoCrop=autoCrop, pageSize=pageSize, pageSizeHandler=None, )) if pageSize=='fit': output[-1]._pageSizeHandler = PageSizeHandler(False) return output
def open(self, fileName): """Parse and resolve a PDF file as much as possible""" self.rawContent = open_and_read(fileName) self._parse()
def test8(self): "test open and read of a relative file: URL" from reportlab.lib.utils import open_and_read b = open_and_read('file:../docs/images/Edit_Prefs.gif')
def test9(self): "test open and read of an http: URL" from reportlab.lib.utils import open_and_read b = open_and_read('http://www.reportlab.com/rsrc/encryption.gif')
def eocb(URI,dtdText=open_and_read(dtd),dtd=dtd): if os.path.basename(URI)=='pythonpoint.dtd': return dtd,dtdText return URI