Exemplo n.º 1
0
 def testRml(self):
     source = open(self.fileName, 'rb').read()
     expectError = getattr(self,'expectError',False)
     try:
         rml2pdf.go(source)
         if expectError:
             raise ValueError('Expected error in %s did not occur' % self.fileName)
     except Exception as e:
         if not expectError:
             annotateException('while rendering %s' % self.fileName)
 def works(self, expr, g=None, l=None):
     try:
         answer = eval(expr, g, l)
         result = rl_safe_eval(expr, g, l)
     except:
         print('expr=%r' % expr)
         annotateException('\nexpr=%r\n' % expr)
     self.assertEqual(
         answer, result,
         "rl_safe_eval(%r) = %r not expected %r" % (expr, result, answer))
    def drawOn(self, canvas, x, y, _sW=0):
        iptrans = self._iptrans
        matrix = self._orientation
        pdfBoxType = self._pdfBoxType
        autoCrop = self._autoCrop
        pageSize = self._pageSize
        doTrans = iptrans and not iptrans.trivial()
        self.callback('raw-pre',canvas)
        restore = doTrans or autoCrop or pdfBoxType or matrix!=None or pageSize
        if restore:
            xi = _formName2ExtraInfo(canvas,self.formName)
            canvas.saveState()
            if pdfBoxType or matrix is not None or pageSize:
                matrix = _formName2OrientationMatrix(canvas,self.formName,matrix,pdfBoxType,pageSize,xi,self._pageSizeHandler)
                if matrix:
                    canvas.transform(*matrix)
            if iptrans:
                if not iptrans.noRotate():
                    canvas.rotate(iptrans.degrees)
                if not iptrans.noTranslate():
                    canvas.translate(iptrans.dx,iptrans.dy)
                if not iptrans.noScale():
                    canvas.scale(iptrans.sx,iptrans.sy)
            self.callback('transformed-pre',canvas)

        if autoCrop:
            if isinstance(autoCrop,(list,tuple)):
                clip = list(map(float,autoCrop))
            elif isinstance(autoCrop,str):
                clip = xi[normalizeBoxName(autoCrop)]
            else:
                clip = xi['CropBox']
            P = (clip[0],clip[1]),(clip[0],clip[3]),(clip[2],clip[3]),(clip[2],clip[1])
            #if canvas._code and canvas._code[-1][-3:]==' cm':
            #   L = canvas._code[-1].split()
            #   transform = list(map(float,L[-7:-1]))
            #   P = transformPoints(transform,P)
            path = canvas.beginPath()
            path.moveTo(*P[0])
            path.lineTo(*P[1])
            path.lineTo(*P[2])
            path.lineTo(*P[3])
            path.close()
            canvas.clipPath(path,0,0)

        try:
            #this won't do much if already loaded
            canvas.doForm(self.formName)
        except:
            annotateException('\ncnvas.doForm(%r) error handling %r' % (self.formName,self._pdf_data))

        if restore:
            self.callback('transformed-post',canvas)
            canvas.restoreState()
        self.callback('raw-post',canvas)
Exemplo n.º 4
0
    def drawOn(self, canvas, x, y, _sW=0):
        iptrans = self._iptrans
        matrix = self._orientation
        pdfBoxType = self._pdfBoxType
        autoCrop = self._autoCrop
        pageSize = self._pageSize
        doTrans = iptrans and not iptrans.trivial()
        self.callback('raw-pre',canvas)
        restore = doTrans or autoCrop or pdfBoxType or matrix!=None or pageSize
        if restore:
            xi = _formName2ExtraInfo(canvas,self.formName)
            canvas.saveState()
            if pdfBoxType or matrix is not None or pageSize:
                matrix = _formName2OrientationMatrix(canvas,self.formName,matrix,pdfBoxType,pageSize,xi,self._pageSizeHandler)
                if matrix:
                    canvas.transform(*matrix)
            if iptrans:
                if not iptrans.noRotate():
                    canvas.rotate(iptrans.degrees)
                if not iptrans.noTranslate():
                    canvas.translate(iptrans.dx,iptrans.dy)
                if not iptrans.noScale():
                    canvas.scale(iptrans.sx,iptrans.sy)
            self.callback('transformed-pre',canvas)

        if autoCrop:
            if isinstance(autoCrop,(list,tuple)):
                clip = list(map(float,autoCrop))
            elif isinstance(autoCrop,str):
                clip = xi[normalizeBoxName(autoCrop)]
            else:
                clip = xi['CropBox']
            P = (clip[0],clip[1]),(clip[0],clip[3]),(clip[2],clip[3]),(clip[2],clip[1])
            #if canvas._code and canvas._code[-1][-3:]==' cm':
            #   L = canvas._code[-1].split()
            #   transform = list(map(float,L[-7:-1]))
            #   P = transformPoints(transform,P)
            path = canvas.beginPath()
            path.moveTo(*P[0])
            path.lineTo(*P[1])
            path.lineTo(*P[2])
            path.lineTo(*P[3])
            path.close()
            canvas.clipPath(path,0,0)

        try:
            #this won't do much if already loaded
            canvas.doForm(self.formName)
        except:
            annotateException('\ncnvas.doForm(%r) error handling %r' % (self.formName,self._pdf_data))

        if restore:
            self.callback('transformed-post',canvas)
            canvas.restoreState()
        self.callback('raw-post',canvas)
