Write PDF object to file
    :param pdf_obj: PDF object to be written to file
    :param destination: Desintation path
348618
def write_pdf(pdf_obj, destination):
    
    reader = PdfFileReader(pdf_obj)  # Create new PDF object
    writer = PdfFileWriter()

    page_count = reader.getNumPages()

    # add the "watermark" (which is the new pdf) on the existing page
    for page_number in range(page_count):
        page = reader.getPage(page_number)
        writer.addPage(page)

    # finally, write "output" to a real file
    with open(destination, "wb") as outputStream:
        writer.write(outputStream)
838746
def dump(self, obj, fp):
        
        if not validate(obj, self._raw_schema):
            raise AvroTypeException(self._avro_schema, obj)
        fastavro_write_data(fp, obj, self._raw_schema)
252876
def _write(self, destination: TextIO) -> None:
        
        for line in self.dest_lines:
            destination.write(line + NL)
1029958
def pdf_insert(
    dest: str,
    source: str,
    pages: [str] = None,
    index: int = None,
    output: str = None,
):
    
    if output is not None and os.path.isfile(output):
        ans = input(
            "The file '%s' already exists. "
            "Overwrite? Yes/Abort [Y/a]: " % output
        ).lower()
        if ans not in ["y", ""]:
            return

    writer = PdfFileWriter()
    # read pages from file1
    destfile = open(dest, "rb")
    destreader = PdfFileReader(destfile)
    for page in destreader.pages:
        writer.addPage(page)

    # read pages from file2
    srcfile = open(source, "rb")
    srcreader = PdfFileReader(srcfile)

    # if no page numbers are given insert all pages
    index = limit(index - 1, 0, len(destreader.pages))
    if pages is None:
        for i, page in enumerate(srcreader.pages):
            if index is None:
                writer.addPage(page)
            else:
                writer.insertPage(page, index + i)
    else:
        pages = parse_rangearg(pages, len(srcreader.pages))
        for i, pagenr in enumerate(pages):
            page = srcreader.getPage(pagenr)
            if index is None:
                writer.addPage(page)
            else:
                writer.insertPage(page, index + i)

    if output is None:
        # Write into Temporary File first and then overwrite dest file
        ans = input(
            "Overwrite the file '%s'? Yes/Abort [Y/a]: " % dest
        ).lower()
        if ans in ["y", ""]:
            tempfile = NamedTemporaryFile(delete=False)
            writer.write(tempfile)
            tempfile.close()
            move(tempfile.name, dest)
    else:
        with open(output, "wb") as outfile:
            writer.write(outfile)
    destfile.close()
    srcfile.close()
436518
public <T> void write(final PrintWriter writer, final T object,
			final DataTypeDescriptor<T> descriptor, final boolean indent) {
		try {
			jsonFormat.write(writer, object, descriptor, indent);
		} catch (Exception e) {
			throw propagate(e);
		}
	}
1056176
def save(self, destination: BinaryIO, buffer_size: int=16384) -> None:
        
        close_destination = False
        if isinstance(destination, str):
            destination = open(destination, 'wb')
            close_destination = True
        try:
            copyfileobj(self.stream, destination, buffer_size)
        finally:
            if close_destination:
                destination.close()
459854
public function createFile(PdfTransfer $pdf)
    {
        $this->setHeaderAndFooter($pdf);

        $options = $pdf->getOptions();
        if ($options instanceof \ArrayObject) {
            $options = iterator_to_array($options);
        }

        $targetPath = $pdf->getTargetPath();
        $contentString = $this->renderTemplate($pdf->getContent());

        $this->pdfGenerator->renderFile($contentString, $targetPath, $options);
    }
339334
def write_object(self, obj, parent=None):
        
        # Transform object
        for transformer in self.object_transformers:
            tmp_object = transformer.transform(obj)
            if tmp_object is not obj:
                obj = tmp_object
                break

        self._writeStruct(">B", 1, (self.TC_OBJECT,))
        cls = obj.get_class()
        self.write_classdesc(cls)

        # Add reference
        self.references.append([])
        logging.debug(
            "*** Adding ref 0x%X for object %s",
            len(self.references) - 1 + self.BASE_REFERENCE_IDX,
            obj,
        )

        all_names = collections.deque()
        all_types = collections.deque()
        tmpcls = cls
        while tmpcls:
            all_names.extendleft(reversed(tmpcls.fields_names))
            all_types.extendleft(reversed(tmpcls.fields_types))
            tmpcls = tmpcls.superclass
        del tmpcls

        logging.debug("<=> Field names: %s", all_names)
        logging.debug("<=> Field types: %s", all_types)

        for field_name, field_type in zip(all_names, all_types):
            try:
                logging.debug(
                    "Writing field %s (%s): %s",
                    field_name,
                    field_type,
                    getattr(obj, field_name),
                )
                self._write_value(field_type, getattr(obj, field_name))
            except AttributeError as ex:
                log_error(
                    "No attribute {0} for object {1}\nDir: {2}".format(
                        ex, repr(obj), dir(obj)
                    )
                )
                raise
        del all_names, all_types

        if (
            cls.flags & self.SC_SERIALIZABLE
            and cls.flags & self.SC_WRITE_METHOD
            or cls.flags & self.SC_EXTERNALIZABLE
            and cls.flags & self.SC_BLOCK_DATA
        ):
            for annotation in obj.annotations:
                log_debug(
                    "Write annotation {0} for {1}".format(repr(annotation), repr(obj))
                )
                if annotation is None:
                    self.write_null()
                else:
                    self.writeObject(annotation)
            self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))
