Esempio n. 1
0
    def addCover(self):
        w = 12.25 * inch + ((self.pageNum + 2) +
                            (4 - (self.pageNum + 2) % 4)) * 0.002252 * inch
        c = canvas.Canvas(self.path + 'covers\\' + self.docName + "English-" +
                          self.lang + '.pdf',
                          pagesize=(w, 9.25 * inch))
        c.setFillColorRGB(228 / 256, 240 / 256, 255 / 256)
        c.rect(0 * mm, 0 * inch, w, 9.25 * inch, stroke=0, fill=1)
        c.setFillColorRGB(5 / 256, 92 / 256, 157 / 256)
        c.rect(0 * mm, (121 / 96) * inch,
               w, (619 / 96) * inch,
               stroke=0,
               fill=1)

        if self.currentBookNum % 400 < 101:
            pages = PdfReader(self.path + 'frames\\' + 'Frame13.pdf').pages
            pages = [pagexobj(x) for x in pages]
        elif self.currentBookNum % 400 < 201:
            pages = PdfReader(self.path + 'frames\\' + 'Frame15.pdf').pages
            pages = [pagexobj(x) for x in pages]
        elif self.currentBookNum % 400 < 301:
            pages = PdfReader(self.path + 'frames\\' + 'Frame16.pdf').pages
            pages = [pagexobj(x) for x in pages]
        else:
            pages = PdfReader(self.path + 'frames\\' + 'Frame17.pdf').pages
            pages = [pagexobj(x) for x in pages]

        pages1 = PdfReader(self.path + 'frames\\' + 'Frame9.pdf').pages
        pages1 = [pagexobj(x) for x in pages1]

        c.translate(0, 0)
        c.doForm(makerl(c, pages[0]))
        c.translate(w - 6.125 * inch, 0)
        c.doForm(makerl(c, pages1[0]))

        c.setFillColorRGB(0 / 256, 0 / 256, 102 / 256)
        c.setFont("SegoeUI", 10)
        text = "English - " + self.lang
        c.drawString((25 / 96) * inch, 8.2 * inch, text)

        p = Paragraph(self.engTitle, self.styles['coverTitle'])
        p.wrapOn(c, (514 / 96) * inch, 3 * inch)
        p.drawOn(c, (25 / 96) * inch, 4 * inch)

        p = Paragraph(self.otherTitle, self.styles['coverTitle'])
        x, y = p.wrapOn(c, (514 / 96) * inch, 3 * inch)
        p.drawOn(c, (25 / 96) * inch, 3.7 * inch - y)

        p = Paragraph(self.coverSubTitle[0], self.styles['coverSubTitle'])
        p.wrapOn(c, 5.3 * inch, 1 * inch)
        p.drawOn(c, (25 / 96) * inch, 0.7 * inch)

        p = Paragraph(self.coverSubTitle[1], self.styles['coverSubTitle'])
        p.wrapOn(c, 5.3 * inch, 1 * inch)
        p.drawOn(c, (25 / 96) * inch, 0.5 * inch)

        c.save()
Esempio n. 2
0
 def __init__(self, controller):
     self.controller = controller
     self.selections = self.controller.selections
     
     self._set_packet_type_id()
     
     if self.packet_type_id:
         # flags that indicate whether each of the files that need to be checked 
         # are being included in the packet
         self.check_files_included = {i : False for i in self.check_files_ids}
         
         self.addon_ids = []
         self.missing_files = []
         self.selected_reports = []
         self.selected_report_attributes = []
         self.selected_report_ids = []
         
         self.output_path = ''
         self.output_path_print = ''
         self.packet_type = ''
         
         self.output_name = self.output_names[self.selections.type_option]
         
         self.is_liaison = ('Liaison' in self.selections.type_option)
         
         self.create_print_file = False
         
         self.total_pages = 0
         
         self.blank_pdf_page = pagexobj(PdfReader(self.blank_pdf_path).pages[0])
             
         self.pdf_converter = PdfConverter()
             
         self._open_excel()
Esempio n. 3
0
def pdf_insert_doi_using_pdfrw(req_content, doi):
    input_file = io.BytesIO(req_content)
    pdf_buffer = io.BytesIO()
    reader = PdfReader(input_file)
    pages = [pagexobj(p) for p in reader.pages]

    canvas = Canvas(pdf_buffer)

    for page_num, page in enumerate(pages, start=1):
        canvas.setPageSize((page.BBox[2], page.BBox[3]))
        canvas.doForm(makerl(canvas, page))

        # Draw footer
        if page_num == 1:
            footer_text = "https://doi.org/{}".format(doi)
            canvas.saveState()
            canvas.setFont("Helvetica-Bold", 8)
            canvas.setFillColor(HexColor('#990100'))
            canvas.drawCentredString(page.BBox[2] / 2, 20, footer_text)
            canvas.restoreState()

        canvas.showPage()

    canvas.save()
    pdf_bytes = pdf_buffer.getbuffer()
    return pdf_bytes
Esempio n. 4
0
    def __init__(self,
                 filename_or_object,
                 width=None,
                 height=None,
                 kind='direct'):
        #        from reportlab.lib.units import inch
        # If using StringIO buffer, set pointer to begining
        if hasattr(filename_or_object, 'read'):
            filename_or_object.seek(0)
        page = PdfReader(filename_or_object, decompress=False).pages[0]
        self.xobj = pagexobj(page)
        self.imageWidth = width
        self.imageHeight = height
        x1, y1, x2, y2 = self.xobj.BBox

        self._w, self._h = x2 - x1, y2 - y1
        if not self.imageWidth:
            self.imageWidth = self._w
        if not self.imageHeight:
            self.imageHeight = self._h
        self.__ratio = float(self.imageWidth) / self.imageHeight
        if kind in ['direct', 'absolute'] or width == None or height == None:
            self.drawWidth = width or self.imageWidth
            self.drawHeight = height or self.imageHeight
        elif kind in ['bound', 'proportional']:
            factor = min(float(width) / self._w, float(height) / self._h)
            self.drawWidth = self._w * factor
            self.drawHeight = self._h * factor
Esempio n. 5
0
    def insert_text_output_pdf(pdf_file_path, target_coordinate, insert_text):
        """
        既存のPDFファイルに文字を挿入し、別名で出力します
        :param pdf_file_path:       既存のPDFファイルパス
        :param target_coordinate:   テキストを挿入座標値(mm)
        :param insert_text:         挿入するテキスト
        :return:
        """
        import numpy as np
        from pdfrw import PdfReader
        from pdfrw.buildxobj import pagexobj
        from pdfrw.toreportlab import makerl
        from reportlab.pdfgen import canvas
        from reportlab.pdfbase.cidfonts import UnicodeCIDFont
        from reportlab.pdfbase import pdfmetrics
        from reportlab.lib.units import mm
        from src.utils.time_util import get_now

        output_name = f"{get_now()}.pdf"
        cc = canvas.Canvas(output_name)
        fontname_g = "HeiseiKakuGo-W5"
        pdfmetrics.registerFont(UnicodeCIDFont(fontname_g))
        cc.setFont(fontname_g, 16)

        page = PdfReader(pdf_file_path, decompress=False).pages
        pp = pagexobj(page[0])
        cc.doForm(makerl(cc, pp))

        target_coordinate_arr = np.squeeze(np.asarray(target_coordinate))
        target_x, target_y = target_coordinate_arr[0], target_coordinate_arr[1]
        cc.drawString(target_x*mm, target_y*mm, insert_text)
        cc.showPage()
        cc.save()
