示例#1
0
def CreatePDF(copy_count):
    file_name = "question.txt"
    nameval_file = "NameVal.txt"
    header_data = ReadNameValFile(nameval_file)
    q_list = ReadQFile(file_name)
    for i in range(0, copy_count):
        pdf = FPDF()
        count = 1
        pdf.add_page()
        pdf.set_title("Ranbir Roshan")  #no effect
        pdf.set_subject("Ranbir Subject")  #no effect
        pdf.set_author("Author Ranbir")
        pdf.set_auto_page_break('auto')
        pdf.set_creator("Ranbir Creator")
        PrintHeader(pdf, header_data)
        pdf.set_font("Arial", size=header_data.NormalLineFontSize)
        if (header_data.RandomQuestionOrder == "TRUE"):
            random.shuffle(q_list)
        if (header_data.PickQuestionCount < len(q_list)
                and header_data.PickQuestionCount > 0):
            list = random.sample(q_list, k=header_data.PickQuestionCount)
        else:
            list = q_list
        for question in q_list:
            #PrintQuestion(question, pdf, count, header_data)
            question.Print(pdf, header_data, "", count)
            count = count + 1
        name = "sample_" + str(i) + ".pdf"
        pdf.output(name)
示例#2
0
def images_to_pdf(pdfName="newPdf.pdf", fitSize=True):
    '''list files(images) from current dir and save it as pdf'''
    files = [
        file for file in os.listdir()
        if file.endswith(('.png', '.jpg', '.jpeg', '.jp2'))
    ]
    files.sort()

    #make pdf (think about 2 images on 1 page vs 1 img on 1 page)
    pdf = FPDF(orientation="P", unit="mm",
               format="A4")  #orientation -> L/P, A4 -> 210x297
    for key, image in enumerate(files):
        pdf.add_page()
        # pdf.line(5, 287, 205, 287)
        cover = Image.open(image)
        if fitSize:
            '''auto resize and position setting'''
            width, height = cover.size
            if width / height > 210 / 297:
                maxFactor = math.trunc((210 / width) * 10000) / 10000
            elif width / height < 210 / 297:
                maxFactor = math.trunc((297 / height) * 10000) / 10000
            else:
                maxFactor = math.trunc((297 / height) * 10000) / 10000
            # print(maxFactor)
            xMove = math.trunc((210 - width * maxFactor) / 2)
            yMove = math.trunc((297 - height * maxFactor) / 2)
            pdf.image(image, xMove, yMove, width * maxFactor,
                      height * maxFactor)
        else:
            pdf.image(image, 0, 0, 0, 0)
    pdf.set_display_mode(zoom="fullpage", layout="two")
    pdf.set_creator("streanger")
    pdf.output(pdfName, "F")
    return True
示例#3
0
def imgs_to_pdf():
    index = 0
    pdf = FPDF()
    pdf.set_creator("刘小绪同学")
    pdf.set_author("刘小绪同学")
    pdf.add_page()
    for img in os.listdir(PATH):
        print(index)
        index += 1
        pdf.image(PATH + img, w=190, h=280)
    pdf.output("articles.pdf")
def main():
    """
    Entry-point for the function.
    """
    pdf = FPDF()
    pdf.set_display_mode('fullwidth')
    pdf.set_creator('Cavin Dsouza')
    pdf.set_author('bizarro')
    scrape(pdf)
    pdf.output("bizarro.pdf", "F")
    print("PDF created successfully.")
示例#5
0
def convert_images_to_pdf(imagelist, pdftitle, pdfcreator):
    """Convert all images to PDF. 
    imagelist is the list with all image filenames.
    """
    pdf = FPDF()
    for image in imagelist:
        pdf.add_page()
        pdf.image(image, w=170)
        pdf.set_title(pdftitle)
        pdf.set_creator(pdfcreator)
    at_filedate = datetime.now(
        pytz.timezone('Asia/Kolkata')).strftime("%Y%m%d")
    suffix = 'pdf'
    at_filename = os.path.join(
        os.path.normpath(os.getcwd() + os.sep + os.pardir), 'pdf',
        at_filedate + "_assamtribune" + os.extsep + suffix)
    pdf.output(at_filename, "F")
示例#6
0
from fpdf import FPDF

pdf = FPDF(orientation='P', unit='mm', format='A4')
pdf.add_page()

# TEXTO
pdf.set_font('Arial', '', 15)

