Beispiel #1
0
def solve_problems(pdf_file, pages, student_ids, problems, solve, copies_per_student):
    if solve < 0.01:
        # nothing to solve
        return

    with NamedTemporaryFile() as sol_file:
        pdf = canvas.Canvas(sol_file.name, pagesize=A4)

        for id, number_of_copies in zip(student_ids, copies_per_student):
            for _ in range(number_of_copies):
                generate_solution(pdf, pages, id, [p for p in problems if random.random() < solve])

                if pages % 2 == 1:
                    # for an odd number of pages, zesje adds a blank page at the end
                    pdf.showPage()

        pdf.save()

        exam_pdf = PdfReader(pdf_file)
        overlay_pdf = PdfReader(sol_file)

        for page_idx, exam_page in enumerate(exam_pdf.pages):
            overlay_merge = PageMerge().add(overlay_pdf.pages[page_idx])[0]
            exam_merge = PageMerge(exam_page).add(overlay_merge)
            exam_merge.render()

        PdfWriter(pdf_file.name, trailer=exam_pdf).write()
def filigrana(input_file,
              output_file="output.pdf",
              path_filigrana_ver="",
              path_filigrana_or=""):
    reader_input = PdfReader(input_file)
    writer_output = PdfWriter()
    page = reader_input.pages[0]
    w, h = sizepage(page)
    watermark_input = None
    watermark = None
    if int(w) > int(h):
        if path_filigrana_or == "":
            print(
                "Non hai fornito la corretta filigrana o hai dimenticato di fornirla."
            )
        else:
            watermark_input = PdfReader(path_filigrana_or)
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))
    else:
        if path_filigrana_ver == "":
            print(
                "Non hai fornito la corretta filigrana o hai dimenticato di fornirla."
            )
        else:
            watermark_input = PdfReader(path_filigrana_ver)
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))

    for current_page in range(len(reader_input.pages)):
        merger = PageMerge(reader_input.pages[current_page])
        merger.add(watermark).render()
    writer_output.write(output_file, reader_input)
Beispiel #3
0
def main():
    selection, start_page_num, sb_or_count = io_check()
    print(u"稼動中...\n")
    print(u"AddText2PDF by WEN")

    assert path.exists('conf.ini')
    ini_file = 'conf.ini'
    ini_object = IniInfo(ini_file)

    # IO
    input_folder = ini_object.get_input_folder()
    input_file_list = [x for x in listdir(input_folder) if x.endswith('.pdf')]
    input_file = input_file_list[0]
    input_path = path.join(input_folder, input_file)

    output_folder = ini_object.get_output_folder()
    output_file = u'編集済み-' + input_file
    output_path = path.join(output_folder, output_file)

    source_pdf = PdfReader(input_path)
    total_page_num = int(source_pdf.Root.Pages.Count)
    for page_num in range(total_page_num):
        canvas_data = get_canvas_data(selection, sb_or_count,
                                      page_num + int(start_page_num),
                                      ini_object)
        wm_pdf = PdfReader(canvas_data)
        wm_obj = PageMerge().add(wm_pdf.pages[0])[0]
        PageMerge(source_pdf.pages[page_num]).add(wm_obj).render()
    output_data = BytesIO()
    PdfWriter().write(output_data, source_pdf)
    output_data.seek(0)

    save2pdf(output_data, output_path)
Beispiel #4
0
def fixpage(*pages):
    """ Taken from example project in pdfrw.
    Puts two pages together into one
    """
    result = PageMerge() + (x for x in pages if x is not None)
    result[-1].x += result[0].w
    return result.render()
Beispiel #5
0
def filigrana(tipo, opacita, input_file, output_file):
    reader_input = PdfReader(input_file)
    writer_output = PdfWriter()

    page = reader_input.pages[0]
    w, h = sizepage(page)

    if tipo == "logo":
        if int(w) > int(h):
            watermark_input = PdfReader("filigrane/fil_" + str(opacita) +
                                        "_logo_or.pdf")
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))
        else:
            watermark_input = PdfReader("filigrane/fil_" + str(opacita) +
                                        "_logo_ver.pdf")
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))
    else:
        if int(w) > int(h):
            watermark_input = PdfReader("filigrane/fil_" + str(opacita) +
                                        "_or.pdf")
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))
        else:
            watermark_input = PdfReader("filigrane/fil_" + str(opacita) +
                                        "_ver.pdf")
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))

    for current_page in range(len(reader_input.pages)):
        merger = PageMerge(reader_input.pages[current_page])
        merger.add(watermark).render()
    writer_output.write(output_file, reader_input)
