Slice each page of the original, to convert to "one real page per PDF
    page". Return the output filename.
7080
def slice_pdf(input_filename: str, output_filename: str,
              slice_horiz: int, slice_vert: int) -> str:
    
    if slice_horiz == 1 and slice_vert == 1:
        log.debug("No slicing required")
        return input_filename  # nothing to do
    log.info("Slicing each source page mv into {} horizontally x {} vertically",
             slice_horiz, slice_vert)
    log.debug("... from {!r} to {!r}", input_filename, output_filename)
    require(MUTOOL, HELP_MISSING_MUTOOL)
    run([
        MUTOOL,
        "poster",
        "-x", str(slice_horiz),
        "-y", str(slice_vert),
        input_filename,
        output_filename
    ])
    return output_filename
1313263
def getPageImageList(self, pno):
        
        if self.isClosed or self.isEncrypted:
            raise ValueError("operation illegal for closed / encrypted doc")
        if self.isPDF:
            return self._getPageInfo(pno, 2)
        return []
599486
def get_pageinfo(input_file, context):
    ""
    pageno = page_number(input_file) - 1
    pageinfo = context.get_pdfinfo()[pageno]
    return pageinfo
1090472
def get_page(pno, zoom = False, max_size = None, first = False):
    
    dlist = dlist_tab[pno]   # get display list of page number
    if not dlist:            # create if not yet there
        dlist_tab[pno] = doc[pno].getDisplayList()
        dlist = dlist_tab[pno]
    r = dlist.rect           # the page rectangle
    clip = r
    # ensure image fits screen:
    # exploit, but do not exceed width or height
    zoom_0 = 1
    if max_size:
        zoom_0 = min(1, max_size[0] / r.width, max_size[1] / r.height)
        if zoom_0 == 1:
            zoom_0 = min(max_size[0] / r.width, max_size[1] / r.height)
    mat_0 = fitz.Matrix(zoom_0, zoom_0)

    if not zoom:             # show total page
        pix = dlist.getPixmap(matrix = mat_0, alpha=False)
    else:
        mp = r.tl + (r.br - r.tl) * 0.5     # page rect center
        w2 = r.width / 2
        h2 = r.height / 2
        clip = r * 0.5
        tl = zoom[0]          # old top-left
        tl.x += zoom[1] * (w2 / 2)
        tl.x = max(0, tl.x)
        tl.x = min(w2, tl.x)
        tl.y += zoom[2] * (h2 / 2)
        tl.y = max(0, tl.y)
        tl.y = min(h2, tl.y)
        clip = fitz.Rect(tl, tl.x + w2, tl.y + h2)

        mat = mat_0 * fitz.Matrix(2, 2)      # zoom matrix
        pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip)

    if first:                     # first call: tkinter still inactive
        img = pix.getPNGData()    # so use fitz png output
    else:                         # else take tk photo image
        pilimg = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
        img = ImageTk.PhotoImage(pilimg)

    return img, clip.tl
1055726
def render(self, filename_root=None, file=None):
        """"""
        self.error = False
        filename_root = Path(filename_root) if filename_root else None
        if filename_root and file is None:
            extension = self.backend_document.extension
            filename = filename_root.with_suffix(extension)
            file = filename.open('wb')
        elif file and filename_root is None:
            filename = getattr(file, 'name', None)
        else:
            raise ValueError("You need to specify either 'filename_root' or "
                             "'file'.")

        def has_converged(part_page_counts):
            """Return `True` if the last rendering iteration converged to a
            stable result.

            Practically, this tests whether the total number of pages and page
            references to document elements have changed since the previous
            rendering iteration."""
            nonlocal prev_number_of_pages, prev_page_references
            return (part_page_counts == prev_number_of_pages and
                    self.page_references == prev_page_references)

        fake_container = FakeContainer(self)
        try:
            self.document_tree.build_document(fake_container)
            (prev_number_of_pages,
             prev_page_references) = self._load_cache(filename_root)

            self.part_page_counts = prev_number_of_pages
            self.prepare(fake_container)
            self.page_elements.clear()
            self.page_references = prev_page_references.copy()
            self.part_page_counts = self._render_pages()
            while not has_converged(self.part_page_counts):
                prev_number_of_pages = self.part_page_counts
                prev_page_references = self.page_references.copy()
                print('Not yet converged, rendering again...')
                del self.backend_document
                self.backend_document = self.backend.Document(self.CREATOR)
                self.part_page_counts = self._render_pages()
            self.create_outlines()
            if filename:
                self._save_cache(filename_root, self.part_page_counts,
                                 self.page_references)
                self.style_log.write_log(filename_root)
                print('Writing output: {}'.format(filename))
            self.backend_document.write(file)
        finally:
            if filename_root:
                file.close()
        return not self.error
