XXX Proprietary for PDF
778376
def _parseAtFrame(self, src):
        
        src = src[len('@frame '):].lstrip()
        box, src = self._getIdent(src)
        src, properties = self._parseDeclarationGroup(src.lstrip())
        result = [self.cssBuilder.atFrame(box, properties)]
        return src.lstrip(), result
1243985
def compile(options = {})

            load_all_objects unless loaded?

            #
            # A valid document must have at least one page.
            #
            append_page if pages.empty?

            #
            # Allocates object numbers and creates references.
            # Invokes object finalization methods.
            #
            physicalize(options)

            #
            # Sets the PDF version header.
            #
            version, level = version_required
            @header.major_version = version[0,1].to_i
            @header.minor_version = version[2,1].to_i

            set_extension_level(version, level) if level > 0

            self
        end
341227
def export_pdf(self, filename):
        
        self.make_request(
            raw_result=True,
            resource='export',
            filename=filename, 
            headers = {'accept': 'application/pdf'})
633276
def file_claims_pdfa(filename):
    

    with pikepdf.open(filename) as pdf:
        pdfmeta = pdf.open_metadata()
        if not pdfmeta.pdfa_status:
            return {
                'pass': False,
                'output': 'pdf',
                'conformance': 'No PDF/A metadata in XMP',
            }
        valid_part_conforms = {'1A', '1B', '2A', '2B', '2U', '3A', '3B', '3U'}
        conformance = f'PDF/A-{pdfmeta.pdfa_status}'
        pdfa_dict = {}
        if pdfmeta.pdfa_status in valid_part_conforms:
            pdfa_dict['pass'] = True
            pdfa_dict['output'] = 'pdfa'
        pdfa_dict['conformance'] = conformance
    return pdfa_dict
317907
def convert()
      errors = ""
      output = ""
      
      if @user_pwd 
        cmd = "pdftohtml -stdout #{@format} -upw #{@user_pwd}" + ' "' + @path + '"'    
      elsif @owner_pwd 
        cmd = "pdftohtml -stdout #{@format} -opw #{@owner_pwd}" + ' "' + @path + '"'
      else
        cmd = "pdftohtml -stdout #{@format}" + ' "' + @path + '"'
      end
      
      output = `#{cmd} 2>&1`

      if (output.include?("Error: May not be a PDF file"))
        raise PDFToHTMLRError, "Error: May not be a PDF file (continuing anyway)"
      elsif (output.include?("Error:"))
        raise PDFToHTMLRError, output.split("\n").first.to_s.chomp
      else
        return output
      end
    end
910178
def emit_pdf(outputs, options):

    ''''''

    cmd = options.pdf_cmd
    cmd = cmd.replace('%o', options.pdfname)
    if len(outputs) > 2:
        cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...']))
    else:
        cmd_print = cmd.replace('%i', ' '.join(outputs))
    cmd = cmd.replace('%i', ' '.join(outputs))

    if not options.quiet:
        print('running PDF command "{}"...'.format(cmd_print))

    try:
        result = subprocess.call(shlex.split(cmd))
    except OSError:
        result = -1

    if result == 0:
        if not options.quiet:
            print('  wrote', options.pdfname)
    else:
        sys.stderr.write('warning: PDF command failed\n')
609231
def logpdf(self, X):
        
        return invwishart.logpdf(X, df=self.v, scale=self.Psi)
984374
def stitch_pdfs(pdf_list):
  '''  '''
  pdf_merger = PdfFileMerger()
  for pdf in pdf_list:
    pdf_merger.append(pdf)

  with NamedTemporaryFile(prefix='pyglass', suffix='.pdf', delete=False) as tempfileobj:
    dest_path = tempfileobj.name

  pdf_merger.write(dest_path)
  pdf_merger.close()
  return dest_path