Beispiel #6
0
def adjust(page, margin=36, scale=4.8):
    info = PageMerge().add(page)
    x1, y1, x2, y2 = info.xobj_box
    viewrect = (margin, margin, x2 - x1 - 2 * margin, y2 - y1 - 2 * margin)
    page = PageMerge().add(page, viewrect=viewrect)
    page[0].scale(scale)
    return page.render()
Beispiel #7
0
def get_single_side_quire_page(pages):
    number_of_pages = len(pages)

    assert number_of_pages == round(QUIRE_SIZE / 2)

    half_index = round(number_of_pages / 2)

    rotate_all(180, pages[half_index:])

    result = PageMerge() + (x for x in pages if x is not None)

    width = result[0].w
    height = result[0].h

    for i in range(half_index):
        dx = i * width
        dy = height
        result[i].x += dx
        result[i].y += dy

    for i in range(half_index, number_of_pages):
        dx = (i - half_index) * width
        dy = 0
        result[i].x += dx
        result[i].y += dy

    return result.render()
Beispiel #8
0
def save_with_even_pages(exam_id, exam_pdf_file):
    """Save a finalized exam pdf with evem number of pages.

    The exam is saved in the path returned by `get_exam_dir(exam_id)` with the name `exam.pdf`.

    If the pdf has an odd number of pages, an extra blank page is added at the end,
    this is specially usefull for printing and contatenating multiple copies at once.

    Parameters
    ----------
    exam_id : int
        The exam identifier
    exam_pdf_file : str or File like object
        The exam pdf to be saved inthe data directory
    """
    os.makedirs(exam_dir(exam_id), exist_ok=True)
    pdf_path = exam_pdf_path(exam_id)

    exam_pdf = PdfReader(exam_pdf_file)
    pagecount = len(exam_pdf.pages)

    if (pagecount % 2 == 0):
        exam_pdf_file.seek(0)
        exam_pdf_file.save(pdf_path)
        return

    new = PdfWriter()
    new.addpages(exam_pdf.pages)
    blank = PageMerge()
    box = exam_pdf.pages[0].MediaBox
    blank.mbox = box
    blank = blank.render()
    new.addpage(blank)

    new.write(pdf_path)
Beispiel #9
0
def resize(outpages, output_size):
    current_size = get_media_box_size(outpages)
    o = list(outpages)

    # rotate output_size if outpages would fit better
    out_ratio = output_size[0] / output_size[1]
    cur_ratio = current_size[0] / current_size[1]
    if out_ratio > 1 and cur_ratio <= 1 or out_ratio <= 1 and cur_ratio > 1:
        output_size = list(reversed(output_size))

    scale, x_margin, y_margin = calculate_margins(output_size, current_size)

    for idx, page in enumerate(outpages):
        page = PageMerge().add(page)

        # scale page
        page[0].scale(scale)
        page[0].x += x_margin
        page[0].y += y_margin

        # set new mediabox size
        page.mbox = [0, 0] + output_size

        # replace original with resized page
        o[idx] = page.render()

    return o
Beispiel #10
0
def two_up(data):
    pdf = PdfReader(fdata=data)
    pages = PageMerge() + pdf.pages

    assert len(pages) == 2

    left, right = pages

    rotation = 270
    scale = 0.7071067811865476  # sqrt(0.5)

    x_increment = scale * pages.xobj_box[2]

    left.Rotate = rotation
    left.scale(scale)

    right.Rotate = rotation
    right.scale(scale)
    right.x = x_increment

    writer = PdfWriter()
    writer.addpage(pages.render())

    # retain and update metadata
    pdf.Info.Creator = 'modulo-nic.py %s' % __version__
    writer.trailer.Info = pdf.Info

    sys.stdout.write('Content-Type: application/x-pdf\n\n')
    writer.write(sys.stdout)
