Write pdf file(s) to disk using pdfkit.

    Keyword arguments:
    args -- program arguments (dict)
    infilenames -- names of user-inputted and/or downloaded files (list)
    outfilename -- name of output pdf file (str)
505044
def write_pdf_files(args, infilenames, outfilename):
    
    if not outfilename.endswith('.pdf'):
        outfilename = outfilename + '.pdf'
    outfilename = overwrite_file_check(args, outfilename)

    options = {}
    try:
        if args['multiple']:
            # Multiple files are written one at a time, so infilenames will
            # never contain more than one file here
            infilename = infilenames[0]
            if not args['quiet']:
                print('Attempting to write to {0}.'.format(outfilename))
            else:
                options['quiet'] = None

            if args['xpath']:
                # Process HTML with XPath before writing
                html = parse_html(read_files(infilename), args['xpath'])
                if isinstance(html, list):
                    if isinstance(html[0], str):
                        pk.from_string('\n'.join(html), outfilename,
                                       options=options)
                    else:
                        pk.from_string('\n'.join(lh.tostring(x) for x in html),
                                       outfilename, options=options)
                elif isinstance(html, str):
                    pk.from_string(html, outfilename, options=options)
                else:
                    pk.from_string(lh.tostring(html), outfilename,
                                   options=options)
            else:
                pk.from_file(infilename, outfilename, options=options)
        elif args['single']:
            if not args['quiet']:
                print('Attempting to write {0} page(s) to {1}.'
                      .format(len(infilenames), outfilename))
            else:
                options['quiet'] = None

            if args['xpath']:
                # Process HTML with XPath before writing
                html = parse_html(read_files(infilenames), args['xpath'])
                if isinstance(html, list):
                    if isinstance(html[0], str):
                        pk.from_string('\n'.join(html), outfilename,
                                       options=options)
                    else:
                        pk.from_string('\n'.join(lh.tostring(x) for x in html),
                                       outfilename, options=options)
                elif isinstance(html, str):
                    pk.from_string(html, outfilename, options=options)
                else:
                    pk.from_string(lh.tostring(html), outfilename,
                                   options=options)
            else:
                pk.from_file(infilenames, outfilename, options=options)
        return True
    except (OSError, IOError) as err:
        sys.stderr.write('An error occurred while writing {0}:\n{1}'
                         .format(outfilename, str(err)))
        return False
389661
def writeHeaderlet(self,**kwargs):
        
        # Insure filehandle is open and available...
        self.openFile()

        pars = kwargs.copy()
        rms_pars = self.fit['rms_keys']

        str_kw = ['descrip','history','author','hdrfile']
        for kw in str_kw:
            if pars[kw] == '': pars[kw] = None

        # Call function with properly interpreted input parameters
        # Syntax: write_headerlet(filename, hdrname, output, sciext='SCI',
        #                    wcsname=None, wcskey=None, destim=None,
        #                    sipname=None, npolfile=None, d2imfile=None,
        #                    author=None, descrip=None, history=None,
        #                    rms_ra=None, rms_dec=None, nmatch=None, catalog=None,
        #                    attach=True, clobber=False):
        headerlet.write_headerlet(self._im.hdu, pars['hdrname'],
                output=pars['hdrfile'],
                wcsname=None, wcskey=self.next_key, destim=None,
                sipname=None, npolfile=None, d2imfile=None,
                author=pars['author'], descrip=pars['descrip'],
                history=pars['history'],
                nmatch=rms_pars['NMATCH'],catalog=pars['catalog'],
                attach=pars['attach'], clobber=pars['clobber']
            )
1067180
def pdf_merge(inputs: [str], output: str, delete: bool = False):
    
    writer = PdfFileWriter()
    if os.path.isfile(output):
        ans = input(
            "The file '%s' already exists. "
            "Overwrite? Yes/Abort [Y/a]: " % output
        ).lower()
        if ans == "a":
            return

    outputfile = open(output, "wb")
    try:
        infiles = []
        for filename in inputs:
            f = open(filename, "rb")
            reader = PdfFileReader(f)
            for page in reader.pages:
                writer.addPage(page)
            infiles.append(f)
        writer.write(outputfile)
    except FileNotFoundError as e:
        print(e.strerror + ": " + e.filename)
    finally:
        outputfile.close()
        for f in infiles:
            f.close()
    if delete:
        for filename in inputs:
            os.remove(filename)
947814
def output_pdf(html, filename)
      args = command(filename)
      invoke = args.join(' ')

      IO.popen(invoke, "wb+") do |pdf|
        pdf.puts(html)
        pdf.close_write
        pdf.gets(nil)
      end
    end
