Exemplo n.º 1
0
    def do_display(self, args):
        """Display an image with ImageMagick.
        Usage:
        \tdisplay <filename>"""
        args = args.strip().lower()
        matched_files = self.pc.match_files(args)

        if len(matched_files) == 1:

            typ = self.pc.classify_file(args).split('/')[0]

            if typ == 'image':
                fd, temp_name = utils.make_temp_file()
                self.pc.cp(args, temp_name)
                os.system('display %s' % temp_name)
                os.remove(temp_name)

            else:
                print "File is not an image."

        elif len(matched_files) == 0:
            print "File not found."

        else:
            print "Only one file at a time may be specified for display."
Exemplo n.º 2
0
    def do_display(self, args):
        """Display an image with ImageMagick.
        Usage:
        \tdisplay <filename>"""
        args = args.strip().lower()
        matched_files = self.pc.match_files(args)

        if len(matched_files) == 1:

            typ = self.pc.classify_file(args).split('/')[0]

            if typ == 'image':
                fd, temp_name = utils.make_temp_file()
                self.pc.cp(args, temp_name)
                os.system('display %s' % temp_name)
                os.remove(temp_name)

            else:
                print("File is not an image.")

        elif len(matched_files) == 0:
            print("File not found.")

        else:
            print("Only one file at a time may be specified for display.")
Exemplo n.º 3
0
    def __getPluginInformation(self, callback=None):
        status, url, check_sum = ERROR_NO_NETWORK, '', ''

        if self.__plugin_conf_file.startswith('http://'):
            if not utils.check_network_connection():
                log.error("Network connection not detected.")
                return ERROR_NO_NETWORK, '', 0

        local_conf_fp, local_conf = utils.make_temp_file()

        try:
            try:
                if self.__plugin_conf_file.startswith('file://'):
                    status, filename = utils.download_from_network(
                        self.__plugin_conf_file, local_conf, True)
                else:
                    wget = utils.which("wget", True)
                    if wget:
                        status, output = utils.run(
                            "%s --tries=3 --timeout=60 --output-document=%s %s --cache=off"
                            % (wget, local_conf, self.__plugin_conf_file))
                        if status:
                            log.error(
                                "Plugin download failed with error code = %d" %
                                status)
                            return status, url, check_sum
                    else:
                        log.error(
                            "Please install wget package to download the plugin."
                        )
                        return status, url, check_sum
            except IOError as e:
                log.error("I/O Error: %s" % e.strerror)
                return status, url, check_sum

            if not os.path.exists(local_conf):
                log.error("plugin.conf not found.")
                return status, url, check_sum

            try:
                plugin_conf_p = ConfigBase(local_conf)
                url = plugin_conf_p.get(self.__required_version, 'url', '')
                check_sum = plugin_conf_p.get(self.__required_version,
                                              'checksum')
                status = ERROR_SUCCESS
            except (KeyError, configparser.NoSectionError) as e:
                log.error(
                    "Error reading plugin.conf: Missing section [%s]  Error[%s]"
                    % (self.__required_version, e))
                return ERROR_FILE_NOT_FOUND, url, check_sum

            if url == '':
                return ERROR_FILE_NOT_FOUND, url, check_sum

        finally:
            os.close(local_conf_fp)
            os.remove(local_conf)

        return status, url, check_sum
Exemplo n.º 4
0
    def do_thumbnail(self, args):
        """Display an embedded thumbnail image with ImageMagick.
        Note:
        \tOnly works with JPEG/JFIF images with embedded JPEG/TIFF thumbnails
        Usage:
        \tthumbnail <filename>"""
        args = args.strip().lower()
        matched_files = self.pc.match_files(args)

        if len(matched_files) == 1:
            typ, subtyp = self.pc.classify_file(args).split('/')

            if typ == 'image' and subtyp in ('jpeg', 'tiff'):
                exif_info = self.pc.get_exif(args)

                dir_name, file_name = os.path.split(args)
                photo_name, photo_ext = os.path.splitext(args)

                if 'JPEGThumbnail' in exif_info:
                    temp_file_fd, temp_file_name = utils.make_temp_file()
                    open(temp_file_name,
                         'wb').write(exif_info['JPEGThumbnail'])
                    os.system('display %s' % temp_file_name)
                    os.remove(temp_file_name)

                elif 'TIFFThumbnail' in exif_info:
                    temp_file_fd, temp_file_name = utils.make_temp_file()
                    open(temp_file_name,
                         'wb').write(exif_info['TIFFThumbnail'])
                    os.system('display %s' % temp_file_name)
                    os.remove(temp_file_name)

                else:
                    print("No thumbnail found.")

            else:
                print("Incorrect file type for thumbnail.")

        elif len(matched_files) == 0:
            print("File not found.")
        else:
            print(
                "Only one file at a time may be specified for thumbnail display."
            )