Beispiel #11
0
def adjust(page, margin=36, scale=4.8):
    info = PageMerge().add(page)
    x1, y1, x2, y2 = info.xobj_box
    viewrect = (margin, margin, x2 - x1 - 2 * margin, y2 - y1 - 2 * margin)
    page = PageMerge().add(page, viewrect=viewrect)
    page[0].scale(scale)
    return page.render()
Beispiel #12
0
def makeDraft(pdffile, folder=None, printername=None):
    """Make a "draft" version of the given pdf file by adding a watermark.
    Print this file and then delete it. The '.pdf' suffix may be omitted
    in <pdffile>, but the file itself must have this suffix.
    If <folder> is given, <pdffile> is the name of a (pdf-)file within that
    folder. Otherwise <pdffile> is the complete file path.
    If <printername> is given, it must be the name of a known printer.
    If no <printername> is given, the system default printer is used.
    """
    pdffile, filepath = _filecheck(pdffile, folder)
    if not filepath:
        return False

    wmarkfn = Configuration.getFormsDir('Draft.pdf')
    wmark = PageMerge().add(PdfReader(wmarkfn).pages[0])[0]
    underneath = True
    opath = os.path.join(os.path.dirname(filepath), "Entwurf.pdf")
    reader = PdfReader(filepath)
    for page in reader.pages:
        PageMerge(page).add(wmark, prepend=underneath).render()
    PdfWriter().write(opath, reader)
    rc = toPrinter(opath, printername=printername)
    if rc:
        # delete the draft file
        os.remove(opath)
    return rc
def splitpage(src):
    ''' Split a page into two (top and bottom)
    '''
    # Yield a result for each half of the page
    for y_pos in (0, 0.5):

        # Create a blank, unsized destination page.
        page = PageMerge()

        # add a portion of the source page to it as
        # a Form XObject.
        page.add(src, viewrect=(0, y_pos, 1, 0.5))

        # By default, the object we created will be
        # at coordinates (0, 0), which is the lower
        # left corner.  To move it up on the page
        # to the top, we simply use its height
        # (which is half the source page height) as
        # its y value.
        page[0].y = page[0].h

        # When we render the page, the media box will
        # encompass (0, 0) and all the objects we have
        # placed on the page, which means the output
        # page will be the same size as the input page.
        yield page.render()
Beispiel #14
0
def resize(outpages: List, output_size: List[int]) -> List:
    current_size = get_media_box_size(outpages)
    o = list(outpages)

    # rotate output_size if outpages would fit better
    out_ratio = output_size[0] / output_size[1]
    cur_ratio = current_size[0] / current_size[1]
    if out_ratio > 1 and cur_ratio <= 1 or out_ratio <= 1 and cur_ratio > 1:
        output_size = list(reversed(output_size))

    scale, x_margin, y_margin = calculate_margins(output_size, current_size)

    for idx, page in enumerate(outpages):
        page = PageMerge().add(page)

        # scale page
        page[0].scale(scale)
        page[0].x += x_margin
        page[0].y += y_margin

        # set new mediabox size
        page.mbox = [0, 0] + output_size

        # replace original with resized page
        o[idx] = page.render()

    return o
Beispiel #15
0
 def _pdfrw_adjust(self, page):
     info = PageMerge().add(page)
     x1, y1, x2, y2 = info.xobj_box
     viewrect = (self.margin_x, self.margin_y, x2 - x1 - 2 * self.margin_x,
                 y2 - y1 - 2 * self.margin_y)
     page = PageMerge().add(page, viewrect=viewrect)
     page[0].scale(self.scale)
     return page.render()
Beispiel #16
0
 def get4_fedex(srcpages):
     scale = 0.88
     srcpages = PageMerge() + srcpages
     x_increment, y_increment = (scale * i
                                 for i in srcpages.xobj_box[2:])
     for i, page in enumerate(srcpages):
         page.scale(scale)
     return srcpages.render()