pdf.cell(w=0, h=15, txt='Hola mundo', border=1, ln=1, align='C', fill=0)

pdf.cell(w=0, h=15, txt='Hola mundo', border=1, ln=2, align='C', fill=0)

# METADATOS

# titulo
pdf.set_title(title='Hoja metadatos')

# autor
pdf.set_author(author='ALEX7320')

# creador
pdf.set_creator('Kodexam')

# palabras clave
pdf.set_keywords(keywords='Hoja, PDF, Prueba')

# asunto
pdf.set_subject(subject='Prueba de metadatos en PDF')

pdf.output('hoja.pdf')
示例#7
0
def create_qc_pdf(**kwargs):
    try:
        kwargs['company'] = kwargs.get('company', u'台茂化工儀器原料行')
        kwargs['product'] = kwargs.get('product', u'product name?')
        kwargs['ASE_pn'] = kwargs.get('ASE_pn', u'ASE PN?')
        if not kwargs.get('lot_no'):
            kwargs['make_date'] = date.today()
            kwargs['test_date'] = date.today()
            kwargs['lot_no'] = u'lot number?'
        else:
            year = 2000 + int(kwargs['lot_no'][1:3])
            month = int(kwargs['lot_no'][3:5])
            day = int(kwargs['lot_no'][5:7])
            kwargs['make_date'] = date(year, month, day)
            kwargs['test_date'] = date(year, month, day)
        kwargs['exp_period'] = kwargs.get('exp_period', u'一年')
        kwargs['amount'] = kwargs.get('amount', u'amount?')
        kwargs['tester'] = kwargs.get('tester', u'tester?')
        kwargs['test_params'] = kwargs.get('test_params', [])
    except Exception as e:
        print e
        return

    # Set placement and style of values
    tm_branch = dict(x=30, y=25, w=178-30, h=10, align='C')
    product_name = dict(x=31, y=50, w=104-31, h=15, align='L')
    product_ASE_pn = dict(x=105, y=50, w=104-31, h=15, align='L')

    make_date = dict(x=31, y=65, w=104-31, h=8, align='L')
    test_date = dict(x=31, y=73, w=104-31, h=8, align='L')
    exp_period = dict(x=31, y=81, w=104-31, h=9, align='L')

    lot_no = dict(x=105, y=65, w=104-31, h=8, align='L')
    amount = dict(x=105, y=73, w=104-31, h=8, align='L')
    tester = dict(x=105, y=81, w=104-31, h=9, align='L')


    # Create PDF
    FPDF = myPDF('P','mm','A4')
    FPDF.set_compression(False)
    FPDF.set_creator('TM_2014')
    FPDF.set_title(u'Quality inspection report for lot# {}'.format(kwargs['lot_no']))
    FPDF.set_author(u'Taimau Chemicals')
    FPDF.set_subject(kwargs['lot_no'])
#    FPDF.set_subject(u'{} {}'.format(kwargs['product'], kwargs['lot_no']), isUTF8=True)
    FPDF.alias_nb_pages()
    FPDF.add_page() # Adding a page also creates a page break from last page


    FPDF.add_font(family=u'SimHei', style='', fname=font, uni=True) # Only .ttf and not .ttc

    FPDF.set_font(family=u'SimHei', style='', size=16)
    FPDF.xycell(txt=kwargs['company'], **tm_branch)

    FPDF.set_font(family=u'SimHei', style='B', size=13)
    FPDF.xycell(txt=u'產品: {}'.format(kwargs['product']), **product_name)
    FPDF.xycell(txt=u'料號: {}'.format(kwargs['ASE_pn']), **product_ASE_pn)

    FPDF.xycell(txt=u'製造日期: {}'.format(kwargs['make_date']), **make_date)
    FPDF.xycell(txt=u'檢驗日期: {}'.format(kwargs['test_date']), **test_date)
    FPDF.xycell(txt=u'保存期間: {}'.format(kwargs['exp_period']), **exp_period)

    FPDF.xycell(txt=u'批號: {}'.format(kwargs['lot_no']), **lot_no)
    FPDF.xycell(txt=u'生產數量: {}'.format(kwargs['amount']), **amount)
    FPDF.xycell(txt=u'取樣人員: {}'.format(kwargs['tester']), **tester)

    FPDF.set_left_margin(30)
    FPDF.set_xy(x=30, y=105)
    for (a, b, c) in kwargs['test_params']:
        if a+b+c == u'':
            break
        FPDF.cell(49, 10, txt=a, align='C')
        FPDF.cell(49, 10, txt=b, align='C')
        FPDF.cell(49, 10, txt=c, align='C')
        FPDF.ln()
    FPDF.cell(49)
    FPDF.cell(49, 10, txt=u'以下空白', align='C')




    initialfilename = u'QC_{}_{}'.format(kwargs['product'], kwargs['lot_no'])
    FILE_OPTS = dict(
        title = u'PDF name and location.',
        defaultextension = '.pdf',
        initialdir = os.path.expanduser('~') + '/Desktop/',
        initialfile = initialfilename,
    )
    if settings.load().get(u'pdfpath'):
        FILE_OPTS['initialdir'] = settings.load()[u'pdfpath']

    outfile = os.path.normpath(tkFileDialog.asksaveasfilename(**FILE_OPTS))


    if os.path.exists(outfile):
        os.remove(outfile)
    if outfile and not os.path.exists(outfile):
        FPDF.output(name=outfile)

        try:
            subprocess.call(['start', outfile],
                             shell=True)
            return
        except:
            pass

        try:
            print u'Trying alternate subprocess command.'
            subprocess.call(['start', '/D'] +
                            list(os.path.split(outfile)),
                            shell=True)
            return
        except UnicodeEncodeError:
            pass

        try:
            os.startfile(outfile)
            return
        except:
            pass

        print u'Failed to autoload PDF after creation.'
        return
    else:
        head = u'Cancelled'
        body = u'Canceled PDF creation.'
        tkMessageBox.showinfo(head, body)