Exemplo n.º 5
0
    def do_thumbnail(self, args):
        """Display an embedded thumbnail image with ImageMagick.
        Note:
        \tOnly works with JPEG/JFIF images with embedded JPEG/TIFF thumbnails
        Usage:
        \tthumbnail <filename>"""
        args = args.strip().lower()
        matched_files = self.pc.match_files(args)

        if len(matched_files) == 1:
            typ, subtyp = self.pc.classify_file(args).split('/')

            if typ == 'image' and subtyp in ('jpeg', 'tiff'):
                exif_info = self.pc.get_exif(args)

                dir_name, file_name=os.path.split(args)
                photo_name, photo_ext=os.path.splitext(args)

                if 'JPEGThumbnail' in exif_info:
                    temp_file_fd, temp_file_name = utils.make_temp_file()
                    open(temp_file_name, 'wb').write(exif_info['JPEGThumbnail'])
                    os.system('display %s' % temp_file_name)
                    os.remove(temp_file_name)

                elif 'TIFFThumbnail' in exif_info:
                    temp_file_fd, temp_file_name = utils.make_temp_file()
                    open(temp_file_name, 'wb').write(exif_info['TIFFThumbnail'])
                    os.system('display %s' % temp_file_name)
                    os.remove(temp_file_name)

                else:
                    print "No thumbnail found."

            else:
                print "Incorrect file type for thumbnail."

        elif len(matched_files) == 0:
            print "File not found."
        else:
            print "Only one file at a time may be specified for thumbnail display."
Exemplo n.º 6
0
    def __getPluginInformation(self, callback=None):
        status, url, check_sum = ERROR_NO_NETWORK, '',''

        if self.__plugin_conf_file.startswith('http://'):
            if not utils.check_network_connection():
                log.error("Network connection not detected.")
                return ERROR_NO_NETWORK, '', 0

        local_conf_fp, local_conf = utils.make_temp_file()

        try:
            try:
                if self.__plugin_conf_file.startswith('file://'):
                    status, filename = utils.download_from_network(self.__plugin_conf_file, local_conf, True)
                else:
                    wget = utils.which("wget", True)
                    if wget:
                        status, output = utils.run("%s --timeout=60 --output-document=%s %s --cache=off" %(wget, local_conf, self.__plugin_conf_file))
                        if status:
                            log.error("Plugin download failed with error code = %d" %status)
                            return status, url, check_sum
                    else:
                        log.error("Please install wget package to download the plugin.")
                        return status, url, check_sum
            except IOError as e:
                log.error("I/O Error: %s" % e.strerror)
                return status, url, check_sum

            if not os.path.exists(local_conf):
                log.error("plugin.conf not found.")
                return status, url, check_sum

            try:
                plugin_conf_p = ConfigBase(local_conf)
                url = plugin_conf_p.get(self.__required_version, 'url','')
                check_sum  = plugin_conf_p.get(self.__required_version, 'checksum')
                status = ERROR_SUCCESS
            except (KeyError, configparser.NoSectionError) as e:
                log.error("Error reading plugin.conf: Missing section [%s]  Error[%s]" % (self.__required_version,e))
                return ERROR_FILE_NOT_FOUND, url, check_sum

            if url == '':
                return ERROR_FILE_NOT_FOUND, url, check_sum

        finally:
            os.close(local_conf_fp)
            os.remove(local_conf)

        return status, url, check_sum