Esempio n. 6
0
 def __init__(self, pdf_template_filename, name=None):
     # use first page as template
     page = PdfReader(pdf_template_filename).pages[0]
     self.page_template = pagexobj(page)
     # Scale it to fill the complete page
     self.page_xscale = PAGE_WIDTH/self.page_template.BBox[2]
     self.page_yscale = PAGE_HEIGHT/self.page_template.BBox[3]
Esempio n. 7
0
def op_w_input(input_fname=None,
               watermark_fname=None,
               outfn0=os.getcwd() + "/Watermarked_PDF_Files/",
               pdfdir=None,
               outdir='tmp'):
    # options=list
    # options.input_fname=input_fname
    # options.watermark_fname=watermark_fname
    # options.pdfdir=pdfdir
    if input_fname and watermark_fname:
        watermark = pagexobj(
            PdfReader(watermark_fname, decompress=False).pages[0])
        # outfn = 'watermark.' + os.path.basename(options.input_fname)
        outfn = os.path.basename(outfn0)
        pages = PdfReader(input_fname, decompress=False).pages
        # output = PdfFileWriter()
        #
        #
        # for i in range(0,pages.getNumPages()):
        #     p = pages.getPage(i)
        #     wt=watermark.getPage(0)
        #     wt.mergePage(p)
        #     output.addPage(wt)
        # outputStream=open(Wm_f, 'wb')
        # # outputStream=StringIO.StringIO()
        # # output.write(open(Wm_f, 'wb'))
        # output.write(outputStream)
        #     outputStream.close()
        test = PdfWriter().addpages([fixpage(x, watermark) for x in pages])
        test.write(outfn0)

    elif pdfdir and watermark_fname:
        batch_watermark(pdfdir, watermark_fname, outdir)
    else:
        parser.print_help()
Esempio n. 8
0
def fixpage(*pages):
    pages = [pagexobj(x) for x in pages]

    class PageStuff(tuple):
        pass

    x = y = 0
    for i, page in enumerate(pages):
        index = '/P%s' % i
        shift_right = x and '1 0 0 1 %s 0 cm ' % x or ''
        stuff = PageStuff((index, page))
        stuff.stream = 'q %s%s Do Q\n' % (shift_right, index)
        x += page.BBox[2]
        y = max(y, page.BBox[3])
        pages[i] = stuff

    # Multiple copies of first page used as a placeholder to
    # get blank page on back.
    for p1, p2 in zip(pages, pages[1:]):
        if p1[1] is p2[1]:
            pages.remove(p1)

    return IndirectPdfDict(
        Type=PdfName.Page,
        Contents=PdfDict(stream=''.join(page.stream for page in pages)),
        MediaBox=PdfArray([0, 0, x, y]),
        Resources=PdfDict(
            XObject=PdfDict(pages),
        ),
    )
Esempio n. 9
0
def pdf_generate_proc(file_template, file_pdf, receiver, price):
    sys.stderr.write("*** pdf_generate_proc *** start ***\n")
    #
    pdf_canvas = canvas.Canvas(file_pdf)
    #
    fontname_g = "HeiseiKakuGo-W5"
    pdfmetrics.registerFont(UnicodeCIDFont(fontname_g))
    pdf_canvas.setFont(fontname_g, 16)
    #
    page = PdfReader(file_template, decompress=False).pages
    pp = pagexobj(page[0])
    pdf_canvas.doForm(makerl(pdf_canvas, pp))
    #
    today = datetime.today()
    str_today = today.strftime('%Y-%m-%d')
    #
    pdf_canvas.drawString(400, 800, str_today)
    pdf_canvas.drawString(100, 725, receiver)
    pdf_canvas.drawString(100, 680, str(price))
    #
    draw_rect_proc(pdf_canvas)
    #
    pdf_canvas.showPage()
    pdf_canvas.save()
    #
    sys.stderr.write("*** pdf_generate_proc *** end ***\n")
    #
    str_res = "Supdf_canvasess"
    return str_res
Esempio n. 10
0
 def __init__(self,
              filename_or_object,
              width=None,
              height=None,
              kind="direct"):
     if hasattr(filename_or_object, "read"):
         filename_or_object.seek(0)
     page = PdfReader(filename_or_object, decompress=False).pages[0]
     self.xobj = pagexobj(page)
     self.dynamic = 0
     # Actual image size
     x1, y1, x2, y2 = self.xobj.BBox
     imgw, imgh = x2 - x1, y2 - y1
     self._imgw, self._imgh = imgw, imgh
     if kind in ["direct", "absolute"]:
         self.drawWidth = width or imgw
         self.drawHeight = height or imgh
     elif kind in ["percentage", "%"]:
         self.drawWidth = imgw * width * 0.01
         self.drawHeight = imgh * height * 0.01
     elif kind in ["bound", "proportional"]:
         w, h = width or imgw, height or imgh
         factor = min(float(w) / imgw, float(h) / imgh)
         self.drawWidth = imgw * factor
         self.drawHeight = imgh * factor
     elif kind in ["dynamic"]:
         self.dynamic = 1
Esempio n. 11
0
def fixpage(*pages):
    pages = [pagexobj(x) for x in pages]

    class PageStuff(tuple):
        pass

    x = y = 0
    for i, page in enumerate(pages):
        index = '/P%s' % i
        shift_right = x and '1 0 0 1 %s 0 cm ' % x or ''
        stuff = PageStuff((index, page))
        stuff.stream = 'q %s%s Do Q\n' % (shift_right, index)
        x += page.BBox[2]
        y = max(y, page.BBox[3])
        pages[i] = stuff

    # Multiple copies of first page used as a placeholder to
    # get blank page on back.
    for p1, p2 in zip(pages, pages[1:]):
        if p1[1] is p2[1]:
            pages.remove(p1)

    return IndirectPdfDict(
        Type=PdfName.Page,
        Contents=PdfDict(stream=''.join(page.stream for page in pages)),
        MediaBox=PdfArray([0, 0, x, y]),
        Resources=PdfDict(XObject=PdfDict(pages), ),
    )
Esempio n. 12
0
def include_footer(input_file_path, output_file_path, link=None):

    # Get pages
    reader = PdfReader(input_file_path)
    pages = [pagexobj(p) for p in reader.pages]

    # Compose new pdf
    canvas = Canvas(output_file_path)

    for page_num, page in enumerate(pages, start=1):

        # Add page
        canvas.setPageSize((page.BBox[2], page.BBox[3]))
        canvas.doForm(makerl(canvas, page))

        # Draw footer
        footer_text = f"This report is reproducible with FAIR data. Find the source datasets here: {link}"
        x = 80
        canvas.saveState()
        canvas.setStrokeColorRGB(0, 0, 0)
        canvas.setLineWidth(0.5)
        canvas.line(66, 40, page.BBox[2] - 66, 40)
        canvas.setFont('Helvetica', 8)
        canvas.drawString(66, 25, footer_text)
        canvas.linkURL(link, (66, 25, page.BBox[2] - 66, 40))
        canvas.restoreState()

        canvas.showPage()

    canvas.save()
Esempio n. 13
0
def add_footer(input_file, output_file):
    logging.info("add_footer started")
    # Get pages
    reader = PdfReader("%s.pdf" % (input_file))
    pages = [pagexobj(p) for p in reader.pages]

    # Compose new pdf
    canvas = Canvas("%s.pdf" % (output_file))
    pdfmetrics.registerFont(
        TTFont('SourceSansPro', 'SourceSansPro-Regular.ttf'))

    for page_num, page in enumerate(pages, start=1):

        # Add page
        canvas.setPageSize((page.BBox[2], page.BBox[3]))
        canvas.doForm(makerl(canvas, page))

        # Draw footer
        footer_text = "www.borderviolence.eu"
        x = 80
        canvas.saveState()
        canvas.setStrokeColorRGB(0.19, 0.19, 0.19)
        canvas.setLineWidth(0.3)
        canvas.line(75, 78, page.BBox[2] - 66, 78)
        canvas.setFont('SourceSansPro', 10)
        canvas.setFillColor(HexColor(0x333333))
        canvas.drawString(page.BBox[2] - x, 85, str(page_num))
        canvas.drawString(page.BBox[2] - x - 436, 85, footer_text)
        canvas.restoreState()

        canvas.showPage()

    canvas.save()
    logging.info("PDF with footer %s.pdf was saved" % (output_file))
    return 1