1364059
def export_file(self, data_object, destination_directory=None,
                    destination_filename=None, retry=False,
                    export_metadata=False, export_raw_file=True):
        
        if not destination_directory:
            destination_directory = os.getcwd()

        # We get filename from the dataobject
        if not destination_filename:
            destination_filename = data_object['value']['filename']

        destination_file_url = os.path.join(destination_directory,
                                            destination_filename)

        logger.info('Exporting file %s@%s ...' % (
            data_object['value']['filename'],
            data_object['uuid']))

        if export_raw_file:
            destination = File(
                destination_file_url, self.storage_settings, retry=retry)
            if destination.exists():
                raise FileAlreadyExistsError(
                    'File already exists at %s' % destination_file_url)
            logger.info('...copying file to %s' % (
                destination.get_url()))

            # Copy from the first file location
            file_resource = data_object.get('value')
            md5 = file_resource.get('md5')
            source_url = data_object['value']['file_url']
            File(source_url, self.storage_settings, retry=retry).copy_to(
                destination, expected_md5=md5)
            data_object['value'] = self._create_new_file_resource(
                data_object['value'], destination.get_url())
        else:
            logger.info('...skipping raw file')

        if export_metadata:
            data_object['value'].pop('link', None)
            data_object['value'].pop('upload_status', None)
            destination_metadata_url = os.path.join(
                destination_file_url + '.metadata.yaml')
            logger.info('...writing metadata to %s' % destination_metadata_url)
            metadata = yaml.safe_dump(data_object, default_flow_style=False)
            metadata_file = File(destination_metadata_url,
                                 self.storage_settings, retry=retry)
            metadata_file.write(metadata)
        else:
            logger.info('...skipping metadata')

        logger.info('...finished file export')
705911
def write(self):
        
        html = self.render()

        if self.file_type == 'pdf':
            self.write_pdf(html)
        else:
            with codecs.open(self.destination_file, 'w',
                             encoding='utf_8') as outfile:
                outfile.write(html)
1322413
def write(self, document, obj, *args, **kwargs):
        
        try:
            document = IWritableDocument(document)
            mime_type = document.mime_type
            writer = self.lookup_writer(mime_type, obj)
            if not writer:
                msg = ("No adapter found to write object %s to %s document"
                       % (obj.__class__.__name__, mime_type))
                raise NoWriterFoundError(msg)
            return writer.write(document, obj, *args, **kwargs)
        except:
            return defer.fail(Failure())
1139515
def bwrite(stream, obj):
    
    handle = None
    if not hasattr(stream, "write"):
        stream = handle = open(stream, "wb")
    try:
        stream.write(bencode(obj))
    finally:
        if handle:
            handle.close()
882416
def write(obj, filepath):
    
    if not isinstance(obj, Multitrack):
        raise TypeError("Support only `pypianoroll.Multitrack` class objects")
    obj.write(filepath)
285710
def write_export_node_to_file(file_object, export_elements):
        
        for export_element in export_elements:
            # Order,Activity,Condition,Who,Subprocess,Terminated
            file_object.write(
                export_element["Order"] + "," + export_element["Activity"] + "," + export_element["Condition"] + "," +
                export_element["Who"] + "," + export_element["Subprocess"] + "," + export_element["Terminated"] + "\n")
1338082
def _destination_position(pdf, destination):
    
    pagewidth = pdf.getPage(
        pdf.getDestinationPageNumber(destination)
    ).cropBox.lowerRight[0]
    if not destination.left or not destination.top:
        raise IncompleteCoordinatesError(destination)
    # assuming max 2 columns
    column = (2 * destination.left) // pagewidth
    return (pdf.getDestinationPageNumber(destination),
            column, -destination.top, destination.left)
52495
def save_object(self, obj):
        
        obj.pre_save(self.jurisdiction.jurisdiction_id)

        filename = '{0}_{1}.json'.format(obj._type, obj._id).replace('/', '-')

        self.info('save %s %s as %s', obj._type, obj, filename)
        self.debug(json.dumps(OrderedDict(sorted(obj.as_dict().items())),
                              cls=utils.JSONEncoderPlus, indent=4, separators=(',', ': ')))

        self.output_names[obj._type].add(filename)

        with open(os.path.join(self.datadir, filename), 'w') as f:
            json.dump(obj.as_dict(), f, cls=utils.JSONEncoderPlus)

        # validate after writing, allows for inspection on failure
        try:
            obj.validate()
        except ValueError as ve:
            if self.strict_validation:
                raise ve
            else:
                self.warning(ve)

        # after saving and validating, save subordinate objects
        for obj in obj._related:
            self.save_object(obj)
603646
def compress_pdf(pdf_fpath, output_fname=None):
    
    import utool as ut
    ut.assertpath(pdf_fpath)
    suffix = '_' + ut.get_datestamp(False) + '_compressed'
    print('pdf_fpath = %r' % (pdf_fpath,))
    output_pdf_fpath = ut.augpath(pdf_fpath, suffix, newfname=output_fname)
    print('output_pdf_fpath = %r' % (output_pdf_fpath,))
    gs_exe = find_ghostscript_exe()
    cmd_list = (
        gs_exe,
        '-sDEVICE=pdfwrite',
        '-dCompatibilityLevel=1.4',
        '-dNOPAUSE',
        '-dQUIET',
        '-dBATCH',
        '-sOutputFile=' + output_pdf_fpath,
        pdf_fpath
    )
    ut.cmd(*cmd_list)
    return output_pdf_fpath