1315443
private void generatePdf() {
        File pdfFile = new File(directory, filename + ".pdf");
        try (OutputStream os = new FileOutputStream(pdfFile)) {
            PdfRendererBuilder builder = new PdfRendererBuilder();
            builder.withHtmlContent(getHtmlForPDFConversion(), "file://" + pdfFile.getAbsolutePath()
                    .replaceAll(" ", "%20"));
            builder.toStream(os);
            builder.run();
        } catch (Exception e) {
            log.error(e);
        }
    }
189515
def logpdf(self, x):
        
        if self.transform is not None:
            x = self.transform(x)       
        return (-self.alpha-1)*np.log(x) - (self.beta/float(x))
747103
def check_ocrmypdf(input_file, output_file, *args, env=None):
    ""

    p, out, err = run_ocrmypdf(input_file, output_file, *args, env=env)
    if p.returncode != 0:
        print('stdout\n======')
        print(out)
        print('stderr\n======')
        print(err)
    #assert p.returncode == 0
    #assert os.path.exists(output_file), "Output file not created"
    #assert os.stat(output_file).st_size > 100, "PDF too small or empty"
    return output_file
737916
def has_textonly_pdf():
    
    args_tess = ['tesseract', '--print-parameters', 'pdf']
    params = ''
    try:
        params = check_output(args_tess, universal_newlines=True, stderr=STDOUT)
    except CalledProcessError as e:
        print("Could not --print-parameters from tesseract", file=sys.stderr)
        raise MissingDependencyError from e
    if 'textonly_pdf' in params:
        return True
    return False
1243320
def _resolved_objects(pdf, xobject):
        """"""
        return [pdf.getPage(i).get(xobject) for i in range(pdf.getNumPages())][0]
38251
def generate_pdf(template_id, submission_data, opts = {})
      data, _status_code, _headers = generate_pdf_with_http_info(template_id, submission_data, opts)
      data
    end