Esempio n. 14
0
def edit_pdf(filePath):
    input_file = filePath
    output_file = filePath
    # Get pages
    reader = PdfReader(input_file)
    pages = [pagexobj(p) for p in reader.pages]
    # Compose new pdf
    canvas = Canvas(output_file)
    for page_num, page in enumerate(pages, start=1):
        # Add page
        canvas.setPageSize((page.BBox[2], page.BBox[3]))
        canvas.doForm(makerl(canvas, page))
        # Draw header
        header_text = "Jhon institute"
        x = 180
        canvas.saveState()
        canvas.setStrokeColorRGB(0, 0, 0)
        canvas.drawImage('input_logo.jpg', height=60, width=110,x=60, y=700)
        canvas.setFont('Times-Roman', 14)
        canvas.drawString(page.BBox[2] -x, 730, header_text)
        # Draw footer
        footer_text = "It’s easy to play any musical instrument: all you have to do is touch the right key at " \
                      "the right time and the instrument will play itself."
        x = 70
        canvas.setStrokeColorRGB(0, 0, 0)
        canvas.setLineWidth(0.5)
        canvas.setFont('Times-Roman', 10)
        canvas.drawString(page.BBox[1] +x, 30, footer_text)
        canvas.restoreState()

        canvas.showPage()

    canvas.save()
Esempio n. 15
0
def control_forms ( pieces, output ):
    """Write a pdf file to 'output',
    and generate control forms (one or more pages each) for 'pieces'.
    """
    c = Canvas ( output, pagesize=letter )
    pdf = PdfReader ( settings.ARTSHOW_BLANK_CONTROL_FORM )
    xobj = pagexobj ( pdf.pages[0] )
    rlobj = makerl ( c, xobj )
    for artist, piecegroup in group_pieces_by_artist_and_n ( pieces, PIECES_PER_CONTROL_FORM ):
        c.doForm ( rlobj )
        text_into_box ( c, settings.ARTSHOW_SHOW_YEAR, 2.4, 10.3, 3.05, 10.6 )
        text_into_box ( c, unicode(artist.artistid), 6.6, 10.25, 8.0, 10.5 )
        text_into_box ( c, artist.person.name, 1.7, 9.875, 4.1, 10.225, style=left_align_style )
        text_into_box ( c, artist.artistname(), 1.7, 9.5,    4.1, 9.85, style=left_align_style )
        text_into_box ( c, artist.person.address1 + " " + artist.person.address2, 1.7, 9.125,  4.1, 9.475, style=left_align_style )
        text_into_box ( c, artist.person.city, 1.7, 8.75,   4.1,  9.1, style=left_align_style   )
        text_into_box ( c, artist.person.state, 1.7, 8.375,  4.1,  8.725, style=left_align_style )
        text_into_box ( c, artist.person.postcode, 1.7, 8.0,    4.1,  8.35, style=left_align_style  )
        text_into_box ( c, artist.person.country, 1.7, 7.625,  4.1,  7.975, style=left_align_style )
        text_into_box ( c, artist.person.phone, 1.7, 7.25,   4.1,  7.6, style=left_align_style   )
        text_into_box ( c, artist.person.email, 4.9, 9.875, 8.0, 10.225, style=left_align_style, fontSize=16 )      
        text_into_box ( c, ", ".join ( [agent.person.name for agent in artist.agent_set.all()] ), 5.9, 7.625, 8.0, 7.975, style=left_align_style )
        for i, piece in enumerate(piecegroup):
            if piece is None: continue
            y0 = 6.45 - i*0.25
            y1 = 6.675 - i*0.25
            text_into_box ( c, unicode(piece.pieceid), 0.5, y0, 1.0, y1 )           
            text_into_box ( c, piece.name, 1.0, y0, 4.0, y1, style=left_align_style )           
            text_into_box ( c, yn(piece.adult), 4.0, y0, 4.5, y1 )          
            text_into_box ( c, priceornfs(piece.not_for_sale,piece.min_bid), 4.5, y0, 5.25, y1 )            
            text_into_box ( c, buynoworna(piece.buy_now), 5.25, y0, 6.0, y1 )           
        c.showPage ()
    c.save ()
Esempio n. 16
0
def add_footer():
    input_file = "/tmp/merged.pdf"
    output_file = "/tmp/merged_footer.pdf"

    # Get pages
    reader = PdfReader(input_file)
    pages = [pagexobj(p) for p in reader.pages]

    # Compose new pdf
    canvas = Canvas(output_file)

    for page_num, page in enumerate(pages, start=1):

        # # Add page
        canvas.setPageSize((page.BBox[2], page.BBox[3]))
        canvas.doForm(makerl(canvas, page))

        canvas.setFont("Helvetica", 10)

        if canvas._pagesize[0] > canvas._pagesize[1]:
            canvas.saveState()
            canvas.rotate(270)
            canvas.translate(-30, -A4[0] + 30)
            canvas.drawRightString(
                -10, A4[0], "%d de %d" % (canvas._pageNumber, len(pages)))
            canvas.restoreState()
        else:
            canvas.drawRightString(
                A4[0] - 60, 30, "%d de %d" % (canvas._pageNumber, len(pages)))

        canvas.showPage()

    canvas.save()
def create_card_face(c, domain, category, header_text, footer_text, frame_colour, content_pdf_fn, offset=0, key_ring=1):
	# Colour frame
	c.setFillColorRGB(frame_colour[0], frame_colour[1], frame_colour[2])
	c.roundRect(0 + offset, 0, FACE_DIM[0], FACE_DIM[1], radius=OUTER_ROUNDED_RAD, stroke=0, fill=1)

	# Content space
	c.setFillColorRGB(1, 1, 1)
	c.roundRect(FACE_MARGINS[3] + offset, FACE_MARGINS[2], CONTENT_DIM[0], CONTENT_DIM[1], radius=INNER_ROUNDED_RAD, stroke=0, fill=1)

	# Key ring cut-out, 0 = none, 1 = left, 2 = right
	if key_ring == 1:
		c.circle(0, DOCUMENT_DIM[1], KEY_RING_RAD, stroke=0, fill=1)
	elif key_ring == 2:
		c.circle(DOCUMENT_DIM[0], DOCUMENT_DIM[1], KEY_RING_RAD, stroke=0, fill=1)

	# Domain / Caetgory text
	c.setFont('Helvetica', 10, leading = None)
	c.drawCentredString(FACE_DIM[0]/2 + offset, FACE_DIM[1] - 0.47*cm, '- ' + domain.title() + ' -')
	# c.drawCentredString(FACE_DIM[0]/2 + offset, FACE_DIM[1] - 0.47*cm, domain.title() + ' / ' + category.title())

	# Header text
	c.setFont('Helvetica-Bold', 20, leading = None)
	c.drawCentredString(FACE_DIM[0]/2 + offset, FACE_DIM[1] - 1.23*cm, header_text)

	# Footer text
	c.setFont('Helvetica', 8, leading = None)
	c.drawCentredString(FACE_DIM[0]/2 + offset, 0.15*cm, footer_text)

	# Include contents
	c.setFillColorRGB(0, 0, 0)
	page = pagexobj(PdfReader(content_pdf_fn).pages[0])
	c.saveState()
	c.translate(FACE_MARGINS[3] + offset, FACE_MARGINS[2])
	c.doForm(makerl(c, page))
	c.restoreState()
