Пример #1
0
 def add_resources(self):
     r = Dictionary()
     if self.opacities:
         extgs = Dictionary()
         for opref, name in self.opacities.iteritems():
             extgs[name] = opref
         r['ExtGState'] = extgs
     if self.fonts:
         fonts = Dictionary()
         for ref, name in self.fonts.iteritems():
             fonts[name] = ref
         r['Font'] = fonts
     if self.xobjects:
         xobjects = Dictionary()
         for ref, name in self.xobjects.iteritems():
             xobjects[name] = ref
         r['XObject'] = xobjects
     if self.patterns:
         r['ColorSpace'] = Dictionary({'PCSp':Array(
             [Name('Pattern'), Name('DeviceRGB')])})
         patterns = Dictionary()
         for ref, name in self.patterns.iteritems():
             patterns[name] = ref
         r['Pattern'] = patterns
     if r:
         self.page_dict['Resources'] = r
Пример #2
0
 def process_toc_item(self, toc, parentref):
     path = toc.abspath or None
     frag = toc.fragment or None
     if path is None:
         return
     path = os.path.normcase(os.path.abspath(path))
     if path not in self.anchors:
         return None
     a = self.anchors[path]
     dest = a.get(frag, a[None])
     item = Dictionary({'Parent':parentref, 'Dest':dest,
                        'Title':String(toc.text or _('Unknown'))})
     return self.pdf.objects.add(item)
Пример #3
0
 def __init__(self,
              cache_key,
              matrix,
              w=8,
              h=8,
              paint_type=2,
              compress=False):
     Stream.__init__(self, compress=compress)
     self.paint_type = paint_type
     self.w, self.h = w, h
     self.matrix = (matrix.m11(), matrix.m12(), matrix.m21(), matrix.m22(),
                    matrix.dx(), matrix.dy())
     self.resources = Dictionary()
     self.cache_key = (self.__class__.__name__, cache_key, self.matrix)
Пример #4
0
 def __init__(self, pixmap, matrix, pdf, clone=None):
     if clone is None:
         image = pixmap.toImage()
         cache_key = pixmap.cacheKey()
         imgref = pdf.add_image(image, cache_key)
         paint_type = (2 if image.format() in {
             QImage.Format_MonoLSB, QImage.Format_Mono
         } else 1)
         super(TexturePattern, self).__init__(cache_key,
                                              matrix,
                                              w=image.width(),
                                              h=image.height(),
                                              paint_type=paint_type)
         m = (self.w, 0, 0, -self.h, 0, self.h)
         self.resources['XObject'] = Dictionary({'Texture': imgref})
         self.write_line('%s cm /Texture Do' % (' '.join(map(fmtnum, m))))
     else:
         super(TexturePattern, self).__init__(clone.cache_key[1],
                                              matrix,
                                              w=clone.w,
                                              h=clone.h,
                                              paint_type=clone.paint_type)
         self.resources['XObject'] = Dictionary(clone.resources['XObject'])
         self.write(clone.getvalue())
Пример #5
0
 def end(self):
     if self.current_page.getvalue():
         self.end_page()
     self.font_manager.embed_fonts(self.debug)
     inforef = self.objects.add(self.info)
     self.links.add_links()
     self.objects.pdf_serialize(self.stream)
     self.write_line()
     startxref = self.objects.write_xref(self.stream)
     file_id = String(as_unicode(self.stream.hashobj.hexdigest()))
     self.write_line('trailer')
     trailer = Dictionary({'Root':self.catalog, 'Size':len(self.objects)+1,
                           'ID':Array([file_id, file_id]), 'Info':inforef})
     serialize(trailer, self.stream)
     self.write_line('startxref')
     self.write_line('%d'%startxref)
     self.stream.write('%%EOF')