Beispiel #17
0
def watermarker(path, watermark, output):
    base_pdf = PdfReader(path)
    watermark_pdf = PdfReader(watermark)
    mark = watermark_pdf.pages[0]
    for page in range(len(base_pdf.pages)):
        merger = PageMerge(base_pdf.pages[page])
        merger.add(mark).render()
    writer = PdfWriter()
    writer.write(output, base_pdf)
Beispiel #18
0
def get4(srcpages):
    scale = 0.5
    srcpages = PageMerge() + srcpages
    x_increment, y_increment = (scale * i for i in srcpages.xobj_box[2:])
    for i, page in enumerate(srcpages):
        page.scale(scale)
        page.x = x_increment if i & 1 else 0
        page.y = 0 if i & 2 else y_increment
    return srcpages.render()
Beispiel #19
0
def get4(srcpages):
    scale = 0.5
    srcpages = PageMerge() + srcpages
    x_increment, y_increment = (scale * i for i in srcpages.xobj_box[2:])
    for i, page in enumerate(srcpages):
        page.scale(scale)
        page.x = x_increment if i & 1 else 0
        page.y = 0 if i & 2 else y_increment
    return srcpages.render()
Beispiel #20
0
def fixpage(page, count=[0]):
    count[0] += 1
    oddpage = (count[0] & 1)

    result = PageMerge()
    for rotation in (180 + 180 * oddpage, 180 * oddpage):
        result.add(page, rotate=rotation)
    result[1].x = result[0].w
    return result.render()
Beispiel #21
0
 def splitPage(page):
     '''
     Split a page into two (left and right)
     '''
     # return two half of the page
     leftHalf = PageMerge().add(page, viewrect=(0, 0, 0.5, 1)).render()
     rightHalf = PageMerge().add(page, viewrect=(0.5, 0, 0.5, 1)).render()
     # page=[leftHalf, rightHalf]
     return leftHalf, rightHalf
Beispiel #22
0
    def watermark(self):
        ipdf = PdfReader('1.pdf')
        wpdf = PdfReader('watermark.pdf')
        wmark = PageMerge().add(wpdf.pages[0])[0]

        for page in ipdf.pages:
            PageMerge(page).add(wmark).render()

        PdfWriter().write('merged.pdf', ipdf)
Beispiel #23
0
def filigrana(input_file, output_file, chat_id):
    reader_input = PdfReader(input_file)
    writer_output = PdfWriter()

    page = reader_input.pages[0]
    w, h = sizepage(page)
    try:
        logo = open(
            "/home/{user}/{path}/converter_bot/" + str(chat_id) +
            "_logo_settings.txt", "r")
        setting = logo.read()
        logo.close()
    except IOError:
        logo = open(
            "/home/{user}/{path}/converter_bot/" + str(chat_id) +
            "_logo_settings.txt", "w")
        logo.write("on")
        setting = "on"

    try:
        opacity = open(
            "/home/{user}/{path}/converter_bot/" + str(chat_id) +
            "_opacity_settings.txt", "r")
        value_opacity = opacity.read()
        opacity.close()
    except IOError:
        opacity = open(
            "/home/{user}/{path}/converter_bot/" + str(chat_id) +
            "_opacity_settings.txt", "w")
        opacity.write("25")
        opacity.close()
        value_opacity = 25

    if setting == "on":
        if int(w) > int(h):
            watermark_input = PdfReader("/home/{user}/{path}/filigrane/fil_" +
                                        str(value_opacity) + "_logo_or.pdf")
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))
        else:
            watermark_input = PdfReader("/home/{user}/{path}/filigrane/fil_" +
                                        str(value_opacity) + "_logo_ver.pdf")
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))
    else:
        if int(w) > int(h):
            watermark_input = PdfReader("/home/{user}/{path}/filigrane/fil_" +
                                        str(value_opacity) + "_or.pdf")
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))
        else:
            watermark_input = PdfReader("/home/{user}/{path}/filigrane/fil_" +
                                        str(value_opacity) + "_ver.pdf")
            watermark = fixpage(watermark_input.pages[0], int(w), int(h))

    for current_page in range(len(reader_input.pages)):
        merger = PageMerge(reader_input.pages[current_page])
        merger.add(watermark).render()
    writer_output.write(output_file, reader_input)