Exemplo n.º 7
0
 def __init__(self, device, byte_format='BGRA', update_queue=None, event_queue=None):
     threading.Thread.__init__(self)
     self.scan_active = True
     self.dev = device
     self.update_queue = update_queue
     self.event_queue = event_queue
     self.buffer_fd, self.buffer_path = utils.make_temp_file(prefix='hpscan')
     self.buffer = os.fdopen(self.buffer_fd, "w+b")
     self.format = -1
     self.format_name = ''
     self.last_frame = -1
     self.pixels_per_line = -1
     self.lines = -1
     self.depth = -1
     self.bytes_per_line = -1
     self.pad_bytes = -1
     self.total_read = 0
     self.byte_format = byte_format
Exemplo n.º 8
0
 def __init__(self, device, byte_format='BGRA', update_queue=None, event_queue=None):
     threading.Thread.__init__(self)
     self.scan_active = True
     self.dev = device
     self.update_queue = update_queue
     self.event_queue = event_queue
     self.buffer_fd, self.buffer_path = utils.make_temp_file(prefix='hpscan')
     self.buffer = os.fdopen(self.buffer_fd, "w+b")
     self.format = -1
     self.format_name = ''
     self.last_frame = -1
     self.pixels_per_line = -1
     self.lines = -1
     self.depth = -1
     self.bytes_per_line = -1
     self.pad_bytes = -1
     self.total_read = 0
     self.byte_format = byte_format
     self.total_write = 0
Exemplo n.º 9
0
    def merge_files(self, state):
        log.debug("%s State: Merge multiple files" % ("*"*20))
        log.debug(self.recipient_file_list)
        log.debug("Merging g3 files...")
        self.remove_temp_file = True

        if self.job_total_pages:
            f_fd, self.f = utils.make_temp_file()
            log.debug("Temp file=%s" % self.f)

            data = struct.pack(">8sBIHHBBBII", "hplip_g3", 1L, self.job_total_pages,
                self.job_hort_dpi, self.job_vert_dpi, self.job_page_size,
                self.job_resolution, self.job_encoding,
                0L, 0L)

            os.write(f_fd, data)

            job_page_num = 1

            for fax_file in self.recipient_file_list:
                fax_file_name = fax_file[0]
                log.debug("Processing file: %s..." % fax_file_name)

                if self.results[fax_file_name] == ERROR_SUCCESS:
                    fax_file_fd = file(fax_file_name, 'r')
                    header = fax_file_fd.read(FILE_HEADER_SIZE)

                    magic, version, total_pages, hort_dpi, vert_dpi, page_size, \
                        resolution, encoding, reserved1, reserved2 = self.decode_fax_header(header)

                    if magic != 'hplip_g3':
                        log.error("Invalid file header. Bad magic.")
                        state = STATE_ERROR
                        break

                    log.debug("Magic=%s Ver=%d Pages=%d hDPI=%d vDPI=%d Size=%d Res=%d Enc=%d" %
                              (magic, version, total_pages, hort_dpi, vert_dpi, page_size, resolution, encoding))

                    for p in range(total_pages):
                        header = fax_file_fd.read(PAGE_HEADER_SIZE)

                        page_num, ppr, rpp, bytes_to_read, thumbnail_bytes, reserved2 = \
                            self.decode_page_header(header)

                        if page_num == -1:
                            log.error("Page header error")
                            state - STATE_ERROR
                            break

                        header = struct.pack(">IIIIII", job_page_num, ppr, rpp, bytes_to_read, thumbnail_bytes, 0L)
                        os.write(f_fd, header)

                        self.write_queue((STATUS_PROCESSING_FILES, job_page_num, ''))

                        log.debug("Page=%d PPR=%d RPP=%d BPP=%d Thumb=%s" %
                                  (page_num, ppr, rpp, bytes_to_read, thumbnail_bytes))

                        os.write(f_fd, fax_file_fd.read(bytes_to_read))
                        job_page_num += 1

                    fax_file_fd.close()

                    if self.check_for_cancel():
                        state = STATE_ABORTED
                        break

                else:
                    log.error("Skipping file: %s" % fax_file_name)
                    continue

            os.close(f_fd)
            log.debug("Total pages=%d" % self.job_total_pages)

        return state