Esempio n. 18
0
 def __init__(self, filename):
     pages = PdfReader(filename).pages
     num_pages = len(pages)
     assert num_pages > 0
     if num_pages > 1:
         warning.warn("PDF file %s has %d pages, using only the first." %
                      (filename, num_pages))
     self.pagexobj = pagexobj(pages[0])
Esempio n. 19
0
 def _set_pdf_pages(self):
     '''
         Stores all the pages of each PDF as page objects.
     '''
     for i in self.selected_reports:
         i.pdf_pages = [
             pagexobj(p) for p in PdfReader(i.path).pages
             ]
Esempio n. 20
0
    def post(self, request):
        fontname_g = "HeiseiKakuGo-W5"
        pdfmetrics.registerFont(UnicodeCIDFont(fontname_g))
        buffer = io.BytesIO()
        cc = canvas.Canvas(buffer)
        cc.setFont(fontname_g, 24)
        page = PdfReader('media/pdf/sample.pdf', decompress=False).pages
        pp = pagexobj(page[0])
        # reader = PdfFileReader('media/pdf/sample.pdf')
        # writer = PdfFileWriter()
        test = {
            "test1":
            "test1",
            "test2":
            "S2",
            "test3":
            "テスト",
            "test4": [
                {
                    "key_label": "テスト1",
                    "flag": True
                },
                {
                    "key_label": "テスト2",
                    "flag": True
                },
                {
                    "key_label": "テスト3",
                    "flag": True
                },
            ]
        }
        a = request.data['test_list']
        for i in a:
            self.test(cc, i.get('contents'), test)
        cc.doForm(makerl(cc, pp))
        cc.showPage()
        cc.save()
        buffer.seek(0)
        # new_pdf = PdfFileReader(buffer)
        # existing_page = reader.getPage(0)
        # existing_page.mergePage(new_pdf.getPage(0))
        # writer.addPage(existing_page)

        # new = io.BytesIO()
        # writer.write(new)
        # new.seek(0)

        # output_pdf = open('media/pdf/sample2.pdf', 'wb')
        r = PdfReader(buffer)
        y = PdfWriter()
        y.addpage(r.pages[0])
        with open('media/pdf/sample2.pdf', 'wb') as f:
            y.write(f)
        # writer.write(output_pdf)
        # output_pdf.close()
        return Response({'detail': _('Successfully confirmed email.')},
                        status=status.HTTP_201_CREATED)
Esempio n. 21
0
 def __init__(self, filename):
     pages = PdfReader(filename).pages
     num_pages = len(pages)
     assert num_pages > 0
     if num_pages > 1:
         warning.warn("PDF file %s has %d pages, using only the first." % (
             filename, num_pages
             ))
     self.pagexobj = pagexobj(pages[0])
Esempio n. 22
0
 def _make_cover(self):
     name = f'{self.jurisdiction.id}_packet_cover.pdf'
     
     path = str(constants.TEMP_FILE_PATH.joinpath(name))
     
     reader = PdfReader(self.blank_cover_path)
     page = pagexobj(reader.pages[0])
     
     canvas = Canvas(path, pagesize=letter)
     canvas.setPageSize((page.BBox[2], page.BBox[3]))
     canvas.doForm(makerl(canvas, page))
     canvas.saveState()
      
     max_title_len = 15
     max_title_font_size = 60
     max_title_pixel = max_title_len * max_title_font_size
     
     x = 15
     
     mid_x = x//2
     
     y1 = 15
     
     fs1 = 16
     y2 = y1 + mid_x + fs1
     
     fs2 = 36
     y3 = y2 + mid_x + fs2
     
     fs3 = max_title_font_size
     
     title = self.jurisdiction.name
     
     rep_info = self._get_rep_info()
     
     # draws the email and phone of the rep   
     canvas.setFontSize(fs1)
     canvas.setFillGray(0.45) 
     canvas.drawString(x=x, y=y1, text=f'{rep_info[0]} | {rep_info[1]}')
        
     canvas.setFont('Calibri', fs2)
     canvas.drawString(
         x=x, y=y2, text=f'Economic Review {self.selections.period}')
        
     canvas.setFillColorRGB(0, .23, .34)
     if len(title) > max_title_len:
         fs3 = max_title_pixel//len(title)
        
     canvas.setFontSize(fs3)
     canvas.drawString(x=x, y=y3, text=title)
        
     canvas.restoreState()
     canvas.showPage()       
     canvas.save()
     
     self._set_path(self.check_files_ids['cover'], path)
Esempio n. 23
0
def get_logo(filename, target_width, width_in_file, height_in_file):
    '''width_in_file and height_in_file can be in any matching units'''
    width_in_file = 191.87
    height_in_file = 54.84
    s = target_width / width_in_file
    target_height = height_in_file * s

    logo = PdfImage(pagexobj(PdfReader(filename).pages[0]), target_width,
                    target_height)
    return logo
Esempio n. 24
0
def process_file(f_input, f_watermark, f_output):

    watermark = pagexobj(PdfReader(f_watermark, decompress=False).pages[0])

    pagestream = PdfReader(f_input, decompress=False)
    for page in pagestream.pages:
        watermark_page(page, watermark)
    PdfWriter().write(f_output, pagestream)

    return len(pagestream.pages)
Esempio n. 25
0
def fix_pdf(fname, watermark_fname, indir, outdir):
    from os import mkdir, path
    if not path.exists(outdir):
        mkdir(outdir)
    watermark = pagexobj(PdfReader(watermark_fname).pages[0])
    trailer = PdfReader(path.join(indir, fname))
    for page in trailer.pages:
        fixpage(page, watermark)
    PdfWriter().write(path.join(outdir, fname), trailer)
    return len(trailer.pages)
Esempio n. 26
0
def fix_pdf(fname, watermark_fname, indir, outdir):
    from os import mkdir, path
    if not path.exists(outdir):
        mkdir(outdir)
    watermark = pagexobj(PdfReader(watermark_fname).pages[0])
    trailer = PdfReader(path.join(indir, fname))
    for page in trailer.pages:
        fixpage(page, watermark)
    PdfWriter().write(path.join(outdir, fname), trailer)
    return len(trailer.pages)
Esempio n. 27
0
def go(argv):
    inpfn, = argv
    outfn = '4up.' + os.path.basename(inpfn)

    pages = PdfReader(inpfn).pages
    pages = [pagexobj(x) for x in pages]
    canvas = Canvas(outfn)

    while pages:
        addpage(canvas, pages)
    canvas.save()
Esempio n. 28
0
def go(argv):
    inpfn, = argv
    outfn = '4up.' + os.path.basename(inpfn)

    pages = PdfReader(inpfn).pages
    pages = [pagexobj(x) for x in pages]
    canvas = Canvas(outfn)

    while pages:
        addpage(canvas, pages)
    canvas.save()
Esempio n. 29
0
def load_pdf_as_form(canvas, path):
    """
    Convert a pdf file into a reportlab object

    :param canvas: Reportlab Canvas object the form may be written to
    :param path: path to pdf file to open
    :return: a reportlab object that may be drawn using canvas.doForm(obj)
    """
    pdf = PdfReader(path)
    xobj = pagexobj(pdf.pages[0])
    reportlab_obj = makerl(canvas, xobj)
    return reportlab_obj