示例#8
0
class PdfHandler:
    def __init__(self, orientation='P', unit='pt', format='A4'):
        self.pdf_handler = FPDF(orientation=orientation, unit=unit, format=format)
    
    def _set_margins(self, left, top, right=-1):
        return self.pdf_handler.set_margins(left, top, right=right)

    def _set_title(self, title):
        return self.pdf_handler.set_title(title)

    def _set_subject(self, subject):
        return self.pdf_handler.set_subject(subject)

    def _set_author(self, author):
        return self.pdf_handler.set_author(author)

    def _set_keywords(self, keywords):
        return self.pdf_handler.set_keywords(keywords)

    def _set_creator(self, creator):
        return self.pdf_handler.set_creator(creator)

    def _add_page(self, orientation=''):
        return self.pdf_handler.add_page(orientation=orientation)

    def _set_draw_color(self, r, g=-1, b=-1):
        return self.pdf_handler.set_draw_color(r, g=g, b=b)

    def _set_fill_color(self, r, g=-1, b=-1):
        return self.pdf_handler.set_fill_color(g=g, b=b)

    def _set_text_color(self, r, g=-1, b=-1):
        return self.pdf_handler.set_text_color(r, g=-g, b=b)

    def _get_string_width(self, s):
        return self.pdf_handler.get_string_width(s)

    def _set_line_width(self, width):
        return self.pdf_handler.set_line_width(width)

    def _line(self, x1, y1, x2, y2):
        return self.pdf_handler.line(x1, y1, x2, y2)

    def _dashed_line(self, x1, y1, x2, y2, dash_length=1, space_length=1):
        return self.pdf_handler.dashed_line(x1, y1, x2, y2, dash_length=dash_length, space_length=space_length)

    def _rect(self, x, y, w, h, style=''):
        return self.pdf_handler.rect(x, y, w, h, style=style)

    def _ellipse(self, x, y, w, h, style=''):
        return self.pdf_handler.ellipse(x, y, w, h, style=style)

    def _set_font(self, family, style='', size=0):
        return self.pdf_handler.set_font(family, style=style, size=size)

    def _set_font_size(self, size):
        return self.pdf_handler.set_font_size(size)

    def _text(self, x, y, txt=''):
        return self.pdf_handler.text(x, y, txt=txt)

    def _multi_cell(self, w, h, txt='', border=0, align='J', fill=0, split_only=False):
        return self.pdf_handler.multi_cell(w, h, txt=txt, border=border, align=align, fill=fill, split_only=split_only)

    def _write(self, h, txt='', link=''):
        return self.pdf_handler.write(h, txt=txt, link=link)

    def _image(self, name, x=None, y=None, w=0, h=0, image_type='', link=''):
        return self.pdf_handler.image(name, x=x, y=y, w=w,h=h,type=image_type,link=link)

    def _normalize_text(self, txt):
        return self.pdf_handler.normalize_text(txt)

    def _output(self, name='', dest=''):
        return self.pdf_handler.output(name, dest)