Пример #6
0
    def __init__(self, metrics, num, objects, compress):
        self.metrics, self.compress = metrics, compress
        self.is_otf = self.metrics.is_otf
        self.subset_tag = bytes(
            re.sub('.', lambda m: chr(int(m.group()) + ord('A')),
                   oct(num))).rjust(6, b'A').decode('ascii')
        self.font_stream = FontStream(metrics.is_otf, compress=compress)
        self.font_descriptor = Dictionary({
            'Type':
            Name('FontDescriptor'),
            'FontName':
            Name('%s+%s' % (self.subset_tag, metrics.postscript_name)),
            'Flags':
            0b100,  # Symbolic font
            'FontBBox':
            Array(metrics.pdf_bbox),
            'ItalicAngle':
            metrics.post.italic_angle,
            'Ascent':
            metrics.pdf_ascent,
            'Descent':
            metrics.pdf_descent,
            'CapHeight':
            metrics.pdf_capheight,
            'AvgWidth':
            metrics.pdf_avg_width,
            'StemV':
            metrics.pdf_stemv,
        })
        self.descendant_font = Dictionary({
            'Type':
            Name('Font'),
            'Subtype':
            Name('CIDFontType' + ('0' if metrics.is_otf else '2')),
            'BaseFont':
            self.font_descriptor['FontName'],
            'FontDescriptor':
            objects.add(self.font_descriptor),
            'CIDSystemInfo':
            Dictionary({
                'Registry': String('Adobe'),
                'Ordering': String('Identity'),
                'Supplement': 0,
            }),
        })
        if not self.is_otf:
            self.descendant_font['CIDToGIDMap'] = Name('Identity')

        self.font_dict = Dictionary({
            'Type':
            Name('Font'),
            'Subtype':
            Name('Type0'),
            'Encoding':
            Name('Identity-H'),
            'BaseFont':
            self.descendant_font['BaseFont'],
            'DescendantFonts':
            Array([objects.add(self.descendant_font)]),
        })

        self.used_glyphs = set()
Пример #7
0
 def set_fill_opacity(self, opacity):
     opacity = float(opacity)
     if opacity not in self.fill_opacities:
         op = Dictionary({'Type': Name('ExtGState'), 'ca': opacity})
         self.fill_opacities[opacity] = self.objects.add(op)
     self.current_page.set_opacity(self.fill_opacities[opacity])
Пример #8
0
 def set_stroke_opacity(self, opacity):
     if opacity not in self.stroke_opacities:
         op = Dictionary({'Type': Name('ExtGState'), 'CA': opacity})
         self.stroke_opacities[opacity] = self.objects.add(op)
     self.current_page.set_opacity(self.stroke_opacities[opacity])
Пример #9
0
 def add_outline(self, toc):
     parent = Dictionary({'Type': Name('Outlines')})
     parentref = self.pdf.objects.add(parent)
     self.process_children(toc, parentref, parent_is_root=True)
     self.pdf.catalog.obj['Outlines'] = parentref
Пример #10
0
    def __init__(self, brush, matrix, pdf, pixel_page_width,
                 pixel_page_height):
        self.matrix = (matrix.m11(), matrix.m12(), matrix.m21(), matrix.m22(),
                       matrix.dx(), matrix.dy())
        gradient = sip.cast(brush.gradient(), QLinearGradient)

        start, stop, stops = self.spread_gradient(gradient, pixel_page_width,
                                                  pixel_page_height, matrix)

        # TODO: Handle colors with different opacities
        self.const_opacity = stops[0].color[-1]

        funcs = Array()
        bounds = Array()
        encode = Array()

        for i, current_stop in enumerate(stops):
            if i < len(stops) - 1:
                next_stop = stops[i + 1]
                func = Dictionary({
                    'FunctionType': 2,
                    'Domain': Array([0, 1]),
                    'C0': Array(current_stop.color[:3]),
                    'C1': Array(next_stop.color[:3]),
                    'N': 1,
                })
                funcs.append(func)
                encode.extend((0, 1))
                if i + 1 < len(stops) - 1:
                    bounds.append(next_stop.t)

        func = Dictionary({
            'FunctionType': 3,
            'Domain': Array([stops[0].t, stops[-1].t]),
            'Functions': funcs,
            'Bounds': bounds,
            'Encode': encode,
        })

        shader = Dictionary({
            'ShadingType':
            2,
            'ColorSpace':
            Name('DeviceRGB'),
            'AntiAlias':
            True,
            'Coords':
            Array([start.x(), start.y(),
                   stop.x(), stop.y()]),
            'Function':
            func,
            'Extend':
            Array([True, True]),
        })

        Dictionary.__init__(
            self, {
                'Type': Name('Pattern'),
                'PatternType': 2,
                'Shading': shader,
                'Matrix': Array(self.matrix),
            })

        self.cache_key = (self.__class__.__name__, self.matrix,
                          tuple(shader['Coords']), stops)