Esempio n. 30
0
 def __init__(self, pdf_template_filename, name=None):
     frames = [
         Frame(0.85 * inch, 0.5 * inch, PAGE_WIDTH - 1.15 * inch,
               PAGE_HEIGHT - (1.5 * inch))
     ]
     PageTemplate.__init__(self, name, frames)
     # use first page as template
     page = PdfReader(pdf_template_filename).pages[0]
     self.page_template = pagexobj(page)
     # Scale it to fill the complete page
     self.page_xscale = PAGE_WIDTH / self.page_template.BBox[2]
     self.page_yscale = PAGE_HEIGHT / self.page_template.BBox[3]
Esempio n. 31
0
def read_and_double(inpfn):
    pages = PdfReader(inpfn, decompress=False).pages
    pages = [pagexobj(x) for x in pages]
    if len(pages) & 1:
        pages.append(pages[0])  # Sentinel -- get same size for back as front

    xobjs = []
    while len(pages) > 2:
        xobjs.append((pages.pop(), pages.pop(0)))
        xobjs.append((pages.pop(0), pages.pop()))
    xobjs += [(x, ) for x in pages]
    return xobjs
Esempio n. 32
0
def read_and_double(inpfn):
    pages = PdfReader(inpfn, decompress=False).pages
    pages = [pagexobj(x) for x in pages]
    if len(pages) & 1:
        pages.append(pages[0])  # Sentinel -- get same size for back as front

    xobjs = []
    while len(pages) > 2:
        xobjs.append((pages.pop(), pages.pop(0)))
        xobjs.append((pages.pop(0), pages.pop()))
    xobjs += [(x,) for x in pages]
    return xobjs
Esempio n. 33
0
 def __init__(self, document, path):
     self.document = document
     self.pages = []
     self.refs = []
     template = PdfReader(path)
     letterhead_num = 1
     for page in template.pages:
         xobject = XObject(self,
                           pagexobj(page),
                           name='Letterhead{}'.format(letterhead_num))
         self.pages.append(xobject.form)
         letterhead_num += 1
Esempio n. 34
0
def load_pdf_as_form(canvas, path):
    """
    Convert a pdf file into a reportlab object

    :param canvas: Reportlab Canvas object the form may be written to
    :param path: path to pdf file to open
    :return: a reportlab object that may be drawn using canvas.doForm(obj)
    """
    pdf = PdfReader(path)
    xobj = pagexobj(pdf.pages[0])
    reportlab_obj = makerl(canvas, xobj)
    return reportlab_obj
Esempio n. 35
0
    def add_page_number(
            pdf_name,
            source_data_footext=ReportParameters.REFERENCE_DATA_TEXT,
            reference_footer_text=ReportParameters.REFERENCE_USE_FOOTER_TEXT):
        """

        Args:
            pdf_name:
            source_data_footext:
            reference_footer_text:

        Returns:

        """

        input_file = pdf_name
        output_file = pdf_name

        # Get pages
        reader = PdfReader(input_file)
        pages = [pagexobj(p) for p in reader.pages]

        # Compose new pdf
        canvas = Canvas(output_file)

        for page_num, page in enumerate(pages, start=1):
            # Add page
            canvas.setPageSize((page.BBox[2], page.BBox[3]))
            canvas.doForm(makerl(canvas, page))

            # Draw footer
            page_number_footer_text = "Page %s of %s" % (page_num, len(pages))

            x = 128
            canvas.saveState()
            # canvas.setStrokeColorRGB(0, 0, 0)
            canvas.setLineWidth(0.5)
            canvas.line(66, 72, page.BBox[2] - 66, 72)
            canvas.setFont('Times-Roman', 10)
            canvas.drawString(x=(page.BBox[2] - x),
                              y=60,
                              text=page_number_footer_text)

            canvas.drawString(x=66, y=60, text=source_data_footext)

            canvas.drawString(x=66, y=45, text=reference_footer_text)

            canvas.restoreState()
            canvas.showPage()

        # Save pdf
        canvas.save()
Esempio n. 36
0
 def get(self, request, *args, **kwargs):
     fontname_g = "HeiseiKakuGo-W5"
     pdfmetrics.registerFont(UnicodeCIDFont(fontname_g))
     buffer = io.BytesIO()
     cc = canvas.Canvas(buffer)
     page = PdfReader('media/pdf/sample.pdf', decompress=False).pages
     pp = pagexobj(page[0])
     cc.doForm(makerl(cc, pp))
     cc.setFont(fontname_g, 24)
     cc.drawString(0, 820, "テスト")
     cc.showPage()
     cc.save()
     buffer.seek(0)
     return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
Esempio n. 37
0
 def __init__(self, pdf_template_filename, name=None):
     frames = [Frame(
         PAD,
         PAD,
         PAGE_WIDTH - 2 * PAD,
         PAGE_HEIGHT - 2 * PAD,
         )]
     PageTemplate.__init__(self, name, frames)
     # use first page as template
     page = PdfReader(pdf_template_filename, decompress=False).pages[0]
     self.page_template = pagexobj(page)
     # Scale it to fill the complete page
     self.page_xscale = PAGE_WIDTH/self.page_template.BBox[2]
     self.page_yscale = PAGE_HEIGHT/self.page_template.BBox[3]
Esempio n. 38
0
def go(inpfn, firstpage, lastpage):
    firstpage, lastpage = int(firstpage), int(lastpage)
    outfn = 'subset_%s_to_%s.%s' % (firstpage, lastpage, os.path.basename(inpfn))

    pages = PdfReader(inpfn).pages
    pages = [pagexobj(x) for x in pages[firstpage-1:lastpage]]
    canvas = Canvas(outfn)

    for page in pages:
        canvas.setPageSize(tuple(page.BBox[2:]))
        canvas.doForm(makerl(canvas, page))
        canvas.showPage()

    canvas.save()
Esempio n. 39
0
 def __init__(self, pdf_template_filename, name=None):
     frames = [Frame(
         0.85 * inch,
         0.5 * inch,
         PAGE_WIDTH - 1.15 * inch,
         PAGE_HEIGHT - (1.5 * inch)
         )]
     PageTemplate.__init__(self, name, frames)
     # use first page as template
     page = PdfReader(pdf_template_filename).pages[0]
     self.page_template = pagexobj(page)
     # Scale it to fill the complete page
     self.page_xscale = PAGE_WIDTH/self.page_template.BBox[2]
     self.page_yscale = PAGE_HEIGHT/self.page_template.BBox[3]
Esempio n. 40
0
def go(inpfn, firstpage, lastpage):
    firstpage, lastpage = int(firstpage), int(lastpage)
    outfn = 'subset_%s_to_%s.%s' % (firstpage, lastpage, os.path.basename(inpfn))

    pages = PdfReader(inpfn, decompress=False).pages
    pages = [pagexobj(x) for x in pages[firstpage-1:lastpage]]
    canvas = Canvas(outfn)

    for page in pages:
        canvas.setPageSize(tuple(page.BBox[2:]))
        canvas.doForm(makerl(canvas, page))
        canvas.showPage()

    canvas.save()
Esempio n. 41
0
def go(inpfn, firstpage, lastpage):
    firstpage, lastpage = int(firstpage), int(lastpage)
    outfn = 'subset.' + os.path.basename(inpfn)

    pages = PdfReader(inpfn).pages
    pages = [pagexobj(x) for x in pages[firstpage - 1:lastpage]]
    canvas = Canvas(outfn)

    for page in pages:
        canvas.setPageSize((page.BBox[2], page.BBox[3]))
        canvas.doForm(makerl(canvas, page))
        canvas.showPage()

    canvas.save()