示例#9
0
class PDFExporter():
    """Exports the set of QR codes as a PDF file."""
    def __init__(self, fname, qr_count):
        self.pdf = FPDF()
        self.fname = fname
        self.qr_number = 0
        self.qr_count = qr_count

        self.pdf.set_font('Arial', '', 10)
        self.pdf.set_creator(
            'PyPaperBak - https://github.com/matheusd/pypaperbak')
        self.pdf.set_title('PyPaperBak Document')
        self.pdf.set_margins(1, 1, 1)
        self.pdf.set_auto_page_break(False)

        self.tmpfilenames = dict()

        # TODO: Parametrize this
        self.format = 'A4'
        page_width = 210
        page_height = 297
        bottom_margin = 15  # margin at the bottom of page for the comments
        self.qr_margin = 5
        self.qr_per_row = 3
        self.qr_rows_per_page = 5
        self.qr_per_page = self.qr_per_row * self.qr_rows_per_page
        self.qr_total_pages = self.qr_count / self.qr_per_page + 1

        # to discover the size, calculate the minimum size to fit as
        # many requested QR's per row and page, giving a
        # margin at each end and between the codes
        self.qr_size = min(
            (page_width - self.qr_per_row * self.qr_margin - self.qr_margin) /
            self.qr_per_row,
            (page_height - self.qr_rows_per_page * self.qr_margin -
             self.qr_margin - bottom_margin) / self.qr_rows_per_page)

        self.qr_margin_x = (page_width - self.qr_size * self.qr_per_row) / (
            self.qr_per_row + 1)
        self.qr_margin_y = (page_height - bottom_margin -
                            self.qr_size * self.qr_rows_per_page) / (
                                self.qr_rows_per_page + 1)

        self.page_util_width = (page_width - self.qr_margin_x * 2)

    def add_qr(self, qr):
        if (self.qr_number % self.qr_per_page) == 0:
            self.pdf.add_page()
            self.pdf.set_xy(self.qr_margin_x, -10)
            self.pdf.write(0, 'Made by PyPaperBak',
                           'https://github.com/matheusd/pypaperbak')
            page_nb = self.qr_number / self.qr_per_page + 1
            self.pdf.set_xy(self.qr_margin_x, -10)
            self.pdf.cell(self.page_util_width,
                          0,
                          'Page %d of %d' % (page_nb, self.qr_total_pages),
                          align='R')

        while True:
            with tempfile.NamedTemporaryFile(delete=False,
                                             suffix='.png') as file:
                tmpname = file.name
            # make sure we don't get a repeat tmpname because fpdf will only
            # include one copy of a given filename
            if not tmpname in self.tmpfilenames: break
        self.tmpfilenames[tmpname] = True
        qr.png(tmpname, scale=6)

        idxinpage = self.qr_number % self.qr_per_page
        col = idxinpage % self.qr_per_row
        row = int(idxinpage / self.qr_per_row)
        size = self.qr_size
        margin_x = self.qr_margin_x
        margin_y = self.qr_margin_y

        self.pdf.image(
            tmpname,
            margin_x + col * (size + margin_x),  # X 
            margin_y + row * (size + margin_y),  # Y
            size,  # width    
            size)  # height
        os.unlink(tmpname)

        self.qr_number += 1

    def finish(self, inputhash):
        """Finish exporting the pdf."""
        self.pdf.set_xy(self.qr_margin_x, -15)
        self.pdf.write(0,
                       'Hash of original document: %s' % inputhash.hexdigest())
        self.pdf.output(self.fname)