Exemplo n.º 10
0
            except ValueError, e:
                log.error("Error saving file: %s (PIL)" % e)
                try:
                    os.remove(output)
                except OSError:
                    pass
                sys.exit(1)

            file_saved = True
            dest.remove("file")

        temp_saved = False
        if ('editor' in dest or 'viewer' in dest or 'email' in dest or 'printer' in dest) \
            and not file_saved:

            output_fd, output = utils.make_temp_file(suffix='.png')
            try:
                im.save(output)
            except IOError, e:
                log.error("Error saving temporary file: %s" % e)

                try:
                    os.remove(output)
                except OSError:
                    pass

                sys.exit(1)

            os.close(output_fd)
            temp_saved = True
Exemplo n.º 11
0
    def merge_files(self, state):
        log.debug("%s State: Merge multiple files" % ("*"*20))
        log.debug(self.recipient_file_list)
        log.debug("Merging g3 files...")
        self.remove_temp_file = True

        if self.job_total_pages:
            f_fd, self.f = utils.make_temp_file()
            log.debug("Temp file=%s" % self.f)

            data = struct.pack(">8sBIHHBBBII", b"hplip_g3", to_long(1), self.job_total_pages,
                self.job_hort_dpi, self.job_vert_dpi, self.job_page_size,
                self.job_resolution, self.job_encoding,
                to_long(0), to_long(0))

            os.write(f_fd, data)

            job_page_num = 1

            for fax_file in self.recipient_file_list:
                fax_file_name = fax_file[0]
                log.debug("Processing file: %s..." % fax_file_name)

                if self.results[fax_file_name] == ERROR_SUCCESS:
                    fax_file_fd = open(fax_file_name, 'rb')
                    header = fax_file_fd.read(FILE_HEADER_SIZE)

                    magic, version, total_pages, hort_dpi, vert_dpi, page_size, \
                        resolution, encoding, reserved1, reserved2 = self.decode_fax_header(header)

                    if magic != b'hplip_g3':
                        log.error("Invalid file header. Bad magic.")
                        state = STATE_ERROR
                        break

                    log.debug("Magic=%s Ver=%d Pages=%d hDPI=%d vDPI=%d Size=%d Res=%d Enc=%d" %
                              (magic, version, total_pages, hort_dpi, vert_dpi, page_size, resolution, encoding))

                    for p in range(total_pages):
                        header = fax_file_fd.read(PAGE_HEADER_SIZE)

                        page_num, ppr, rpp, bytes_to_read, thumbnail_bytes, reserved2 = \
                            self.decode_page_header(header)

                        if page_num == -1:
                            log.error("Page header error")
                            state - STATE_ERROR
                            break

                        header = struct.pack(">IIIIII", job_page_num, ppr, rpp, bytes_to_read, thumbnail_bytes, to_long(0))
                        os.write(f_fd, header)

                        self.write_queue((STATUS_PROCESSING_FILES, job_page_num, ''))

                        log.debug("Page=%d PPR=%d RPP=%d BPP=%d Thumb=%s" %
                                  (page_num, ppr, rpp, bytes_to_read, thumbnail_bytes))

                        os.write(f_fd, fax_file_fd.read(bytes_to_read))
                        job_page_num += 1

                    fax_file_fd.close()

                    if self.check_for_cancel():
                        state = STATE_ABORTED
                        break

                else:
                    log.error("Skipping file: %s" % fax_file_name)
                    continue

            os.close(f_fd)
            log.debug("Total pages=%d" % self.job_total_pages)

        return state
Exemplo n.º 12
0
            except ValueError, e:
                log.error("Error saving file: %s (PIL)" % e)
                try:
                    os.remove(output)
                except OSError:
                    pass
                sys.exit(1)

            file_saved = True
            dest.remove("file")

        temp_saved = False
        if ('editor' in dest or 'viewer' in dest or 'email' in dest or 'printer' in dest) \
            and not file_saved:

            output_fd, output = utils.make_temp_file(suffix='.png')
            try:
                im.save(output)
            except IOError, e:
                log.error("Error saving temporary file: %s" % e)

                try:
                    os.remove(output)
                except OSError:
                    pass

                sys.exit(1)

            os.close(output_fd)
            temp_saved = True