Esempio n. 42
0
 def __init__(self, bg_page, name=None):
     frames = [Frame(
         22.0*mm,
         13.0*mm,
         PAGE_WIDTH-30.0*mm,
         PAGE_HEIGHT-30.0*mm,
         )]
     PageTemplate.__init__(self, name, frames)
     self.page_template = pagexobj(bg_page)
     # scale to fill the complete page
     self.page_xscale = PAGE_WIDTH/self.page_template.BBox[2]
     self.page_yscale = PAGE_HEIGHT/self.page_template.BBox[3]
     # store content and absolute position of paragraphs/primitives
     self.abspars = []
     self.absprims = []
Esempio n. 43
0
File: helpers.py Progetto: oledm/gmp
 def __init__(self, filename, width=None, height=None, kind='bound',
                                  mask=None, lazy=True, srcinfo=None):
     Flowable.__init__(self)
     self._kind = kind
     page = PdfReader(filename, decompress=False).pages[0]
     self.xobj = pagexobj(page)
     self.imageWidth, self.imageHeight = imageWidth, imageHeight = self.xobj.w, self.xobj.h
     width = width or imageWidth
     height = height or imageHeight
     if kind in ['bound','proportional']:
         factor = min(float(width)/imageWidth,float(height)/imageHeight)
         width = factor * imageWidth
         height = factor * imageHeight
     self.drawWidth = width
     self.drawHeight = height
Esempio n. 44
0
def labelbooklets(
    labels,
    pagecount,
    booklets="booklets.pdf",
    output="labeled_booklets.pdf",
    colfname="fname",
    collname="lname",
    colid="netID",
):
    """
    Outputs a PDF containing labeled exams given a data frame of labels,
    a PDF of unlabeled booklets, and the number of pages in each exam.
    """

    # Extract pages from booklet pdf
    pages = PdfReader(booklets, decompress=False).pages
    pagex = [pagexobj(i) for i in pages]

    # Set output path
    c = canvas.Canvas(output, pagesize=letter)

    # Select columns (order is important)
    labels = labels[[colfname, collname, colid]]

    # Truncate any string longer than 17 chars
    labels = labels.applymap(func="{:.17}".format)

    # Loop over all students to apply labels
    for (i, fname, lname, netid) in labels.itertuples():

        # Set font to fixed-wdith and set font size
        c.setFont("Courier", 32)

        # Extract the first page of this student's exam
        c.doForm(makerl(c, pagex[i * pagecount]))
        c.drawString(76, 481, fname.upper(), charSpace=7.8)
        c.drawString(76, 418, lname.upper(), charSpace=7.8)
        c.drawString(76, 355, netid.upper(), charSpace=7.8)
        c.showPage()

        # Loop over the rest of the pages in this student's exam
        for page in pagex[i * pagecount + 1:(i + 1) * pagecount]:
            c.doForm(makerl(c, page))
            c.showPage()

    # Save the PDF file after processing all students
    c.save()
    print("Attempting to save output to " + output)
Esempio n. 45
0
def popup_getpopup_xobjs():
    from pdfrw.buildxobj import pagexobj
    popups = {}
    toremove = []
    for page in popup_pdf.pages:
        if page['/SYMIDX.POPUP']:
            popupid = page['/SYMIDX.POPUP'].decode()
            if popupid in popups:
                raise RuntimeError(
                    "Duplicated /SYMIDX.POPUP: {}".format(popupid))
            xobj = pagexobj(page)
            popups[popupid] = xobj
            toremove.append(page)

    popup_removepages(popup_pdf, toremove)
    return popups
Esempio n. 46
0
def getPages(allpages, x, y, gap):

    # Number of pages to combine
    count = x * y

    # Pull pages off the list
    pages = [pagexobj(p) for p in allpages[:count]]
    del allpages[:count]

    # Out page size
    width_max  = max(page.BBox[2] for page in pages)
    height_max = max(page.BBox[3] for page in pages)

    stream = []
    xobjdict = PdfDict()

    line = y
    for index, page in enumerate(pages):

        width = (index % x) * width_max / x
        if not width:
            line = line - 1
        height = line * height_max / y

        # Page number
        index = PdfName('P{}'.format(index))

        format_stream = {
            "x": 1./x - gap,
            "y": 1./y - gap,
            "w": width,
            "h": height,
            "i": index
        }
        stream.append('q {x} 0 0 {y} {w} {h} cm {i} Do Q\n'.format(**format_stream))

        xobjdict[index] = page

    return PdfDict(
        Type = PdfName.Page,
        Contents = PdfDict(stream=''.join(stream)),
        MediaBox = PdfArray([-1000*gap, -1000*gap, width_max, height_max]),
        Resources = PdfDict(XObject = xobjdict),
    )
Esempio n. 47
0
    def __init__(self, filename_or_object, width=None, height=None, kind='direct'):
        # If using StringIO buffer, set pointer to begining
        if hasattr(filename_or_object, 'read'):
            filename_or_object.seek(0)
        page = PdfReader(filename_or_object, decompress=False).pages[0]
        self.xobj = pagexobj(page)
        self.imageWidth = width
        self.imageHeight = height
        x1, y1, x2, y2 = self.xobj.BBox

        self._w, self._h = x2 - x1, y2 - y1
        if not self.imageWidth:
            self.imageWidth = self._w
        if not self.imageHeight:
            self.imageHeight = self._h
        self.__ratio = float(self.imageWidth)/self.imageHeight
        if kind in ['direct','absolute'] or width==None or height==None:
            self.drawWidth = width or self.imageWidth
            self.drawHeight = height or self.imageHeight
        elif kind in ['bound','proportional']:
            factor = min(float(width)/self._w,float(height)/self._h)
            self.drawWidth = self._w*factor
            self.drawHeight = self._h*factor
Esempio n. 48
0
def get4(allpages):
    # Pull a maximum of 4 pages off the list
    pages = [pagexobj(x) for x in allpages[:4]]
    del allpages[:4]

    x_max = max(page.BBox[2] for page in pages)
    y_max = max(page.BBox[3] for page in pages)

    stream = []
    xobjdict = PdfDict()
    for index, page in enumerate(pages):
        x = x_max * (index & 1) / 2.0
        y = y_max * (index <= 1) / 2.0
        index = '/P%s' % index
        stream.append('q 0.5 0 0 0.5 %s %s cm %s Do Q\n' % (x, y, index))
        xobjdict[index] = page

    return PdfDict(
        Type = PdfName.Page,
        Contents = PdfDict(stream=''.join(stream)),
        MediaBox = PdfArray([0, 0, x_max, y_max]),
        Resources = PdfDict(XObject = xobjdict),
    )
Esempio n. 49
0
def adjust(page):
    page = pagexobj(page)
    assert page.BBox == [0, 0, 11 * 72, int(8.5 * 72)], page.BBox
    margin = 72 // 2
    old_x, old_y = page.BBox[2] - 2 * margin, page.BBox[3] - 2 * margin

    new_x, new_y = 48 * 72, 36 * 72
    ratio = 1.0 * new_x / old_x
    assert ratio == 1.0 * new_y / old_y

    index = '/BasePage'
    x = -margin * ratio
    y = -margin * ratio
    stream = 'q %0.2f 0 0 %0.2f %s %s cm %s Do Q\n' % (ratio, ratio, x, y, index)
    xobjdict = PdfDict()
    xobjdict[index] = page

    return PdfDict(
        Type = PdfName.Page,
        Contents = PdfDict(stream=stream),
        MediaBox = PdfArray([0, 0, new_x, new_y]),
        Resources = PdfDict(XObject = xobjdict),
    )