示例#10
0
    def process(self,
                output_file_name=None,
                dpi=150,
                offset=0,
                fps=10,
                height_mm=50,
                margins=Margin(10, 10, 10, 10),
                paper_format='a4'):

        def draw_raster():
            for ix in range(0, nx + 1):
                xx = x0 + ix * total.width
                pdf.line(xx, y0, xx, y1)
                if offset > 0 and ix != nx:
                    pdf.line(xx + offset, y0, xx + offset, y1)
            for iy in range(0, ny + 1):
                yy = y0 + iy * total.height
                pdf.line(x0, yy, x1, yy)

        height_mm = float(height_mm)
        tmp_files = []
        if self.clip:
            if fps != self.clip.fps:
                if self.verbosity > 0:
                    print 'Transcoding from {} fps to {} fps ...'.format(self.clip.fps, fps)
                self.clip.write_videofile('tmp.mp4', fps=fps, audio=False)
                tmp_files.append('tmp.mp4')
                self.clip = VideoFileClip('tmp.mp4')
                self.fps = self.clip.fps
                self.frame_count = int(self.clip.duration * self.fps)
            clip_size = Size.from_tuple(self.clip.size)
        elif self.frames:
            clip_size = Size.from_tuple(self.im.size)

        paper = self.PAPER_SIZES[paper_format.lower()]
        printable_area = Size(paper.width - margins.left - margins.right,
                              paper.height - margins.top - margins.bottom)
        frame_mm = Size(height_mm / clip_size.height * clip_size.width, height_mm)
        total = Size(offset + frame_mm.width, frame_mm.height)
        frame = Size(int(frame_mm.width / 25.4 * dpi),
                     int(frame_mm.height / 25.4 * dpi))
        nx = int(printable_area.width / total.width)
        ny = int(printable_area.height / total.height)
        if self.verbosity > 0:
            print 'Input:  {} fps, {}x{}, {} frames'\
                '\n        from: {}'\
                .format(
                    self.fps,
                    clip_size.width,
                    clip_size.height,
                    self.frame_count,
                    self.input_file_name
                )
            print 'Output: {}dpi, {}x{}, {:.2f}mm x {:.2f}mm, {}x{} tiles'\
                '\n        to: {}'\
                .format(
                    dpi,
                    frame.width, frame.height,
                    frame_mm.width, frame_mm.height,
                    nx, ny,
                    output_file_name
                )
        pdf = FPDF(unit='mm', format=paper_format.upper(), orientation='L')
        pdf.set_compression(True)
        pdf.set_title('Funny video')
        pdf.set_author('Oliver Lau <*****@*****.**> - Heise Medien GmbH & Co. KG')
        pdf.set_creator('flippy')
        pdf.set_keywords('flip-book, video, animated GIF')
        pdf.set_draw_color(128, 128, 128)
        pdf.set_line_width(0.1)
        pdf.set_font('Helvetica', '', 12)
        pdf.add_page()
        i = 0
        page = 0
        tx, ty = -1, 0
        x0, y0 = margins.left, margins.top
        x1, y1 = x0 + nx * total.width, y0 + ny * total.height

        if self.clip:
            all_frames = self.clip.iter_frames()
        elif self.frames:
            all_frames = AnimatedGif(self.im)
        else:
            all_frames = []
        for f in all_frames:
            ready = float(i + 1) / self.frame_count
            if self.verbosity:
                sys.stdout.write('\rProcessing frames |{:30}| {}%'
                                 .format('X' * int(30 * ready), int(100 * ready)))
                sys.stdout.flush()
            tx += 1
            if type(f) == GifImagePlugin.GifImageFile:
                f.putpalette(self.palette)
                self.last_im.paste(f)
                im = self.last_im.convert('RGBA')
            else:
                im = Image.fromarray(f)
                im.thumbnail(frame.to_tuple())
            if tx == nx:
                tx = 0
                ty += 1
                if ty == ny:
                    ty = 0
                    draw_raster()
                    pdf.add_page()
                    page += 1
            temp_file = 'tmp-{}-{}-{}.jpg'.format(page, tx, ty)
            im.save(temp_file)
            tmp_files.append(temp_file)
            x = x0 + tx * total.width
            y = y0 + ty * total.height
            pdf.image(temp_file,
                      x=x + offset,
                      y=y,
                      w=frame_mm.width,
                      h=frame_mm.height)
            text = Point(x, y + frame_mm.height - 2)
            if offset > 0:
                pdf.rotate(90, text.x, text.y)
                pdf.text(text.x, text.y + 5, '{}'.format(i))
                pdf.rotate(0)
            i += 1

        if y != 0 and x != 0:
            draw_raster()

        if self.verbosity > 0:
            print '\nGenerating PDF ...'
        pdf.output(name=output_file_name)
        if self.verbosity > 0:
            print 'Removing temporary files ...'
        for temp_file in tmp_files:
            os.remove(temp_file)
示例#11
0
    global downloads
    image_location = downloads + x
    img = cv2.imread(image_location)
    i, j, k = img.shape
    if i < j:
        rotated = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
        cv2.imwrite(image_location, rotated)
    pdf.image(image_location, x=0, y=0, w=8.27, h=11.69)