649716
def file_writeOnce(astr_fileName, astr_val, **kwargs):
    '''
    
    '''

    _str_mode = 'w'
    for key, val in kwargs.items():
        if key == 'mode':   _str_mode   = val

    FILE = open(astr_fileName, _str_mode)
    FILE.write(astr_val)
    FILE.close()
462387
def pdfdump(self, filename = None, **kargs):
        """"""
        d = self._dump_document(**kargs)
        if filename is None:
            filename = get_temp_file(autoext=".pdf")
            d.writePDFfile(filename)
            subprocess.Popen([conf.prog.pdfreader, filename+".pdf"])
        else:
            d.writePDFfile(filename)
        print
778923
def write_files(text, where='.'):
    """"""
    for filename in text:
        target = os.path.join(where, filename)
        write_file(target, text[filename])
145764
def save_as(output_file_path, failure_list=[])
      filestream = FileOutputStream.new(output_file_path)
      copy = PdfCopyFields.new(filestream)

      @files_to_merge.each do |f|
        if File.exists?(f)
          begin
            copy.addDocument(PdfReader.new(f))
          rescue => e
            failure_list << f
            log "PDF::Merger: Invalid PDF: #{f}"
          end
        else
          failure_list << f
          log "PDF::Merger: File does not exist: #{f}"
        end
      end

      if @files_to_merge.size - failure_list.size > 0
        copy.addJavaScript(@js) if @js && !@js.empty?
        copy.close()
        PdfReader.new(output_file_path).getNumberOfPages
      else
        0
      end
    end
1284668
def write_csv_files(args, infilenames, outfilename):
    
    def csv_convert(line):
        """Strip punctuation and insert commas"""
        clean_line = []
        for word in line.split(' '):
            clean_line.append(word.strip(string.punctuation))
        return ', '.join(clean_line)

    if not outfilename.endswith('.csv'):
        outfilename = outfilename + '.csv'
    outfilename = overwrite_file_check(args, outfilename)

    all_text = []  # Text must be aggregated if writing to a single output file
    for i, infilename in enumerate(infilenames):
        parsed_text = get_parsed_text(args, infilename)
        if parsed_text:
            if args['multiple']:
                if not args['quiet']:
                    print('Attempting to write to {0}.'.format(outfilename))

                csv_text = [csv_convert(x) for x in parsed_text]
                print(csv_text)
                write_file(csv_text, outfilename)
            elif args['single']:
                all_text += parsed_text
                # Newline added between multiple files being aggregated
                if len(infilenames) > 1 and i < len(infilenames) - 1:
                    all_text.append('\n')

    # Write all text to a single output file
    if args['single'] and all_text:
        if not args['quiet']:
            print('Attempting to write {0} page(s) to {1}.'
                  .format(len(infilenames), outfilename))

        csv_text = [csv_convert(x) for x in all_text]
        print(csv_text)
        write_file(csv_text, outfilename)
473507
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):
    
    append_memory_pdf_to_writer(input_pdf=input_pdf,
                                writer=output_writer)