Esempio n. 50
0
 def __init__(self, filename_or_object, width=None, height=None, kind='direct'):
     if hasattr(filename_or_object, 'read'):
         filename_or_object.seek(0)
     page = PdfReader(filename_or_object, decompress=False).pages[0]
     self.xobj = pagexobj(page)
     self.dynamic = 0
     # Actual image size
     x1, y1, x2, y2 = self.xobj.BBox
     imgw, imgh = x2 - x1, y2 - y1
     self._imgw, self._imgh = imgw, imgh
     if kind in ['direct', 'absolute']:
         self.drawWidth = width or imgw
         self.drawHeight = height or imgh
     elif kind in ['percentage', '%']:
         self.drawWidth = imgw * width * 0.01
         self.drawHeight = imgh * height * 0.01
     elif kind in ['bound', 'proportional']:
         w, h = width or imgw, height or imgh
         factor = min(float(w) / imgw, float(h) / imgh)
         self.drawWidth = imgw * factor
         self.drawHeight = imgh * factor
     elif kind in ['dynamic']:
         self.dynamic = 1
Esempio n. 51
0
def grid_overlay(infile, outfile=sys.stdout, pagesize=letter, lpi=10):
    """Read PDF file 'infile'. Generates a new PDF file to 'outfile'
    containing the first page (only) of infile, with a 'lpi' grid
    overlaid.
    """

    c = Canvas(outfile, pagesize=pagesize)

    pdf = PdfReader(infile)
    xobj = pagexobj(pdf.pages[0])
    rlobj = makerl(c, xobj)

    c.doForm(rlobj)

    xmax = 9
    ymax = 12

    thickline = 0.5
    thinline = 0.1

    for x in range(0, xmax):
        c.setLineWidth(thickline)
        for xx in range(0, lpi):
            x0 = (x + (float(xx) / lpi)) * inch
            c.line(x0, 0, x0, ymax * inch)
            c.setLineWidth(thinline)

    for y in range(0, ymax):
        c.setLineWidth(thickline)
        for yy in range(0, lpi):
            y0 = (y + (float(yy) / lpi)) * inch
            c.line(0, y0, xmax * inch, y0)
            c.setLineWidth(thinline)

    c.showPage()
    c.save()
Esempio n. 52
0
    def __init__(self, pdfpage, width=None, height=None, kind='direct',hAlign='LEFT',rotation=0):
        # If using StringIO buffer, set pointer to begining
        self.xobj = pagexobj(pdfpage)
        self.rotation = rotation
        self.imageWidth = width
        self.imageHeight = height
        x1, y1, x2, y2 = self.xobj.BBox
        self.hAlign = hAlign

        w, h = x2 - x1, y2 - y1
        self._w = abs(w * cos(radians(rotation)) + h * sin(radians(rotation)))
        self._h = abs(w * sin(radians(rotation)) + h * cos(radians(rotation)))
        if not self.imageWidth:
            self.imageWidth = self._w
        if not self.imageHeight:
            self.imageHeight = self._h
        self.__ratio = float(self.imageWidth)/self.imageHeight
        if kind in ['direct','absolute'] or width==None or height==None:
            self.drawWidth = width or self.imageWidth
            self.drawHeight = height or self.imageHeight
        elif kind in ['bound','proportional']:
            factor = min(float(width)/self._w,float(height)/self._h)
            self.drawWidth = self._w*factor
            self.drawHeight = self._h*factor
	def draw_card_face(self, c, card_face, domain, colour_scheme, frame_layout, page_nr, offset = 0):
		colour = colour_scheme[domain]

		# Colour frame
		c.setFillColorRGB(colour[0], colour[1], colour[2])
		c.roundRect(0 + offset, 0, frame_layout['card']['width']*cm, frame_layout['card']['height']*cm, radius=frame_layout['border']['outer_corner_radius']*cm, stroke=0, fill=1)

		# Content space
		c.setFillColorRGB(1, 1, 1)
		c.roundRect(frame_layout['border']['left']*cm + offset, frame_layout['border']['bottom']*cm, frame_layout['content']['width']*cm, frame_layout['content']['height']*cm, radius=frame_layout['border']['inner_corner_radius']*cm, stroke=0, fill=1)

		# Key ring cut-out: 0 = none, 1 = top left, 2 = top right
		if page_nr == 1:
			c.circle(0, frame_layout['card_spread']['height']*cm, frame_layout['key_ring']['radius']*cm, stroke=0, fill=1)
		elif page_nr == 2:
			c.circle(frame_layout['card_spread']['width']*cm, frame_layout['card_spread']['height']*cm, frame_layout['key_ring']['radius']*cm, stroke=0, fill=1)

		# Domain / Caetgory text
		c.setFont('Helvetica', 10, leading = None)
		c.drawCentredString(frame_layout['card']['width']*cm/2 + offset, frame_layout['card']['height']*cm - 0.47*cm, '- ' + domain.title() + ' -')

		# Header text
		c.setFont('Helvetica-Bold', 20, leading = None)
		c.drawCentredString(frame_layout['card']['width']*cm/2 + offset, frame_layout['card']['height']*cm - 1.23*cm, card_face.header)

		# Footer text
		c.setFont('Helvetica', 8, leading = None)
		c.drawCentredString(frame_layout['card']['width']*cm/2 + offset, 0.15*cm, frame_layout['static_text']['footer'])

		# Include contents
		c.setFillColorRGB(0, 0, 0)
		page = pagexobj(PdfReader(card_face.content_path).pages[0])
		c.saveState()
		c.translate(frame_layout['border']['left']*cm + offset, frame_layout['border']['bottom']*cm)
		c.doForm(makerl(c, page))
		c.restoreState()
Esempio n. 54
0
def bidder_agreement(bidder, output):
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont

    pdfmetrics.registerFont(TTFont(*settings.ARTSHOW_BARCODE_FONT))

    c = Canvas(output, pagesize=letter)
    pdf = PdfReader(settings.ARTSHOW_BLANK_BIDDER_AGREEMENT)
    xobj = pagexobj(pdf.pages[0])
    rlobj = makerl(c, xobj)

    c.translate(0, 5.5 * inch)

    c.doForm(rlobj)
    text_into_box(c, u"*P" + unicode(bidder.person.id) + u"*", 3.5, 4.8, 5.5, 5.05, fontSize=14, style=barcode_style)
    text_into_box(c, "Ref. " + unicode(bidder.person.id), 3.5, 4.55, 5.5, 4.75, fontSize=10)

    text_into_box(c, bidder.person.reg_id, 6.2, 1.35, 7.7, 1.6, fontSize=12)

    text_into_box(c, bidder.person.name, 1.3, 1.4, 5.2, 1.7, fontSize=14)
    text_into_box(c, bidder.at_con_contact, 2.1, 0.5, 5.2, 0.8, fontSize=12)

    c.showPage()
    c.save()
Esempio n. 55
0
out.close()

# be careful if using libreoffice for generating pdf, in olderversions via command line
# it can start differently like loffice libreoffice or similar
os.system("libreoffice5.0 --writer --headless --convert-to pdf %s " % (fname + ".txt"))


# Tnx to this answer for implementing footer and page numbering http://stackoverflow.com/a/28283732/2397101
# this code follows

input_file = fname + ".pdf"
output_file = fname.rstrip("d") + ".pdf"

# Get pages
reader = PdfReader(input_file)
pages = [pagexobj(p) for p in reader.pages]


# Compose new pdf
canvas = Canvas(output_file)

for page_num, page in enumerate(pages, start=1):

    # Add page
    canvas.setPageSize((page.BBox[2], page.BBox[3]))
    canvas.doForm(makerl(canvas, page))

    # Draw footer
    footer_text = "Page %s of %s" % (page_num, len(pages))
    x = 128
    canvas.saveState()