760286
def add(self, document, watermark):
        """"""
        # 5a. Create output PDF file name
        output_filename = self.output_filename

        def pypdf3():
            """Much slower than PyPDF3 method."""
            # 5b. Get our files ready
            document_reader = PdfFileReader(document)
            output_file = PdfFileWriter()

            # Number of pages in input document
            page_count = document_reader.getNumPages()

            # Watermark objects
            watermark_reader = PdfFileReader(watermark)
            wtrmrk_page = watermark_reader.getPage(0)
            wtrmrk_width = (wtrmrk_page.mediaBox.getWidth() / 2) + 0
            wtrmrk_height = (wtrmrk_page.mediaBox.getHeight() / 2) + 80
            wtrmrk_rotate = -int(Info(watermark_reader).rotate) if Info(watermark_reader).rotate is not None else 0

            # 5c. Go through all the input file pages to add a watermark to them
            for page_number in range(page_count):
                # Merge the watermark with the page
                if not self.underneath:
                    input_page = document_reader.getPage(page_number)
                    if wtrmrk_rotate is not 0:
                        input_page.mergeRotatedTranslatedPage(wtrmrk_page, wtrmrk_rotate, wtrmrk_width, wtrmrk_height)
                    else:
                        wtrmrk_width = 0
                        wtrmrk_height = 0
                        input_page.mergeTranslatedPage(wtrmrk_page, wtrmrk_width, wtrmrk_height)
                else:
                    size = Info(document_reader).dimensions
                    input_page = PageObject().createBlankPage(document_reader, size['w'], size['h'])
                    if wtrmrk_rotate is not 0:
                        input_page.mergeRotatedTranslatedPage(wtrmrk_page, wtrmrk_rotate, wtrmrk_width, wtrmrk_height)
                    else:
                        wtrmrk_width = 0
                        wtrmrk_height = 0
                        input_page.mergeTranslatedPage(wtrmrk_page, wtrmrk_width, wtrmrk_height)
                    input_page.mergePage(document_reader.getPage(page_number))

                # Add page from input file to output document
                output_file.addPage(input_page)

            # 5d. finally, write "output" to PDF
            with open(output_filename, "wb") as outputStream:
                output_file.write(outputStream)
            return output_filename

        def pdfrw():
            """Faster than PyPDF3 method by as much as 15x."""
            # TODO: Fix issue where watermark is improperly placed on large pagesize PDFs
            # print(Info(document).size)
            # print(Info(watermark).size)
            # print('\n')

            # Open both the source files
            wmark_trailer = PdfReader(watermark)
            trailer = PdfReader(document)

            # Handle different sized pages in same document with
            # a memoization cache, so we don't create more watermark
            # objects than we need to (typically only one per document).

            wmark_page = wmark_trailer.pages[0]
            wmark_cache = {}

            # Process every page
            for pagenum, page in enumerate(trailer.pages, 1):

                # Get the media box of the page, and see
                # if we have a matching watermark in the cache
                mbox = tuple(float(x) for x in page.MediaBox)
                odd = pagenum & 1
                key = mbox, odd
                wmark = wmark_cache.get(key)
                if wmark is None:

                    # Create and cache a new watermark object.
                    wmark = wmark_cache[key] = PageMerge().add(wmark_page)[0]

                    # The math is more complete than it probably needs to be,
                    # because the origin of all pages is almost always (0, 0).
                    # Nonetheless, we illustrate all the values and their names.

                    page_x, page_y, page_x1, page_y1 = mbox
                    page_w = page_x1 - page_x
                    page_h = page_y1 - page_y  # For illustration, not used

                    # Scale the watermark if it is too wide for the page
                    # (Could do the same for height instead if needed)
                    if wmark.w > page_w:
                        wmark.scale(1.0 * page_w / wmark.w)

                    # Always put watermark at the top of the page
                    # (but see horizontal positioning for other ideas)
                    wmark.y += page_y1 - wmark.h

                    # For odd pages, put it at the left of the page,
                    # and for even pages, put it on the right of the page.
                    if odd:
                        wmark.x = page_x
                    else:
                        wmark.x += page_x1 - wmark.w

                    # Optimize the case where the watermark is same width
                    # as page.
                    if page_w == wmark.w:
                        wmark_cache[mbox, not odd] = wmark

                # Add the watermark to the page
                PageMerge(page).add(wmark, prepend=self.underneath).render()

            # Write out the destination file
            PdfWriter(output_filename, trailer=trailer).write()

        if self.method is 'pypdf3':
            return pypdf3()
        else:
            return pdfrw()
450588
def execute
            latex = compile_latex
            Dir.mktmpdir do | dir |
                @pass_count = 0
                @log        = ''
                success     = false
                while log_suggests_rerunning? && @pass_count < 5
                    @pass_count += 1
                    success = execute_xelatex(latex,dir)
                end
                pdf_file = Pathname.new(dir).join( "output.pdf" )
                if success && pdf_file.exist?
                    yield pdf_file
                else
                    errors = @log.scan(/\*\!\s(.*?)\n\s*\n/m).map{|e| e.first.gsub(/\n/,'') }.join("; ")
                    STDERR.puts @log, errors if ErbLatex.config.verbose_logs
                    raise LatexError.new( errors.empty? ? "xelatex compile error" : errors, @log )
                end
            end
        end
1057112
def pdftoxml(pdfdata, options=""):
    """"""
    pdffout = tempfile.NamedTemporaryFile(suffix='.pdf')
    pdffout.write(pdfdata)
    pdffout.flush()

    xmlin = tempfile.NamedTemporaryFile(mode='r', suffix='.xml')
    tmpxml = xmlin.name  # "temph.xml"
    cmd = 'pdftohtml -xml -nodrm -zoom 1.5 -enc UTF-8 -noframes %s "%s" "%s"' % (
        options, pdffout.name, os.path.splitext(tmpxml)[0])
    # can't turn off output, so throw away even stderr yeuch
    cmd = cmd + " >/dev/null 2>&1"
    os.system(cmd)

    pdffout.close()
    #xmlfin = open(tmpxml)
    xmldata = xmlin.read()
    xmlin.close()
    return xmldata.decode('utf-8')