Beispiel #24
0
def merge(overlay_canvas: io.BytesIO, template_path: str) -> io.BytesIO:
    template_pdf = PdfReader(template_path)
    overlay_pdf = PdfReader(overlay_canvas)
    for page, data in zip(template_pdf.pages, overlay_pdf.pages):
        overlay = PageMerge().add(data)[0]
        PageMerge(page).add(overlay).render()
    form = io.BytesIO()
    PdfWriter().write(form, template_pdf)
    form.seek(0)
    return form
Beispiel #25
0
def get2(srcpages):
    scale = 0.5
    srcpages = PageMerge() + srcpages.pages[:2]
    x_increment, y_increment = (scale * i for i in srcpages.xobj_box[2:])
    for i, page in enumerate(srcpages):
        page.scale(scale)
        page.x = 0 if i == 0 else x_increment
        page.y = 0

    return srcpages.render()
Beispiel #26
0
    def sign(self, event):

        #save signature biometric data in meta headers and draw signature image to pdf
        try:
            #clear tkinter signature canvas
            self.tkinter_signature_canvas.delete("all")

            templete_bytes = BytesIO()
            templete_bytes.write(self.pdf_to_sign)

            templete_bytes.seek(0)

            # open templete,write biometric data and save to new virual file
            trailer = PdfReader(templete_bytes)
            #
            #
            #
            trailer.Info.biometric_date = str(self.biometric_data)
            PdfWriter(templete_bytes, trailer=trailer).write()

            # signature_canvas.drawPath()
            self.signature_canvas.save()

            #set position to 0
            self.singature_bytes.seek(0)
            templete_bytes.seek(0)

            #merge signature and templete dpf bytes
            signature = PageMerge().add(
                PdfReader(self.singature_bytes).pages[0])[0]
            # trailer = PdfReader(templete_bytes)

            #add signature to all pages
            for page in trailer.pages:
                PageMerge(page).add(signature).render()

            #save merged result to new res.pdf file

            res_bytes = BytesIO()
            # PdfWriter('res.pdf', trailer=trailer).write()
            PdfWriter(res_bytes, trailer=trailer).write()
            res_bytes.seek(0)
            self.bytes = res_bytes.getvalue()
            res_bytes.close()

        except Exception as e:
            print(e)
        finally:

            #clear global variables and define again
            self.singature_bytes.close()
            templete_bytes.close()
            self.reinit_global_var()

            self.localstatus = False
Beispiel #27
0
        def get4_fedex(srcpages):
            scale = 0.88
            srcpages = PageMerge() + srcpages
            x_increment, y_increment = (scale * i for i in srcpages.xobj_box[2:])
            for i, page in enumerate(srcpages):
                page.scale(scale)
                 
#                 page.x = x_increment if i & 1 else 0
#                 page.y = 0 if i & 2 else y_increment
#                 print "parrrrrrrrrrrrrrrrrrrrrr",page.x,page.y
            return srcpages.render()  
Beispiel #28
0
def pdfWaterMark(files_folder):
    water_mark = PageMerge().add(
        PdfReader('%s/wtmrk.pdf' % files_folder).pages[0]
    )[0]

    trailer = PdfReader('%s/mergedPDF.pdf' % files_folder)

    for page in trailer.pages:
        PageMerge(page).add(water_mark, prepend='-u').render()

    PdfWriter("%s/resultPDF.pdf" % (files_folder), trailer=trailer).write()
def place8(srcpages):
    scale = 1
    srcpages = PageMerge() + srcpages
    x_increment, y_increment = (scale * i for i in srcpages.xobj_box[2:])
    for i, page in enumerate(srcpages):
        print(page.w)
        print(page.h)
        page.scale(scale, scale)
        page.x = (i % 4) * x_increment
        page.y = 0 if i < 4 else y_increment
    return srcpages.render()
Beispiel #30
0
def adjust(page, params):
    scale, margin, is_vertical = params
    info = PageMerge().add(page)
    x1, y1, x2, y2 = info.xobj_box
    if is_vertical == 1:
        viewrect = (0, margin / scale, x2, y2 - 2 * margin / scale)
    else:
        viewrect = (margin / scale, 0, x2 - 2 * margin / scale, y2)
    page = PageMerge().add(page, viewrect=viewrect)
    page[0].scale(scale)
    return page.render()