Esempio n. 56
0

if __name__ == "__main__":

    from optparse import OptionParser

    parser = OptionParser(description=__doc__)
    parser.add_option("-i", dest="input_fname", help="file name to be watermarked (pdf)")
    parser.add_option("-w", dest="watermark_fname", help="watermark file name (pdf)")
    parser.add_option("-d", dest="pdfdir", help="watermark all pdf files in this directory")
    parser.add_option("-o", dest="outdir", help="outputdir used with option -d", default="tmp")
    parser.add_option("-s", dest="skip_pages", help="page numbers to be skipped -d", default="")
    options, args = parser.parse_args()

    if options.input_fname and options.watermark_fname:
        watermark = pagexobj(PdfReader(options.watermark_fname, decompress=False).pages[0])
        outfn = "watermark." + os.path.basename(options.input_fname)
        pages = PdfReader(options.input_fname, decompress=False).pages

        skip_pages = [int(y) - 1 for y in filter(lambda x: x != "", options.skip_pages.split(","))]
        new_pages = []
        for i in range(len(pages)):
            if i in skip_pages:
                new_pages.append(pages[i])
            else:
                new_pages.append(fixpage(pages[i], watermark))

        PdfWriter().addpages(new_pages).write(outfn)

    elif options.pdfdir and options.watermark_fname:
        batch_watermark(options.pdfdir, options.watermark_fname, options.outdir)
Esempio n. 57
0
def watermark(input_fname, watermark_fname, output_fname=None):
    outfn = output_fname or ('watermark.' + os.path.basename(input_fname))
    w = pagexobj(PdfReader(watermark_fname).pages[0])
    pages = PdfReader(input_fname).pages
    PdfWriter().addpages([fixpage(x, w) for x in pages]).write(outfn)
    return outfn
Esempio n. 58
0
        except Exception:
            print "%s Failed miserably" %fname
            print traceback.format_exc()[:2000]
            #raise
    
    print "success %.2f%% %s pages" %((float(good_files)/len(fnames))*100, total_pages)
    
if __name__ == "__main__":
    
    from optparse import OptionParser
    parser = OptionParser(description = __doc__)
    parser.add_option('-i', dest='input_fname', help='file name to be watermarked (pdf)')
    parser.add_option('-w', dest='watermark_fname', help='watermark file name (pdf)')
    parser.add_option('-d', dest='pdfdir', help='watermark all pdf files in this directory')
    parser.add_option('-o', dest='outdir', help='outputdir used with option -d', default='tmp')
    options, args = parser.parse_args()
    
    if options.input_fname and options.watermark_fname:
        watermark = pagexobj(PdfReader(options.watermark_fname).pages[0])
        outfn = 'watermark.' + os.path.basename(options.input_fname)
        pages = PdfReader(options.input_fname).pages
        
        PdfWriter().addpages([fixpage(x, watermark) for x in pages]).write(outfn)
    
    elif options.pdfdir and options.watermark_fname:
        batch_watermark(options.pdfdir, options.watermark_fname, options.outdir)
    
    else:
        parser.print_help()
        
        
Esempio n. 59
0
def bid_sheets ( pieces, output ):

    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    pdfmetrics.registerFont(TTFont(*settings.ARTSHOW_BARCODE_FONT))

    c = Canvas(output,pagesize=letter)

    pdf = PdfReader ( settings.ARTSHOW_BLANK_BID_SHEET )
    xobj = pagexobj ( pdf.pages[0] )
    rlobj = makerl ( c, xobj )
    
    nfs_pdf = PdfReader ( settings.ARTSHOW_BLANK_NFS_SHEET )
    nfs_xobj = pagexobj ( nfs_pdf.pages[0] )
    nfs_rlobj = makerl ( c, nfs_xobj )

    sheet_offsets = [
        (0,5.5),
        (4.25,5.5),
        (0,0),
        (4.25,0),
        ]

    sheets_per_page = len(sheet_offsets)
    sheet_num = 0
    pieceiter = iter(pieces)
    if artshow_settings.ARTSHOW_BID_SHEET_PRECOLLATION:
        pieceiter = precollate_pieces(pieceiter)
    last_artist = None
    
    try:
        piece = pieceiter.next ()
        while True:
            try:
                for sheet_num in range(sheets_per_page):
                    if artshow_settings.ARTSHOW_BID_SHEET_PRECOLLATION:
                        if piece is None:
                            piece = pieceiter.next()
                            continue
                    else:
                        if piece.artist != last_artist and sheet_num != 0:
                            continue
                    c.saveState ()
                    c.translate ( sheet_offsets[sheet_num][0]*inch, sheet_offsets[sheet_num][1]*inch )
                    if piece.not_for_sale:
                        c.doForm ( nfs_rlobj )
                    else:
                        c.doForm ( rlobj )
                    c.saveState ()
                    c.setLineWidth ( 4 )
                    c.setFillColorRGB ( 1, 1, 1 )
                    c.setStrokeColorRGB ( 1, 1, 1 )
                    c.roundRect ( 1.1875*inch, 4.4375*inch, 1.75*inch, 0.5*inch, 0.0675*inch, stroke=True, fill=True )
                    c.restoreState ()
                    text_into_box ( c, u"*A"+unicode(piece.artist.artistid)+u"P"+unicode(piece.pieceid)+u"*", 1.3125, 4.6, 2.8125, 4.875, fontSize=13, style=barcode_style )
                    text_into_box ( c, "Artist "+unicode(piece.artist.artistid), 1.25, 4.4375, 2.0, 4.625 )
                    text_into_box ( c, "Piece "+unicode(piece.pieceid), 2.125, 4.4375, 2.875, 4.625 )
                    text_into_box ( c, piece.artist.artistname(), 1.125, 4.125, 3.875, 4.375 )
                    text_into_box ( c, piece.name, 0.75, 3.8125, 3.875, 4.0625 )
                    if piece.not_for_sale:
                        text_into_box ( c, piece.media, 0.875, 3.5, 2.375, 3.75 )
                    else:
                        text_into_box ( c, piece.media, 0.875, 3.5, 3.875, 3.75 )
                        text_into_box ( c, piece.not_for_sale and "NFS" or unicode(piece.min_bid), 3.25, 2.625, 3.75, 3.0 )
                        text_into_box ( c, piece.buy_now and unicode(piece.buy_now) or "N/A", 3.25, 1.9375, 3.75, 2.3125 )
                        text_into_box ( c, "X", 3.375, 0.375, 3.5625, 0.675, style=left_align_style, fontSize=16 )      
                    c.restoreState ()
                    last_artist = piece.artist
                    piece = pieceiter.next ()
            finally:
                c.showPage ()
    except StopIteration:
        pass

    c.save ()
Esempio n. 60
-1
def file_x(route):
    input_file = route
    output_file = route.replace("static","static_pdf")
    print input_file

    # Get pages
    reader = PdfReader(input_file)
    pages = [pagexobj(p) for p in reader.pages]


    # Compose new pdf
    canvas = Canvas(output_file)

    for page_num, page in enumerate(pages, start=1):

        # Add page
        canvas.setPageSize((page.BBox[2], page.BBox[3]))
        canvas.doForm(makerl(canvas, page))

        # Draw footer
        footer_text = "Descargado desde https://UdpCursos.com"
        x = 180
        canvas.saveState()
        canvas.setFont('Times-Roman', 10)
        canvas.drawString(page.BBox[2]-x, 40, footer_text)
        canvas.restoreState()

        canvas.showPage()

    canvas.save()