ls = os.listdir(downloads)
pdf = FPDF("P", "in", "A4")
pdf.add_page()
pdf.set_font("Arial", "B", 32)
pdf.set_author("Suphal Bhattarai")
pdf.set_creator("Suphal Bhattarai")
pdf.set_title("Homework")
pdf.set_fill_color(0, 0, 0)
pdf.set_text_color(255, 255, 255)
pdf.rect(0, 0, 8.27, 11.69, "FD")
pdf.set_xy(1.5, 4)
pdf.multi_cell(0, 0.5,
               "Name : Suphal Bhattarai \n Section : D6 \n Group : Biology", 0,
               2, "C")

for x in ls:
    if match(".*.jpg", x):
        pdf.add_page()
        insert_img(x)

results = str(Rofi().text_entry("Whose homeowrk is this?")).upper()
示例#12
0
    def to_pdf(self, **kwargs):
        from fpdf import FPDF
        import random
        paper_format = kwargs.get('paper_format', 'a4')
        paper = self.PAPER_SIZES[string.lower(paper_format)]
        font_scale = kwargs.get('font_scale', 1)
        font_name = kwargs.get('font_name')
        colorize = kwargs.get('colorize', False)
        if font_name is not None and not colorize:
            self.generate_luminosity_mapping(font_name)
        orientation = kwargs.get('orientation')
        if self.im.width > self.im.height:
            orientation = 'l'
        else:
            orientation = 'p'
        if orientation == 'l':
            paper.width, paper.height = paper.height, paper.width

        inner = Size(ceil(paper.width - self.margins.left - self.margins.right),
                     ceil(paper.height - self.margins.top - self.margins.bottom))
        imgpixels = Size(self.im.width, self.im.height)
        scale = min(inner.width, inner.height) / max(imgpixels.width, imgpixels.height)
        offset = Point(self.margins.left + (inner.width - imgpixels.width * scale) / 2,
                       self.margins.bottom + (inner.height - imgpixels.height * scale) / 2)

        pdf = FPDF(unit='mm', format=paper_format.upper(), orientation=orientation.upper())
        pdf.set_compression(True)
        pdf.set_title('ASCII Art')
        pdf.set_author('Oliver Lau <*****@*****.**> - Heise Medien GmbH & Co. KG')
        pdf.set_creator('asciifier')
        pdf.set_keywords('retro computing art fun')
        pdf.add_page()

        if font_name is not None:
            pdf.add_font(font_name, fname=font_name, uni=True)
        else:
            font_name = 'Courier'
        pdf.set_font(font_name, '', mm2pt(scale * font_scale))

        for y in range(0, self.im.height):
            yy = offset.y + scale * y
            for x in range(0, self.im.width):
                c = self.result[x][y]
                if c != ' ':
                    if colorize is True:
                        r, g, b = self.im.getpixel((x, y))
                        pdf.set_text_color(r, g, b)
                        pdf.text(offset.x + x * scale, yy, random.choice(Asciifier.COLOR_CHARS))
                    else:
                        pdf.text(offset.x + x * scale, yy, c)

        crop_area = Margin(offset.y - scale,
                           offset.x + (self.im.width - 1 + font_scale) * scale,
                           offset.y + (self.im.height - 2 + font_scale) * scale,
                           offset.x)

        if kwargs.get('cropmarks', False):
            pdf.set_draw_color(0, 0, 0)
            pdf.set_line_width(pt2mm(0.1))
            for p in [Point(crop_area.left, crop_area.top),
                      Point(crop_area.right, crop_area.top),
                      Point(crop_area.right, crop_area.bottom),
                      Point(crop_area.left, crop_area.bottom)]:
                pdf.line(p.x - 6, p.y, p.x - 2, p.y)
                pdf.line(p.x + 2, p.y, p.x + 6, p.y)
                pdf.line(p.x, p.y - 6, p.x, p.y - 2)
                pdf.line(p.x, p.y + 2, p.x, p.y + 6)

        if kwargs.get('logo'):
            logo_width = 20
            pdf.image(kwargs.get('logo'),
                      x=(crop_area.right - crop_area.left - logo_width / 2) / 2,
                      y=crop_area.bottom + 10,
                      w=logo_width)

        return pdf.output(dest='S')