Beispiel #31
0
def pdf(rm_files_path, path_original_pdf, path_annotated_pdf, path_oap_pdf):
    """ Render pdf with annotations. The path_oap_pdf defines the pdf 
        which includes only annotated pages.
    """

    base_pdf = PdfReader(open(path_original_pdf, "rb"))

    # Parse remarkable files and write into pdf
    annotations_pdf = []

    for page_nr in range(base_pdf.numPages):
        rm_file_name = "%s/%d" % (rm_files_path, page_nr)
        rm_file = "%s.rm" % rm_file_name
        if not os.path.exists(rm_file):
            annotations_pdf.append(None)
            continue

        page_layout = base_pdf.pages[page_nr].MediaBox
        crop_box = base_pdf.pages[page_nr].CropBox
        if page_layout is None:
            page_layout = base_pdf.pages[page_nr].ArtBox

            if page_layout is None:
                annotations_pdf.append(None)
                continue

        image_width, image_height = float(page_layout[2]), float(
            page_layout[3])
        annotated_page = _render_rm_file(rm_file_name,
                                         image_width=image_width,
                                         image_height=image_height,
                                         crop_box=crop_box)
        if len(annotated_page.pages) <= 0:
            annotations_pdf.append(None)
        else:
            page = annotated_page.pages[0]
            annotations_pdf.append(page)

    # Merge annotations pdf and original pdf
    writer_full = PdfWriter()
    writer_oap = PdfWriter()
    for i in range(base_pdf.numPages):
        annotations_page = annotations_pdf[i]

        if annotations_page != None:
            merger = PageMerge(base_pdf.pages[i])
            merger.add(annotations_page).render()
            writer_oap.addpage(base_pdf.pages[i])

        writer_full.addpage(base_pdf.pages[i])

    writer_full.write(path_annotated_pdf)
    writer_oap.write(path_oap_pdf)
Beispiel #32
0
def add_page_number(target_file):
    """Helper function to add page numbers to a pdf-file.

    Writes a pdf file containing page numbers.
    """

    from PyPDF2 import PdfFileReader
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import A4
    from pdfrw import PdfReader, PdfWriter, PageMerge

    tmp_pagenum = 'wmark_' + target_file

    # Create object for page numbers
    c = canvas.Canvas(
        tmp_pagenum,
        pagesize=A4,
    )

    # Read the target file
    input_pdf = PdfFileReader(open(target_file, 'rb'))

    # Count number of pages in the target file
    number_of_pages = input_pdf.getNumPages()

    # Loop through all pages in the target file and create a page number
    # in a new file. Not using
    for i in range(input_pdf.getNumPages()):
        text = '- Committee Pack, page ' + str(
            (i + 1)) + ' / ' + str(number_of_pages) + ' -'

        c.setFont("Helvetica", 7)
        c.drawString(
            20,
            8,
            text,
        )
        c.showPage()

    c.save()

    # Open the watermark file
    trailer = PdfReader(target_file)

    # Loop through the target file and append the page number
    for i, page in enumerate(trailer.pages):
        wmark = PageMerge().add(PdfReader(tmp_pagenum).pages[i])[0]

        PageMerge(page).add(wmark, prepend=True).render()
    PdfWriter(target_file, trailer=trailer).write()

    # Cleanup
    os.unlink(tmp_pagenum)
def merge_pdfs(form_pdf, overlay_pdf, output):
    """
    Merge the specified fillable form PDF with the  overlay PDF
    and save the output.
    """
    form = PdfReader(form_pdf)
    olay = PdfReader(overlay_pdf)
    for form_page, overlay_page in zip(form.pages, olay.pages):
        merge_obj = PageMerge()
        overlay = merge_obj.add(overlay_page)[0]
        PageMerge(form_page).add(overlay).render()
    writer = PdfWriter()
    writer.write(output, form)