Exemplo n.º 5
0
 def parse(self, text, style):
     "attempt replacement for parse"
     self._setup_for_parse(style)
     text = asUnicode(text)
     if not(len(text)>=6 and text[0]=='<' and _re_para.match(text)):
         text = u"<para>"+text+u"</para>"
     try:
         self.feed(text)
     except:
         annotateException('paragraph text %s caused exception' % ascii(text))
     return self._complete_parse()
Exemplo n.º 6
0
 def parse(self, text, style):
     "attempt replacement for parse"
     self._setup_for_parse(style)
     text = asUnicode(text)
     if not(len(text)>=6 and text[0]=='<' and _re_para.match(text)):
         text = u"<para>"+text+u"</para>"
     try:
         self.feed(text)
     except:
         annotateException('paragraph text %s caused exception' % ascii(text))
     return self._complete_parse()
Exemplo n.º 7
0
    def _calc_width(self,availWidth,W=None):
        if getattr(self,'_width_calculated_once',None): return
        #comments added by Andy to Robin's slightly terse variable names
        if not W: W = self._argW
        # if not W: W = _calc_pc(self._argW,availWidth)   #widths array
        canv = getattr(self,'canv',None)
        saved = None
        if self._spanCmds:
            colSpanCells = self._colSpanCells
            spanRanges = self._spanRanges
        else:
            colSpanCells = ()
            spanRanges = {}
        spanCons = {}
        if W is self._argW:
            W0 = W
            W = W[:]
        else:
            W0 = W[:]
        V = self._cellvalues
        S = self._cellStyles
        # calc minimal needed widths
        needed_widths = []
        for j,w in enumerate(W):
            if w is None:
                w = self._calcColumnWidth(j,spanRanges,colSpanCells,spanCons)
            needed_widths.append(w)
        for j,w in enumerate(needed_widths):
            if isinstance(w,str):
                fac = float(w.rstrip('%'))/100
                tables.spanFixDim(W0,W,spanCons,lim=j-1)
                W[j] = (availWidth-sum(W[:j]))*fac
            else:
                W[j] = w
        if spanCons:
            try:
                tables.spanFixDim(W0,W,spanCons)
            except:
                annotateException('\nspanning problem in %s\nW0=%r W=%r\nspanCons=%r' % (self.identity(),W0,W,spanCons))

        self._colWidths = W
        width = 0
        self._colpositions = [0]        #index -1 is right side boundary; we skip when processing cells
        for w in W:
            width = width + w
            self._colpositions.append(width)

        self._width = width
        self._width_calculated_once = 1
Exemplo n.º 8
0
 def apply(self,doc):
     '''
     This is called by the doc.build processing to allow the instance to
     implement its behaviour
     '''
     action = self.action[0]
     args = tuple(self.action[1:])
     arn = 'handle_'+action
     if arn=="handle_nextPageTemplate" and args[0]=='main':
         pass
     try:
         getattr(doc,arn)(*args)
     except AttributeError as aerr:
         if aerr.args[0]==arn:
             raise NotImplementedError("Can't handle ActionFlowable(%s)" % action)
         else:
             raise
     except:
         annotateException("\nhandle_%s args=%s"%(action,ascii(args)))
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
Exemplo n.º 10
0
 def tokens(s):
     try:
         return list(tokenize.generate_tokens(getStringIO(s).readline))
     except:
         annotateException(': line=%r' % s)
Exemplo n.º 11
0
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