示例#13
0
    def to_pdf(self, **kwargs):
        from fpdf import FPDF
        import random
        paper_format = kwargs.get('paper_format', 'a4')
        paper = self.PAPER_SIZES[string.lower(paper_format)]
        font_scale = kwargs.get('font_scale', 1)
        font_name = kwargs.get('font_name')
        colorize = kwargs.get('colorize', False)
        if font_name is not None and not colorize:
            self.generate_luminosity_mapping(font_name)
        orientation = kwargs.get('orientation')
        if self.im.width > self.im.height:
            orientation = 'l'
        else:
            orientation = 'p'
        if orientation == 'l':
            paper.width, paper.height = paper.height, paper.width

        inner = Size(
            ceil(paper.width - self.margins.left - self.margins.right),
            ceil(paper.height - self.margins.top - self.margins.bottom))
        imgpixels = Size(self.im.width, self.im.height)
        scale = min(inner.width, inner.height) / max(imgpixels.width,
                                                     imgpixels.height)
        offset = Point(
            self.margins.left + (inner.width - imgpixels.width * scale) / 2,
            self.margins.bottom +
            (inner.height - imgpixels.height * scale) / 2)

        pdf = FPDF(unit='mm',
                   format=paper_format.upper(),
                   orientation=orientation.upper())
        pdf.set_compression(True)
        pdf.set_title('ASCII Art')
        pdf.set_author('Oliver Lau <*****@*****.**> - Heise Medien GmbH & Co. KG')
        pdf.set_creator('asciifier')
        pdf.set_keywords('retro computing art fun')
        pdf.add_page()

        if font_name is not None:
            pdf.add_font(font_name, fname=font_name, uni=True)
        else:
            font_name = 'Courier'
        pdf.set_font(font_name, '', mm2pt(scale * font_scale))

        for y in range(0, self.im.height):
            yy = offset.y + scale * y
            for x in range(0, self.im.width):
                c = self.result[x][y]
                if c != ' ':
                    if colorize is True:
                        r, g, b = self.im.getpixel((x, y))
                        pdf.set_text_color(r, g, b)
                        pdf.text(offset.x + x * scale, yy,
                                 random.choice(Asciifier.COLOR_CHARS))
                    else:
                        pdf.text(offset.x + x * scale, yy, c)

        crop_area = Margin(
            offset.y - scale,
            offset.x + (self.im.width - 1 + font_scale) * scale,
            offset.y + (self.im.height - 2 + font_scale) * scale, offset.x)

        if kwargs.get('cropmarks', False):
            pdf.set_draw_color(0, 0, 0)
            pdf.set_line_width(pt2mm(0.1))
            for p in [
                    Point(crop_area.left, crop_area.top),
                    Point(crop_area.right, crop_area.top),
                    Point(crop_area.right, crop_area.bottom),
                    Point(crop_area.left, crop_area.bottom)
            ]:
                pdf.line(p.x - 6, p.y, p.x - 2, p.y)
                pdf.line(p.x + 2, p.y, p.x + 6, p.y)
                pdf.line(p.x, p.y - 6, p.x, p.y - 2)
                pdf.line(p.x, p.y + 2, p.x, p.y + 6)

        if kwargs.get('logo'):
            logo_width = 20
            pdf.image(kwargs.get('logo'),
                      x=(crop_area.right - crop_area.left - logo_width / 2) /
                      2,
                      y=crop_area.bottom + 10,
                      w=logo_width)

        return pdf.output(dest='S')
示例#14
0
page_width = 210
page_height = 297

page_left_margin = 10
page_right_margin = 10
page_top_margin = 10
page_bottom_margin = 10

page_x_area = page_width - page_left_margin - page_right_margin
page_y_area = page_height - page_top_margin - page_bottom_margin

pdf = FPDF(orientation='P', unit='mm', format='A4')

pdf.set_author("Author Test Terminal")
pdf.set_creator("Creator Test Terminal")
pdf.set_subject("Exam Results")

pdf.add_page(orientation='P', format='A4', same=False)
pdf.set_left_margin(margin=10)
pdf.set_right_margin(margin=10)

pdf.alias_nb_pages()

# Draw border
pdf.line(10, 10, 200, 10)
pdf.line(10, 277, 200, 277)
pdf.line(10, 10, 10, 277)
pdf.line(200, 10, 200, 277)