Exemplo n.º 13
0
def createStandardCoverPage(page_size=PAGE_SIZE_LETTER,
                            total_pages=1,
                            recipient_name='',
                            recipient_phone='',
                            recipient_fax='',
                            sender_name='',
                            sender_phone='',
                            sender_fax='',
                            sender_email='',
                            regarding='',
                            message='',
                            preserve_formatting=False,
                            output=None):

    s = getSampleStyleSheet()

    story = []

    #print prop.locale
    #TTFSearchPath.append('/usr/share/fonts/truetype/arphic')
    #pdfmetrics.registerFont(TTFont('UMing', 'uming.ttf'))

    ps = ParagraphStyle(
        name="title",
        parent=None,
        fontName='helvetica-bold',
        #fontName='STSong-Light',
        #fontName = 'UMing',
        fontSize=72,
    )

    story.append(Paragraph("FAX", ps))

    story.append(Spacer(1, inch))

    ps = ParagraphStyle(
        name='normal',
        fontName='Times-Roman',
        #fontName='STSong-Light',
        #fontName='UMing',
        fontSize=12)

    recipient_name_label = Paragraph("To:", ps)
    recipient_name_text = Paragraph(escape(recipient_name[:64]), ps)

    recipient_fax_label = Paragraph("Fax:", ps)
    recipient_fax_text = Paragraph(escape(recipient_fax[:64]), ps)

    recipient_phone_label = Paragraph("Phone:", ps)
    recipient_phone_text = Paragraph(escape(recipient_phone[:64]), ps)

    sender_name_label = Paragraph("From:", ps)
    sender_name_text = Paragraph(escape(sender_name[:64]), ps)

    sender_phone_label = Paragraph("Phone:", ps)
    sender_phone_text = Paragraph(escape(sender_phone[:64]), ps)

    sender_email_label = Paragraph("Email:", ps)
    sender_email_text = Paragraph(escape(sender_email[:64]), ps)

    regarding_label = Paragraph("Regarding:", ps)
    regarding_text = Paragraph(escape(regarding[:128]), ps)

    date_time_label = Paragraph("Date:", ps)
    date_time_text = Paragraph(
        strftime("%a, %d %b %Y %H:%M:%S (%Z)", localtime()), ps)

    total_pages_label = Paragraph("Total Pages:", ps)
    total_pages_text = Paragraph("%d" % total_pages, ps)

    data = [[
        recipient_name_label, recipient_name_text, sender_name_label,
        sender_name_text
    ],
            [
                recipient_fax_label, recipient_fax_text, sender_phone_label,
                sender_phone_text
            ],
            [
                date_time_label, date_time_text, sender_email_label,
                sender_email_text
            ],
            [
                regarding_label, regarding_text, total_pages_label,
                total_pages_text
            ]]

    LIST_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
        #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
        #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
    ])

    story.append(HRFlowable(width='100%', color='black'))

    story.append(Table(data, style=LIST_STYLE))

    if message:
        MSG_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
            #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
            #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
            ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (-2, 1), (-1, -1)),
        ])

        story.append(HRFlowable(width='100%', color='black'))
        story.append(Spacer(1, 0.5 * inch))

        if preserve_formatting:
            message = '\n'.join(message[:2048].splitlines()[:32])

            data = [
                [Paragraph("Comments/Notes:", ps), ''],
                [Preformatted(escape(message), ps), ''],
            ]
        else:
            data = [
                [Paragraph("Comments/Notes:", ps), ''],
                [Paragraph(escape(message[:2048]), ps), ''],
            ]

        story.append(HRFlowable(width='100%', color='black'))
        story.append(Table(data, style=MSG_STYLE))
        story.append(HRFlowable(width='100%', color='black'))

    if page_size == PAGE_SIZE_LETTER:
        pgsz = letter
    elif page_size == PAGE_SIZE_LEGAL:
        pgsz = legal
    else:
        pgsz = A4

    if output is None:
        f_fd, f = utils.make_temp_file()
    else:
        f = output

    doc = SimpleDocTemplate(f, pagesize=pgsz)
    doc.build(story)

    return f