Beispiel #34
0
 def _merge_overlay(self, overlay):
     """Merge the overlay into the template"""
     # open a copy of the template form to merge in
     self.form.seek(0)
     template = PdfReader(self.form)
     # merge the overlay and template
     overlay_pdf = PdfReader(overlay)
     for t_page, o_page in zip(template.pages, overlay_pdf.pages):
         overlay = PageMerge().add(o_page)[0]
         PageMerge(t_page).add(overlay).render()
     final_form = StringIO()
     PdfWriter().write(final_form, template)
     final_form.seek(0)
     return final_form
Beispiel #35
0
def make_all_up(pages):
    result = PageMerge()
    # note: pagemerge() resizes based on content so we now have a
    # (pagecount)*width by height page.  Ideally we'd then resize the page, but
    # this is fine for now since we can use print to scale in print programs.
    for page in pages:
        # p.scale(0.5)
        result.add(page)
        first_page_added = len(result) == 1
        if first_page_added:
            continue

        added_page = result[-1]
        second_last_page_added = result[-2]
        added_page.x = second_last_page_added.x + second_last_page_added.w

    return result.render()
Beispiel #36
0
def make_card():
  """Render a message via the API, then composite the render on top of an
  existing template, at the correct position.
  """
  # render the message
  message_render = render_handwritten_msg(HANDWRITING_ID, MESSAGE_TO_RENDER)

  # wrap the render and the template files with pdfrw
  template_pdf = PdfReader('template.pdf')
  message_pdf = PdfReader(fdata=message_render)

  # set up our render as a "stamp" to put on the template
  stamp = PageMerge().add(message_pdf.pages[0])[0]
  # x is the distance from the left edge of the template to the left edge of the stamp:
  stamp.x = OFFSET_X_POINTS
  # y is the distance from the bottom edge of the template to the top edge of the stamp:
  stamp.y = CARD_H_POINTS - OFFSET_Y_POINTS
  pm = PageMerge(template_pdf.pages[0])
  pm.add(stamp)
  pm.render()

  PdfWriter().write('out.pdf', template_pdf)
Beispiel #37
0
    def test_is_landscape(self):
        page = PageMerge() + self.portrait_pdf[0]
        self.assertFalse(core.is_landscape(page))

        page.rotate = 90
        page = PageMerge() + page.render()
        self.assertTrue(core.is_landscape(page))

        page.rotate = 90
        page = PageMerge() + page.render()
        self.assertFalse(core.is_landscape(page))

        page.rotate = 90
        page = PageMerge() + page.render()
        self.assertTrue(core.is_landscape(page))

        page = PageMerge() + self.landscape_pdf[0]
        self.assertTrue(core.is_landscape(page))
Beispiel #38
0
def fixpage(*pages):
    result = PageMerge() + (x for x in pages if x is not None)
    result[-1].x += result[0].w
    return result.render()
Beispiel #39
0
parser.add_argument('--evenrev',
                    dest='evenrev',
                    action='store_const',
                    const=True,
                    default=False,
                    help='reverses the even pages before shuffling')

args = parser.parse_args()

# The shuffling magic
even = PdfReader(args.evenFile[0])
odd = PdfReader(args.oddFile[0])
isEvenReversed = args.evenrev;
isOddReversed = args.oddrev;
all = PdfWriter()
blank = PageMerge()
blank.mbox = [0, 0, 612, 792] # 8.5 x 11
blank = blank.render()

if isEvenReversed and not isOddReversed:
    for i in range(0, len(odd.pages)):
        all.addpage(odd.pages[i])
        all.addpage(even.pages[len(even.pages)-1-i])
elif isOddReversed and not isEvenReversed:
    for i in range(0, len(odd.pages)):
        all.addpage(odd.pages[len(odd.pages)-1-i])
        all.addpage(even.pages[i])
elif isEvenReversed and isOddReversed:
    for i in range(0, len(odd.pages)):
        all.addpage(odd.pages[len(odd.pages)-1-i])
        all.addpage(even.pages[len(even.pages)-1-i])
Beispiel #40
0
def merge(pages, rotation, binding):
    page = PageMerge() + (p for p in pages)
    page = set_binding(page, binding, rotation)
    return page.render()
Beispiel #41
0
def create_blank_copy(page):
    blank_page = PageMerge()
    blank_page.mbox = page.MediaBox
    blank_page.rotate = page.Rotate
    return blank_page.render()