1147056
function createPage(filename) {
        let page = {
            path: filename,
            rawContent: fs.readFileSync(filename, "utf8"),
            name: path.basename(filename).replace(/\.[^/.]+$/, ""),
            filename: path.basename(filename),
            folder: path.dirname(filename),
            ext: path.extname(filename),
            userData: {}
        };
        page.isMarkdown = page.ext.toLocaleUpperCase() == ".MD";
        if (page.isMarkdown)
            page.ext = ".html";
        page.template = doT.template(page.rawContent, null, page.userData);
        page.outPath = path.join(path.relative(CONTENT, page.folder), page.name + page.ext);
        page.href = CONFIG.prefix + page.outPath;
        return page;
    }
589351
def upscale(file_name, scale=1.5, margin_x=0, margin_y=0, suffix='scaled', tempdir=None):
    """"""
    def adjust(page):
        info = PageMerge().add(page)
        x1, y1, x2, y2 = info.xobj_box
        viewrect = (margin_x, margin_y, x2 - x1 - 2 * margin_x, y2 - y1 - 2 * margin_y)
        page = PageMerge().add(page, viewrect=viewrect)
        page[0].scale(scale)
        return page.render()

    # Set output file name
    if tempdir:
        output = NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False).name
    elif suffix:
        output = os.path.join(os.path.dirname(file_name), add_suffix(file_name, suffix))
    else:
        output = NamedTemporaryFile(suffix='.pdf').name

    reader = PdfReader(file_name)
    writer = PdfWriter(output)
    for i in list(range(0, len(reader.pages))):
        writer.addpage(adjust(reader.pages[i]))
    writer.trailer.Info = IndirectPdfDict(reader.Info or {})
    writer.write()
    return output
60115
def _get_page_title(self, page):
        
        fname = os.path.join(SOURCE_PATH, '{}.rst'.format(page))
        option_parser = docutils.frontend.OptionParser(
            components=(docutils.parsers.rst.Parser,))
        doc = docutils.utils.new_document(
            '<doc>',
            option_parser.get_default_values())
        with open(fname) as f:
            data = f.read()

        parser = docutils.parsers.rst.Parser()
        # do not generate any warning when parsing the rst
        with open(os.devnull, 'a') as f:
            doc.reporter.stream = f
            parser.parse(data, doc)

        section = next(node for node in doc.children
                       if isinstance(node, docutils.nodes.section))
        title = next(node for node in section.children
                     if isinstance(node, docutils.nodes.title))

        return title.astext()
1198162
def _url_to_epub(
            self):
        
        self.log.debug('starting the ``_url_to_epub`` method')

        from polyglot import htmlCleaner
        cleaner = htmlCleaner(
            log=self.log,
            settings=self.settings,
            url=self.urlOrPath,
            outputDirectory=self.outputDirectory,
            title=self.title,  # SET TO FALSE TO USE WEBPAGE TITLE,
            style=False,  # add simpdf's styling to the HTML document
            metadata=True,  # include metadata in generated HTML (e.g. title),
            h1=False  # include title as H1 at the top of the doc
        )
        html = cleaner.clean()

        if not html:
            return None

        if self.footer:
            footer = self._tmp_html_file(self.footer)
            footer = '"%(footer)s"' % locals()
        else:
            footer = ""

        if self.header:
            header = self._tmp_html_file(self.header)
            header = '"%(header)s"' % locals()
        else:
            header = ""

        # HTML SOURCE FILE
        epub = html.replace(".html", ".epub")
        pandoc = self.settings["executables"]["pandoc"]

        cmd = """%(pandoc)s -S -s -f html -t epub3 %(header)s '%(html)s' %(footer)s -o '%(epub)s' """ % locals(
        )
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        stdout, stderr = p.communicate()
        self.log.debug('output: %(stdout)s' % locals())

        try:
            with open(epub):
                pass
            fileExists = True
        except IOError:
            fileExists = False
            raise IOError(
                "the epub %s does not exist on this machine, here is the failure message: %s" % (epub, stderr))

        os.remove(html)

        self.log.debug('completed the ``_url_to_epub`` method')
        return epub
738284
def get_page_numbers(
        current_page, num_pages,
        extremes=DEFAULT_CALLABLE_EXTREMES,
        arounds=DEFAULT_CALLABLE_AROUNDS,
        arrows=DEFAULT_CALLABLE_ARROWS):
    
    page_range = range(1, num_pages + 1)
    pages = []
    if current_page != 1:
        if arrows:
            pages.append('first')
        pages.append('previous')

    # Get first and last pages (extremes).
    first = page_range[:extremes]
    pages.extend(first)
    last = page_range[-extremes:]

    # Get the current pages (arounds).
    current_start = current_page - 1 - arounds
    if current_start < 0:
        current_start = 0
    current_end = current_page + arounds
    if current_end > num_pages:
        current_end = num_pages
    current = page_range[current_start:current_end]

    # Mix first with current pages.
    to_add = current
    if extremes:
        diff = current[0] - first[-1]
        if diff > 1:
            pages.append(None)
        elif diff < 1:
            to_add = current[abs(diff) + 1:]
    pages.extend(to_add)

    # Mix current with last pages.
    if extremes:
        diff = last[0] - current[-1]
        to_add = last
        if diff > 1:
            pages.append(None)
        elif diff < 1:
            to_add = last[abs(diff) + 1:]
        pages.extend(to_add)

    if current_page != num_pages:
        pages.append('next')
        if arrows:
            pages.append('last')
    return pages