Exemplo n.º 14
0
def createUrgentCoverPage(page_size=PAGE_SIZE_LETTER,
                          total_pages=1,
                          recipient_name='',
                          recipient_phone='',
                          recipient_fax='',
                          sender_name='',
                          sender_phone='',
                          sender_fax='',
                          sender_email='',
                          regarding='',
                          message='',
                          preserve_formatting=False,
                          output=None):

    s = getSampleStyleSheet()

    story = []
    i = Image(os.path.join(prop.image_dir, 'other', 'urgent_title.png'),
              width=424,
              height=92)
    i.hAlign = 'LEFT'
    story.append(i)
    story.append(Spacer(1, inch))
    story.append(HRFlowable(width='100%', color='black'))

    ps = ParagraphStyle(
        name='normal',
        fontName='Times-Roman',
        #fontName='STSong-Light',
        #fontName='UMing',
        fontSize=12)

    recipient_name_label = Paragraph("To:", ps)
    recipient_name_text = Paragraph(escape(recipient_name[:64]), ps)

    recipient_fax_label = Paragraph("Fax:", ps)
    recipient_fax_text = Paragraph(escape(recipient_fax[:64]), ps)

    recipient_phone_label = Paragraph("Phone:", ps)
    recipient_phone_text = Paragraph(escape(recipient_phone[:64]), ps)

    sender_name_label = Paragraph("From:", ps)
    sender_name_text = Paragraph(escape(sender_name[:64]), ps)

    sender_phone_label = Paragraph("Phone:", ps)
    sender_phone_text = Paragraph(escape(sender_phone[:64]), ps)

    sender_email_label = Paragraph("Email:", ps)
    sender_email_text = Paragraph(escape(sender_email[:64]), ps)

    regarding_label = Paragraph("Regarding:", ps)
    regarding_text = Paragraph(escape(regarding[:128]), ps)

    date_time_label = Paragraph("Date:", ps)
    date_time_text = Paragraph(
        strftime("%a, %d %b %Y %H:%M:%S (%Z)", localtime()), ps)

    total_pages_label = Paragraph("Total Pages:", ps)
    total_pages_text = Paragraph("%d" % total_pages, ps)

    data = [
        [recipient_name_label, recipient_name_text],
        [recipient_fax_label, recipient_fax_text],
        ['', ''],
        [sender_name_label, sender_name_text],
        [sender_phone_label, sender_phone_text],
        [sender_email_label, sender_email_text],
        ['', ''],
        [date_time_label, date_time_text],
        [total_pages_label, total_pages_text],
        [regarding_label, regarding_text],
    ]

    LIST_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
        #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
        #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
    ])

    story.append(Table(data, style=LIST_STYLE))
    story.append(HRFlowable(width='100%', color='black'))

    if message:
        MSG_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
            #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
            #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
            ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            #('SPAN', (-2, 1), (-1, -1)),
        ])

        #story.append(HRFlowable(width='100%', color='black'))
        story.append(Spacer(1, 0.5 * inch))

        #        if preserve_formatting:
        #            message = '\n'.join(message[:2048].splitlines()[:32])
        #
        #            data = [#[Paragraph("Comments/Notes:", ps), ''],
        #                    [Preformatted(escape(message), ps)],]
        #        else:
        #            data = [#[Paragraph("Comments/Notes:", ps), ''],
        #                    [Paragraph(escape(message[:2048]), ps), ''],]
        #
        #        #story.append(HRFlowable(width='100%', color='black'))
        #        #story.append(Table(data, style=MSG_STYLE))

        if preserve_formatting:
            message = '\n'.join(message[:2048].splitlines()[:32])
            story.append(Preformatted(escape(message), ps))
        else:
            story.append(Paragraph(escape(message), ps))

    if page_size == PAGE_SIZE_LETTER:
        pgsz = letter
    elif page_size == PAGE_SIZE_LEGAL:
        pgsz = legal
    else:
        pgsz = A4

    if output is None:
        f_fd, f = utils.make_temp_file()
    else:
        f = output

    doc = SimpleDocTemplate(f, pagesize=pgsz)
    doc.build(story)

    return f