434720
def _write_out_argfile(argfile, out, fnargs, parallel, out_keys, input_files, work_dir):
    
    with open(argfile, "w") as out_handle:
        if argfile.endswith(".json"):
            record_name, record_attrs = _get_record_attrs(out_keys)
            if record_name:
                if parallel in ["multi-batch"]:
                    recs = _nested_cwl_record(out, record_attrs, input_files)
                elif parallel in ["single-split", "multi-combined", "multi-parallel", "batch-single",
                                  "single-single"]:
                    recs = [_collapse_to_cwl_record_single(utils.to_single_data(xs), record_attrs, input_files)
                            for xs in out]
                else:
                    samples = [utils.to_single_data(xs) for xs in out]
                    recs = [_collapse_to_cwl_record(samples, record_attrs, input_files)]
                json.dump(_combine_cwl_records(recs, record_name, parallel),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
            elif parallel in ["single-split", "multi-combined", "batch-split"]:
                json.dump(_convert_to_cwl_json([utils.to_single_data(xs) for xs in out], fnargs, input_files),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
            else:
                json.dump(_convert_to_cwl_json(utils.to_single_data(utils.to_single_data(out)), fnargs, input_files),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
        else:
            yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
10971
def merge_pdfs(pdf_names, output) -> None:
    
    merger = PyPDF2.PdfFileMerger()

    for filename in pdf_names:
        merger.append(filename)
    merger.write(output)
    merger.close()
962072
def gswrite(self, fn=None, device='jpeg', res=600, alpha=4, quality=90, gs=None):
        ""
        gs = (gs or self.gs or os.environ.get('gs') or 'gs')
        # count the number of pages
        if fn is None: 
            fn = os.path.splitext(self.fn)[0] + DEVICE_EXTENSIONS[device]
        fn = File(fn=fn).fn     # normalize path
        if not os.path.exists(os.path.dirname(fn)):
            os.makedirs(os.path.dirname(fn))
        log.debug("PDF.gswrite():\n\tself.fn = %s\n\tout fn = %s" % (self.fn, fn))
        if os.path.splitext(self.fn)[-1].lower()=='.pdf':
            cmd = [gs, '-q', '-dNODISPLAY', '-c', 
                    "(%s) (r) file runpdfbegin pdfpagecount = quit" % self.fn]
            log.debug(cmd)
            out = subprocess.check_output(cmd).decode('utf-8').strip()
            if out=='': out = '1'
            pages = int(out)
            log.debug("%d page(s)" % pages)
        else:
            pages = 1
        if pages > 1:
            # add a counter to the filename, which tells gs to create a file for every page in the input
            fb, ext = os.path.splitext(fn)
            n = len(re.split('.', str(pages))) - 1
            counter = "-%%0%dd" % n
            fn = fb + counter + ext

            # remove any existing output filenames that match the pattern
            for existingfn in glob(fb+'*'+ext):
                log.debug("REMOVING %s" % existingfn)
                os.remove(existingfn)

        callargs = [gs, '-q', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dUseCropBox',
                    '-sDEVICE=%s' % device, '-r%d' % res]
        if device=='jpeg': 
            callargs += ['-dJPEGQ=%d' % quality]
        if 'png' in device or 'jpeg' in device or 'tiff' in device: 
            callargs += [
                '-dTextAlphaBits=%d' % alpha,
                '-dGraphicsAlphaBits=%d' % alpha]
        callargs += ['-sOutputFile=%s' % fn, self.fn]
        try:
            log.debug(callargs)
            subprocess.check_output(callargs)
        except subprocess.CalledProcessError as e:
            log.error(callargs)
            log.error(str(e.output, 'utf-8'))
        fns = sorted(glob(re.sub('%\d+d','*', fn)))
        log.debug('\n\t'+'\n\t'.join(fns))
        return fns
934431
def setFilenames( self, filenames ):
        
        mapped = []
        for filename in filenames:
            filename = nativestring(filename)
            if ( not filename ):
                continue
            
            mapped.append(filename)
            if ( len(mapped) == self.maximumLength() ):
                break
        
        self._filenames = mapped
        self.refresh()
446905
public static void writeRAMFiles(DataOutput out, RAMDirectory dir,
      String[] names) throws IOException {
    out.writeInt(names.length);

    for (int i = 0; i < names.length; i++) {
      Text.writeString(out, names[i]);
      long length = dir.fileLength(names[i]);
      out.writeLong(length);

      if (length > 0) {
        // can we avoid the extra copy?
        IndexInput input = null;
        try {
          input = dir.openInput(names[i], BUFFER_SIZE);

          int position = 0;
          byte[] buffer = new byte[BUFFER_SIZE];

          while (position < length) {
            int len =
                position + BUFFER_SIZE <= length ? BUFFER_SIZE
                    : (int) (length - position);
            input.readBytes(buffer, 0, len);
            out.write(buffer, 0, len);
            position += len;
          }
        } finally {
          if (input != null) {
            input.close();
          }
        }
      }
    }
  }
782905
def write_csv_file(output_filename, tpip_pkgs):
    
    dirname = os.path.dirname(os.path.abspath(os.path.expanduser(output_filename)))

    if dirname and not os.path.exists(dirname):
        os.makedirs(dirname)

    with open(output_filename, 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=FIELDNAMES)
        writer.writeheader()
        writer.writerows(tpip_pkgs)
261010
def output(f):
    
    def wrapper(self, *args, **kwargs):
        try:
            text = kwargs.get('text') or args[0]
        except IndexError:
            text = True
        _ = f(self, *args, **kwargs)
        if text:
            return _
        elif _ is not None and isinstance(_, string_types):
            filename = "{}.{}".format(self.filename, f.__name__)
            while exists(filename):
                name, ext = splitext(filename)
                try:
                    name, i = name.split('-')
                    i = int(i) + 1
                except ValueError:
                    i = 2
                filename = "{}-{}".format(name, i) + ext
            with open(filename, 'w') as out:
                out.write(_)
    return wrapper