1145588
def get_page_count(filename: str) -> int:
    
    log.debug("Getting page count for {!r}", filename)
    require(PDFTK, HELP_MISSING_PDFTK)
    stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True)
    regex = re.compile(r"^NumberOfPages: (\d+)$", re.MULTILINE)
    m = regex.search(stdout)
    if m:
        return int(m.group(1))
    raise ValueError("Can't get PDF page count for: {!r}".format(filename))
1345094
function getPDFFileNameFromURL(url) {
  var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  //            SCHEME      HOST         1.PATH  2.QUERY   3.REF
  // Pattern to get last matching NAME.pdf
  var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  var splitURI = reURI.exec(url);
  var suggestedFilename = reFilename.exec(splitURI[1]) ||
                           reFilename.exec(splitURI[2]) ||
                           reFilename.exec(splitURI[3]);
  if (suggestedFilename) {
    suggestedFilename = suggestedFilename[0];
    if (suggestedFilename.indexOf('%') !== -1) {
      // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
      try {
        suggestedFilename =
          reFilename.exec(decodeURIComponent(suggestedFilename))[0];
      } catch(e) { // Possible (extremely rare) errors:
        // URIError "Malformed URI", e.g. for "%AA.pdf"
        // TypeError "null has no properties", e.g. for "%2F.pdf"
      }
    }
  }
  return suggestedFilename || 'document.pdf';
}
570170
def get(self):
        
        self.log.debug('starting the ``get`` method')

        # APPEND TO FILENAME?
        if not self.append:
            self.append = ""

        if not self.readability:
            pdfPath = self._print_original_webpage()
        else:
            pdfPath = self._print_parsed_webpage()

        tag(
            log=self.log,
            filepath=pdfPath,
            tags="pop",
            rating=2,
            wherefrom=self.url
        )

        self.log.debug('completed the ``get`` method')
        return pdfPath
1306128
private static Page extractNonEmptyPage(PageBuffer pageBuffer)
    {
        Page page = pageBuffer.poll();
        while (page != null && page.getPositionCount() == 0) {
            page = pageBuffer.poll();
        }
        return page;
    }
1133794
def get_filename(self):
        
        if self.filename is None:
            name = splitext(basename(self.template_name))[0]
            return '{}.pdf'.format(name)

        return self.filename
517045
def _get_page_data(self, pno, zoom=0):
        
        dlist = self.dlist_tab[pno]  # get display list
        if not dlist:  # create if not yet there
            self.dlist_tab[pno] = self.doc[pno].getDisplayList()
            dlist = self.dlist_tab[pno]
        r = dlist.rect  # page rectangle
        mp = r.tl + (r.br - r.tl) * 0.5  # rect middle point
        mt = r.tl + (r.tr - r.tl) * 0.5  # middle of top edge
        ml = r.tl + (r.bl - r.tl) * 0.5  # middle of left edge
        mr = r.tr + (r.br - r.tr) * 0.5  # middle of right egde
        mb = r.bl + (r.br - r.bl) * 0.5  # middle of bottom edge
        mat = fitz.Matrix(2, 2)  # zoom matrix
        if zoom == 1:  # top-left quadrant
            clip = fitz.Rect(r.tl, mp)
        elif zoom == 4:  # bot-right quadrant
            clip = fitz.Rect(mp, r.br)
        elif zoom == 2:  # top-right
            clip = fitz.Rect(mt, mr)
        elif zoom == 3:  # bot-left
            clip = fitz.Rect(ml, mb)
        if zoom == 0:  # total page
            pix = dlist.getPixmap(alpha=False)
        else:
            pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip)
        return pix.getPNGData()
893668
def _dump_to_pages(dump):
  
  pos = 0
  ret = []
  start_tag = u"<page>\n"
  end_tag = u"</page>\n"
  while True:
    start_pos = dump.find(start_tag, pos)
    if start_pos == -1:
      break
    start_pos += len(start_tag)
    end_pos = dump.find(end_tag, start_pos)
    if end_pos == -1:
      break
    ret.append(dump[start_pos:end_pos])
    pos = end_pos + len(end_tag)
  return ret