Exemplo n.º 15
0
def createStandardCoverPage(page_size=PAGE_SIZE_LETTER,
                            total_pages=1,
                            recipient_name='',
                            recipient_phone='',
                            recipient_fax='',
                            sender_name='',
                            sender_phone='',
                            sender_fax='',
                            sender_email='',
                            regarding='',
                            message='',
                            preserve_formatting=False,
                            output=None):

    s = getSampleStyleSheet()

    story = []

    #print prop.locale
    #TTFSearchPath.append('/usr/share/fonts/truetype/arphic')
    #pdfmetrics.registerFont(TTFont('UMing', 'uming.ttf'))

    ps = ParagraphStyle(name="title",
                        parent=None,
                        fontName='helvetica-bold',
                        #fontName='STSong-Light',
                        #fontName = 'UMing',
                        fontSize=72,
                        )

    story.append(Paragraph("FAX", ps))

    story.append(Spacer(1, inch))

    ps = ParagraphStyle(name='normal',
                        fontName='Times-Roman',
                        #fontName='STSong-Light',
                        #fontName='UMing',
                        fontSize=12)

    recipient_name_label = Paragraph("To:", ps)
    recipient_name_text = Paragraph(escape(recipient_name[:64]), ps)

    recipient_fax_label = Paragraph("Fax:", ps)
    recipient_fax_text = Paragraph(escape(recipient_fax[:64]), ps)

    recipient_phone_label = Paragraph("Phone:", ps)
    recipient_phone_text = Paragraph(escape(recipient_phone[:64]), ps)

    sender_name_label = Paragraph("From:", ps)
    sender_name_text = Paragraph(escape(sender_name[:64]), ps)

    sender_phone_label = Paragraph("Phone:", ps)
    sender_phone_text = Paragraph(escape(sender_phone[:64]), ps)

    sender_email_label = Paragraph("Email:", ps)
    sender_email_text = Paragraph(escape(sender_email[:64]), ps)

    regarding_label = Paragraph("Regarding:", ps)
    regarding_text = Paragraph(escape(regarding[:128]), ps)

    date_time_label = Paragraph("Date:", ps)
    date_time_text = Paragraph(strftime("%a, %d %b %Y %H:%M:%S (%Z)", localtime()), ps)

    total_pages_label = Paragraph("Total Pages:", ps)
    total_pages_text = Paragraph("%d" % total_pages, ps)

    data = [[recipient_name_label, recipient_name_text, sender_name_label, sender_name_text],
            [recipient_fax_label, recipient_fax_text, sender_phone_label, sender_phone_text],
            [date_time_label, date_time_text, sender_email_label, sender_email_text],
            [regarding_label, regarding_text, total_pages_label, total_pages_text]]

    LIST_STYLE = TableStyle([#('LINEABOVE', (0,0), (-1,0), 2, colors.black),
                             #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
                             #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
                             ('ALIGN', (1,1), (-1,-1), 'RIGHT'),
                             ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                            ])

    story.append(HRFlowable(width='100%', color='black'))

    story.append(Table(data, style=LIST_STYLE))

    if message:
        MSG_STYLE = TableStyle([#('LINEABOVE', (0,0), (-1,0), 2, colors.black),
                                 #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
                                 #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
                                 ('ALIGN', (1,1), (-1,-1), 'RIGHT'),
                                 ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                 ('SPAN', (-2, 1), (-1, -1)),
                                ])

        story.append(HRFlowable(width='100%', color='black'))
        story.append(Spacer(1, 0.5*inch))

        if preserve_formatting:
            message = '\n'.join(message[:2048].splitlines()[:32])

            data = [[Paragraph("Comments/Notes:", ps), ''],
                    [Preformatted(escape(message), ps), ''],]
        else:
            data = [[Paragraph("Comments/Notes:", ps), ''],
                    [Paragraph(escape(message[:2048]), ps), ''],]

        story.append(HRFlowable(width='100%', color='black'))
        story.append(Table(data, style=MSG_STYLE))
        story.append(HRFlowable(width='100%', color='black'))

    if page_size == PAGE_SIZE_LETTER:
        pgsz = letter
    elif page_size == PAGE_SIZE_LEGAL:
        pgsz = legal
    else:
        pgsz = A4

    if output is None:
        f_fd, f = utils.make_temp_file()
    else:
        f = output

    doc = SimpleDocTemplate(f, pagesize=pgsz)
    doc.build(story)

    return f