# Title
示例#15
0
文件: flippy.py 项目: ola-ct/flippy
    def process(
        self,
        output_file_name=None,
        dpi=150,
        offset=0,
        fps=10,
        height_mm=50,
        margins=Margin(10, 10, 10, 10),
        paper_format="a4",
    ):
        def draw_raster():
            for ix in range(0, nx + 1):
                xx = x0 + ix * total.width
                pdf.line(xx, y0, xx, y1)
                if offset > 0 and ix != nx:
                    pdf.line(xx + offset, y0, xx + offset, y1)
            for iy in range(0, ny + 1):
                yy = y0 + iy * total.height
                pdf.line(x0, yy, x1, yy)

        height_mm = float(height_mm)
        tmp_files = []
        if self.clip:
            if fps != self.clip.fps:
                if self.verbosity > 0:
                    print "Transcoding from {} fps to {} fps ...".format(self.clip.fps, fps)
                self.clip.write_videofile("tmp.mp4", fps=fps, audio=False)
                tmp_files.append("tmp.mp4")
                self.clip = VideoFileClip("tmp.mp4")
                self.fps = self.clip.fps
                self.frame_count = int(self.clip.duration * self.fps)
            clip_size = Size.from_tuple(self.clip.size)
        elif self.frames:
            clip_size = Size.from_tuple(self.im.size)

        paper = self.PAPER_SIZES[paper_format.lower()]
        printable_area = Size(paper.width - margins.left - margins.right, paper.height - margins.top - margins.bottom)
        frame_mm = Size(height_mm / clip_size.height * clip_size.width, height_mm)
        total = Size(offset + frame_mm.width, frame_mm.height)
        frame = Size(int(frame_mm.width / 25.4 * dpi), int(frame_mm.height / 25.4 * dpi))
        nx = int(printable_area.width / total.width)
        ny = int(printable_area.height / total.height)
        if self.verbosity > 0:
            print "Input:  {} fps, {}x{}, {} frames" "\n        from: {}".format(
                self.fps, clip_size.width, clip_size.height, self.frame_count, self.input_file_name
            )
            print "Output: {}dpi, {}x{}, {:.2f}mm x {:.2f}mm, {}x{} tiles" "\n        to: {}".format(
                dpi, frame.width, frame.height, frame_mm.width, frame_mm.height, nx, ny, output_file_name
            )
        pdf = FPDF(unit="mm", format=paper_format.upper(), orientation="L")
        pdf.set_compression(True)
        pdf.set_title("Funny video")
        pdf.set_author("Oliver Lau <*****@*****.**> - Heise Medien GmbH & Co. KG")
        pdf.set_creator("flippy")
        pdf.set_keywords("flip-book, video, animated GIF")
        pdf.set_draw_color(128, 128, 128)
        pdf.set_line_width(0.1)
        pdf.set_font("Helvetica", "", 12)
        pdf.add_page()
        i = 0
        page = 0
        tx, ty = -1, 0
        x0, y0 = margins.left, margins.top
        x1, y1 = x0 + nx * total.width, y0 + ny * total.height

        if self.clip:
            all_frames = self.clip.iter_frames()
        elif self.frames:
            all_frames = AnimatedGif(self.im)
        else:
            all_frames = []
        for f in all_frames:
            ready = float(i + 1) / self.frame_count
            if self.verbosity:
                sys.stdout.write("\rProcessing frames |{:30}| {}%".format("X" * int(30 * ready), int(100 * ready)))
                sys.stdout.flush()
            tx += 1
            if type(f) == GifImagePlugin.GifImageFile:
                f.putpalette(self.palette)
                self.last_im.paste(f)
                im = self.last_im.convert("RGBA")
            else:
                im = Image.fromarray(f)
                im.thumbnail(frame.to_tuple())
            if tx == nx:
                tx = 0
                ty += 1
                if ty == ny:
                    ty = 0
                    draw_raster()
                    pdf.add_page()
                    page += 1
            temp_file = "tmp-{}-{}-{}.jpg".format(page, tx, ty)
            im.save(temp_file)
            tmp_files.append(temp_file)
            x = x0 + tx * total.width
            y = y0 + ty * total.height
            pdf.image(temp_file, x=x + offset, y=y, w=frame_mm.width, h=frame_mm.height)
            text = Point(x, y + frame_mm.height - 2)
            if offset > 0:
                pdf.rotate(90, text.x, text.y)
                pdf.text(text.x, text.y + 5, "{}".format(i))
                pdf.rotate(0)
            i += 1

        if y != 0 and x != 0:
            draw_raster()

        if self.verbosity > 0:
            print "\nGenerating PDF ..."
        pdf.output(name=output_file_name)
        if self.verbosity > 0:
            print "Removing temporary files ..."
        for temp_file in tmp_files:
            os.remove(temp_file)