示例#1
0
def main(args):
    parser = argparse.ArgumentParser(
        description='Amend one page of a pdf document.')
    parser.add_argument('orig_pdf', type=str)
    parser.add_argument('page_num_to_amend', type=int)
    parser.add_argument('-a', '--amend-with', dest='amend_with')
    parser.add_argument('-o', '--output')
    args = parser.parse_args(args)

    page = args.page_num_to_amend
    pidx = page - 1
    main, ext = os.path.splitext(args.orig_pdf)
    new_pdf = args.output or "%s.amended%s" % (main, ext)
    amend_with = args.amend_with or "%s.page-%s.amended%s" % (main, page, ext)

    if os.path.exists(amend_with):
        print("using existing amended page %s" % amend_with)
    else:
        print("%s does not exist; I will now open GIMP so you can edit page #%s in that file." % (amend_with, page))
        print("After you have made your edits, do File -> Overwrite %s, then exit GIMP." % amend_with)
        print("(It's safe to 'Discard Changes' after Overwrite.)")
        input("Press enter to continue and run GIMP ")
        amend_with_png = "%s.page-%s.amended.png" % (main, page)
        C(("convert -density %s -units pixelsperinch" % DENSITY_DPI).split() +
          ['%s[%s]' % (args.orig_pdf, pidx), amend_with_png])
        C(["gimp", amend_with_png])
        C(["convert", amend_with_png, amend_with])

    with open(args.orig_pdf, 'rb') as orig, open(amend_with, 'rb') as new:
        pdf = PdfFileMerger()
        pdf.merge(0, orig, pages = PageRange("0:%s" % pidx))
        pdf.merge(pidx, new)
        pdf.merge(pidx+1, orig, pages = PageRange("%s:" % (pidx+1)))
        pdf.write(new_pdf)
        print("wrote %s" % new_pdf)
示例#2
0
 def pages(self):
     try:
         rng = PageRange(self.pages_edit.text())
         self.colorgood(self.pages_edit)
         return rng
     except:
         self.colorbad(self.pages_edit)
         raise ValueError(
             f'Cannot make valid page range from: {self.pages_edit.text()}')
示例#3
0
def split_pdf(update: Update, context: CallbackContext) -> int:
    result = check_back_user_data(update, context)
    if result is not None:
        return result

    _ = set_lang(update, context)
    message = update.effective_message
    split_range = message.text

    if not PageRange.valid(split_range):
        message.reply_text(
            _(
                "The range is invalid. Try again",
                reply_markup=get_back_markup(update, context),
            ))

        return WAIT_SPLIT_RANGE

    message.reply_text(_("Splitting your PDF file"),
                       reply_markup=ReplyKeyboardRemove())

    with tempfile.NamedTemporaryFile() as tf:
        user_data = context.user_data
        file_id, file_name = user_data[PDF_INFO]
        pdf_reader = open_pdf(update, context, file_id, tf.name)

        if pdf_reader is not None:
            merger = PdfFileMerger()
            merger.append(pdf_reader, pages=PageRange(split_range))
            write_send_pdf(update, context, merger, file_name, "split")

    # Clean up memory
    if user_data[PDF_INFO] == file_id:
        del user_data[PDF_INFO]

    return ConversationHandler.END
示例#4
0
def test_equality():
    pr1 = PageRange(slice(0, 5))
    pr2 = PageRange(slice(0, 5))
    assert pr1 == pr2
示例#5
0
def test_str_init_error():
    init_str = "1-2"
    assert PageRange.valid(init_str) is False
    with pytest.raises(ParseError) as exc:
        PageRange(init_str)
    assert exc.value.args[0] == "1-2"
示例#6
0
def test_str_init(range_str, expected):
    pr = PageRange(range_str)
    assert pr._slice == expected
    assert PageRange.valid
示例#7
0
def test_idempotency():
    pr = PageRange(slice(0, 5))
    pr2 = PageRange(pr)
    assert pr == pr2
示例#8
0
def test_equality_other_objectc():
    pr1 = PageRange(slice(0, 5))
    pr2 = "PageRange(slice(0, 5))"
    assert pr1 != pr2
示例#9
0
def test_str(page_range, expected):
    assert str(PageRange(page_range)) == expected
示例#10
0
    assert pr._slice == expected
    assert PageRange.valid


def test_str_init_error():
    init_str = "1-2"
    assert PageRange.valid(init_str) is False
    with pytest.raises(ParseError) as exc:
        PageRange(init_str)
    assert exc.value.args[0] == "1-2"


@pytest.mark.parametrize(
    "params,expected",
    [
        (["foo.pdf", "1:5"], [("foo.pdf", PageRange("1:5"))]),
        (
            ["foo.pdf", "1:5", "bar.pdf"],
            [("foo.pdf", PageRange("1:5")), ("bar.pdf", PageRange(":"))],
        ),
    ],
)
def test_parse_filename_page_ranges(params, expected):
    assert parse_filename_page_ranges(params) == expected


def test_parse_filename_page_ranges_err():
    with pytest.raises(ValueError):
        parse_filename_page_ranges(["1:5", "foo.pdf"])

示例#11
0
def test_str_init_error():
    init_str = "1-2"
    assert PageRange.valid(init_str) is False
    with pytest.raises(ParseError):
        PageRange(init_str)
示例#12
0
def test_repr(page_range, expected):
    assert repr(PageRange(page_range)) == expected
示例#13
0
def test_addition(a, b, expected):
    pr1 = PageRange(a)
    pr2 = PageRange(b)
    assert pr1 + pr2 == PageRange(expected)
    assert pr2 + pr1 == PageRange(expected)  # addition is commutative
示例#14
0
def test_addition_stride():
    a = PageRange(slice(0, 5, 2))
    b = PageRange(slice(7, 9))
    with pytest.raises(ValueError) as exc:
        a + b
    assert exc.value.args[0] == "Can't add PageRange with stride"
示例#15
0
def test_addition_non_page_range():
    with pytest.raises(TypeError) as exc:
        PageRange(slice(0, 5)) + "2:7"
    assert exc.value.args[0] == "Can't add PageRange and <class 'str'>"
示例#16
0
    assert pr._slice == expected
    assert PageRange.valid


def test_str_init_error():
    init_str = "1-2"
    assert PageRange.valid(init_str) is False
    with pytest.raises(ParseError) as exc:
        PageRange(init_str)
    assert exc.value.args[0] == "1-2"


@pytest.mark.parametrize(
    ("params", "expected"),
    [
        (["foo.pdf", "1:5"], [("foo.pdf", PageRange("1:5"))]),
        (
            ["foo.pdf", "1:5", "bar.pdf"],
            [("foo.pdf", PageRange("1:5")), ("bar.pdf", PageRange(":"))],
        ),
    ],
)
def test_parse_filename_page_ranges(params, expected):
    assert parse_filename_page_ranges(params) == expected


def test_parse_filename_page_ranges_err():
    with pytest.raises(ValueError) as exc:
        parse_filename_page_ranges(["1:5", "foo.pdf"])
    assert (
        exc.value.args[0] == "The first argument must be a filename, not a page range."