Exemplo n.º 16
0
def createUrgentCoverPage(page_size=PAGE_SIZE_LETTER,
                            total_pages=1,
                            recipient_name='',
                            recipient_phone='',
                            recipient_fax='',
                            sender_name='',
                            sender_phone='',
                            sender_fax='',
                            sender_email='',
                            regarding='',
                            message='',
                            preserve_formatting=False,
                            output=None):

    s = getSampleStyleSheet()

    story = []
    i = Image(os.path.join(prop.image_dir, 'other', 'urgent_title.png'), width=424, height=92)
    i.hAlign = 'LEFT'
    story.append(i)
    story.append(Spacer(1, inch))
    story.append(HRFlowable(width='100%', color='black'))

    ps = ParagraphStyle(name='normal',
                        fontName='Times-Roman',
                        #fontName='STSong-Light',
                        #fontName='UMing',
                        fontSize=12)

    recipient_name_label = Paragraph("To:", ps)
    recipient_name_text = Paragraph(escape(recipient_name[:64]), ps)

    recipient_fax_label = Paragraph("Fax:", ps)
    recipient_fax_text = Paragraph(escape(recipient_fax[:64]), ps)

    recipient_phone_label = Paragraph("Phone:", ps)
    recipient_phone_text = Paragraph(escape(recipient_phone[:64]), ps)

    sender_name_label = Paragraph("From:", ps)
    sender_name_text = Paragraph(escape(sender_name[:64]), ps)

    sender_phone_label = Paragraph("Phone:", ps)
    sender_phone_text = Paragraph(escape(sender_phone[:64]), ps)

    sender_email_label = Paragraph("Email:", ps)
    sender_email_text = Paragraph(escape(sender_email[:64]), ps)

    regarding_label = Paragraph("Regarding:", ps)
    regarding_text = Paragraph(escape(regarding[:128]), ps)

    date_time_label = Paragraph("Date:", ps)
    date_time_text = Paragraph(strftime("%a, %d %b %Y %H:%M:%S (%Z)", localtime()), ps)

    total_pages_label = Paragraph("Total Pages:", ps)
    total_pages_text = Paragraph("%d" % total_pages, ps)

    data = [[recipient_name_label, recipient_name_text],
            [recipient_fax_label, recipient_fax_text],
            ['', ''],
            [sender_name_label, sender_name_text],
            [sender_phone_label, sender_phone_text],
            [sender_email_label, sender_email_text],
            ['', ''],
            [date_time_label, date_time_text],
            [total_pages_label, total_pages_text],
            [regarding_label, regarding_text],]

    LIST_STYLE = TableStyle([#('LINEABOVE', (0,0), (-1,0), 2, colors.black),
                             #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
                             #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
                             ('ALIGN', (1,1), (-1,-1), 'RIGHT'),
                             ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                            ])


    story.append(Table(data, style=LIST_STYLE))
    story.append(HRFlowable(width='100%', color='black'))

    if message:
        MSG_STYLE = TableStyle([#('LINEABOVE', (0,0), (-1,0), 2, colors.black),
                                 #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
                                 #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
                                 ('ALIGN', (1,1), (-1,-1), 'RIGHT'),
                                 ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                 #('SPAN', (-2, 1), (-1, -1)),
                                ])

        #story.append(HRFlowable(width='100%', color='black'))
        story.append(Spacer(1, 0.5*inch))

#        if preserve_formatting:
#            message = '\n'.join(message[:2048].splitlines()[:32])
#
#            data = [#[Paragraph("Comments/Notes:", ps), ''],
#                    [Preformatted(escape(message), ps)],]
#        else:
#            data = [#[Paragraph("Comments/Notes:", ps), ''],
#                    [Paragraph(escape(message[:2048]), ps), ''],]
#
#        #story.append(HRFlowable(width='100%', color='black'))
#        #story.append(Table(data, style=MSG_STYLE))

        if preserve_formatting:
            message = '\n'.join(message[:2048].splitlines()[:32])
            story.append(Preformatted(escape(message), ps))
        else:
            story.append(Paragraph(escape(message), ps))


    if page_size == PAGE_SIZE_LETTER:
        pgsz = letter
    elif page_size == PAGE_SIZE_LEGAL:
        pgsz = legal
    else:
        pgsz = A4

    if output is None:
        f_fd, f = utils.make_temp_file()
    else:
        f = output

    doc = SimpleDocTemplate(f, pagesize=pgsz)
    doc.build(story)

    return f