Merges PDF files.

@param inputPdfFiles array of input files
@param outputPdfFile output file
975422
public static void mergePdf(File[] inputPdfFiles, File outputPdfFile) {
        if (PDFBOX.equals(System.getProperty(PDF_LIBRARY))) {
            PdfBoxUtilities.mergePdf(inputPdfFiles, outputPdfFile);
        } else {
            try {
                PdfGsUtilities.mergePdf(inputPdfFiles, outputPdfFile);
            } catch (Exception e) {
                System.setProperty(PDF_LIBRARY, PDFBOX);
                mergePdf(inputPdfFiles, outputPdfFile);
            }
        }
    }
50663
public static void mergeTiff(File[] inputImages, File outputTiff) throws IOException {
        if (inputImages.length == 0) {
            // if no image
            return;
        }

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
        if (!writers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
        }
        ImageWriter writer = writers.next();

        //Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
//        tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // commented out to preserve original sizes

        //Get the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        try (ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff)) {
            writer.setOutput(ios);
            boolean firstPage = true;
            int index = 1;
            for (File inputImage : inputImages) {
                String imageFileFormat = getImageFileFormat(inputImage);
                Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFileFormat);
                if (!readers.hasNext()) {
                    throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
                }
                ImageReader reader = readers.next();
                try (ImageInputStream iis = ImageIO.createImageInputStream(inputImage)) {
                    reader.setInput(iis);
                    int imageTotal = reader.getNumImages(true);
                    for (int i = 0; i < imageTotal; i++) {
                        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                        if (firstPage) {
                            writer.write(streamMetadata, oimage, tiffWriteParam);
                            firstPage = false;
                        } else {
                            writer.writeInsert(index++, oimage, tiffWriteParam);
                        }
                    }
                } finally {
                    if (reader != null) {
                        reader.dispose();
                    }
                }
            }
        } finally {
            writer.dispose();
        }
    }
285787
def merge_required_files(dirnames, out_dir):
    
    # The list of files to merge
    fn_to_merge = ("steps_summary.tex", "excluded_markers.txt",
                   "excluded_samples.txt")

    # Merging the files
    for fn in fn_to_merge:
        o_fn = os.path.join(out_dir, fn)
        with open(o_fn, "w") as o_file:
            for dn in dirnames:
                i_fn = os.path.join(dn, fn)
                with open(i_fn, "r") as i_file:
                    o_file.write(i_file.read())

    # Merging the result summary file
    o_fn = os.path.join(out_dir, "results_summary.txt")
    with open(o_fn, "w") as o_file:
        for i, dn in enumerate(dirnames):
            i_fn = os.path.join(dn, "results_summary.txt")
            with open(i_fn, "r") as i_file:
                if i != 0:
                    # We skip the first 4 lines (file descriptions)
                    [i_file.readline() for i in range(4)]
                o_file.write(i_file.read())

    # Merging the graphic paths file
    graphic_paths = set()
    for dn in dirnames:
        fn = os.path.join(dn, "graphic_paths.txt")
        if os.path.isfile(fn):
            with open(fn, "r") as i_file:
                graphic_paths.update({
                    os.path.join(dn, path)
                    for path in i_file.read().splitlines()
                })
    if len(graphic_paths) > 0:
        with open(os.path.join(out_dir, "graphic_paths.txt"), "w") as o_file:
            for path in sorted(graphic_paths):
                print >>o_file, os.path.relpath(path, out_dir)
896104
def merge(args):
    
    p = OptionParser(merge.__doc__)
    p.set_outfile(outfile="merged_results.delta")
    opts, args = p.parse_args(args)

    if len(args) < 3:
        sys.exit(not p.print_help())

    ref, query = args[:2]
    deltafiles = args[2:]
    outfile = opts.outfile

    ref = get_abs_path(ref)
    query = get_abs_path(query)
    fw = must_open(outfile, "w")
    print(" ".join((ref, query)), file=fw)
    print("NUCMER", file=fw)
    fw.close()

    for d in deltafiles:
        cmd = "awk 'NR > 2 {{print $0}}' {0}".format(d)
        sh(cmd, outfile=outfile, append=True)
411274
public static void mergeFiles(File[] files, File destinationFile, String[] filterRegex) throws IOException {
        if (filterRegex.length < files.length) {
            filterRegex = ArrayUtils.concatArrays(filterRegex, new String[files.length - filterRegex.length]);
        }
        createNewFile(destinationFile);
        int i = 0;
        for (File file : files) {
            mergeFiles(file, destinationFile, filterRegex[i++]);
        }
    }
400340
public static void splitPdf(File inputPdfFile, File outputPdfFile, int firstPage, int lastPage) {
        PDDocument document = null;
        try {
            document = PDDocument.load(inputPdfFile);
            Splitter splitter = new Splitter();

            splitter.setStartPage(firstPage);
            splitter.setEndPage(lastPage);
            splitter.setSplitAtPage(lastPage - firstPage + 1);

            List<PDDocument> documents = splitter.split(document);

            if (documents.size() == 1) {
                PDDocument outputPdf = documents.get(0);
                outputPdf.save(outputPdfFile);
                outputPdf.close();
            } else {
                logger.error("Splitter returned " + documents.size() + " documents rather than expected of 1");
            }
        } catch (IOException ioe) {
            logger.error("Exception splitting PDF => " + ioe);
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (Exception e) {
                }
            }
        }
    }
10971
def merge_pdfs(pdf_names, output) -> None:
    
    merger = PyPDF2.PdfFileMerger()

    for filename in pdf_names:
        merger.append(filename)
    merger.write(output)
    merger.close()
202188
def merge(filehandle_1, filehandle_2, output_filehandle):
    
    line2 = filehandle_2.readline()
    for line1 in filehandle_1.readlines():
        while line2 != '' and line2 <= line1:
            output_filehandle.write(line2)
            line2 = filehandle_2.readline()
        output_filehandle.write(line1)
    while line2 != '':
        output_filehandle.write(line2)
        line2 = filehandle_2.readline()
1077457
private void printMergedCopy(String output) throws IOException, ParserConfigurationException, TransformerConfigurationException, TransformerException {
        tc = "printMergedCopy - ";
        if (debug)
            Tr.info(traceComponent, tc + "Output File: " + output);
        cleanPlugins();
        FileOutputStream fos = new FileOutputStream(output);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = dbf.newDocumentBuilder();
        Document mergeDoc = parser.newDocument();
        final Comment comment = mergeDoc.createComment(" This config file was generated by plugin's merge tool v1.0.0.2 on " +
                                                       new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss z").format(new Date()) + " ");
        mergeDoc.appendChild(comment);

        mergeDoc.appendChild(mergeDoc.importNode(mergeConfigNode, true));
        mergeConfigNode = mergeDoc.getDocumentElement();
        removeComments(parser, mergeDoc);

        mergeConfigNode.appendChild(mergeDoc.importNode(mergeDoc.createComment(" Server Clusters "), true));

        Node[] sc = null;
        sharedPlugins.trimToSize();
        Iterator<PluginInfo> itrSharedPlugins = sharedPlugins.iterator();
        while (itrSharedPlugins.hasNext()) {
            if (failOver)
                sc = (itrSharedPlugins.next()).getFailOverServerClusters();
            else
                sc = (itrSharedPlugins.next()).getSharedServerClusters();

            for (int i = 0; i < sc.length; i++)
                mergeConfigNode.appendChild(mergeDoc.importNode(sc[i], true));
        }

        for (int i = 0; i < plugins.length - paramCnt; i++) {
            if (!plugins[i].getUniquePluginRep().isEmpty()) {
                sc = plugins[i].getUnsharedServerClusters();
                for (int j = 0; j < sc.length; j++)
                    mergeConfigNode.appendChild(mergeDoc.importNode(sc[j], true));
            }
        }

        mergeConfigNode.appendChild(mergeDoc.createComment(" Virtual Host Groups "));

        Node[] vhgs = null;
        itrSharedPlugins = sharedPlugins.iterator();
        while (itrSharedPlugins.hasNext()) {
            vhgs = (itrSharedPlugins.next()).getSharedVHostGrps();
            for (int i = 0; i < vhgs.length; i++) {
                mergeConfigNode.appendChild(mergeDoc.importNode(vhgs[i], true));
            }
        }

        vhgs = null;
        for (int i = 0; i < plugins.length - paramCnt; i++) {
            vhgs = plugins[i].getUnsharedVHostGrp();
            for (int j = 0; j < vhgs.length; j++)
                mergeConfigNode.appendChild(mergeDoc.importNode(vhgs[j], true));
        }

        mergeConfigNode.appendChild(mergeDoc.createComment(" URI Groups "));

        Node[] uriGrps = null;
        itrSharedPlugins = sharedPlugins.iterator();
        while (itrSharedPlugins.hasNext()) {
            uriGrps = (itrSharedPlugins.next()).getUriGrps();
            for (int i = 0; i < uriGrps.length; i++)
                mergeConfigNode.appendChild(mergeDoc.importNode(uriGrps[i], true));
        }

        for (int i = 0; i < plugins.length - paramCnt; i++) {
            uriGrps = plugins[i].getUriGrps();
            for (int j = 0; j < uriGrps.length; j++)
                mergeConfigNode.appendChild(mergeDoc.importNode(uriGrps[j], true));

            //output unqiueUriGrps needed due to vhost def
            uriGrps = plugins[i].getUniqueUriGrps();
            for (int j = 0; j < uriGrps.length; j++)
                mergeConfigNode.appendChild(mergeDoc.importNode(uriGrps[j], true));
        }

        mergeConfigNode.appendChild(mergeDoc.createComment(" Routes "));

        Node[] routes = null;
        itrSharedPlugins = sharedPlugins.iterator();
        while (itrSharedPlugins.hasNext()) {
            routes = (itrSharedPlugins.next()).getRoutes();
            for (int i = 0; i < routes.length; i++)
                mergeConfigNode.appendChild(mergeDoc.importNode(routes[i], true));
        }

        for (int i = 0; i < plugins.length - paramCnt; i++) {
            routes = plugins[i].getRoutes();
            for (int j = 0; j < routes.length; j++)
                mergeConfigNode.appendChild(mergeDoc.importNode(routes[j], true));
        }

        TransformerFactory transfac = TransformerFactory.newInstance();

        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.METHOD, "xml");
        trans.setOutputProperty(OutputKeys.ENCODING, encoding);
        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        //create string from xml tree
        StreamResult result = new StreamResult(fos);
        DOMSource source = new DOMSource(mergeDoc);
        trans.transform(source, result);

        fos.flush();
        fos.close();

        Tr.info(traceComponent, "Merged plugin config file written to " + output);
    }
1147717
public function mergePdfs($pdfs, $opts = array())
	{
		$this->debug->groupCollapsed(__CLASS__.'->'.__FUNCTION__);
		#$this->debug->log('pdfs',$pdfs);
		$return = false;
		$temp_dir = sys_get_temp_dir();
		$opts = array_merge_replace(array(
			'output_file' => 'temporary',	// if null is passed, pdf object will be returned
			/*
			'parameters' => array(
				'license'		=> null,
				'errorpolicy'	=> 'return',
				'SearchPath'	=> $_SERVER['DOCUMENT_ROOT'],
				// 'escapesequence'	=> 'true',
			),
			*/
			'info' => array(),
		), $opts);
		if ($opts['output_file'] == 'temporary') {
			$opts['output_file'] = tempnam($temp_dir, 'pdf');
		}
		$this->debug->log('output_file', $opts['output_file']);
		try {
			$p = getPDFlib();
			if ($p->begin_document($opts['output_file'], 'tempdirname='.$temp_dir)) {
				foreach ($opts['info'] as $k => $v) {
					$p->set_info($k, $v);
				}
				foreach ($pdfs as $pdf) {
					$pdfNo = $this->openPdf($pdf);
					if (!$pdfNo) {
						$this->debug->log('error', 'error opening');
						continue;
					}
					$endpage = $p->pcos_get_number($pdfNo, 'length:pages');
					/*
						Loop over all pages of the input document
					*/
					for ($pageNo = 1; $pageNo <= $endpage; $pageNo++) {
						$page = $p->open_pdi_page($pdfNo, $pageNo, '');
						if (!$page) {
							$this->debug->log('error', 'error opening pageno '.$pageno);
							continue;
						}
						// Dummy $page size; will be adjusted later
						$p->begin_page_ext(10, 10, '');
						/*
						// Create a bookmark with the file name
						if ($pageno == 1) {
							$p->create_bookmark($pdffile, '');
						}
						*/
						/*
							Place the imported $page on the output $page, and
							adjust the $page size
						*/
						$p->fit_pdi_page($page, 0, 0, 'adjustpage');
						$p->close_pdi_page($page);
						$p->end_page_ext('');
					}
					$p->close_pdi_document($pdf_in);
					if (empty($pdf)) {
						// can't delete until closed
						$ret = $p->delete_pvf($this->pvf);
					}
				}
				$p->end_document('');
				if (empty($opts['output_file'])) {
					$this->debug->info('returning raw pdf');
					$return = $p->get_buffer();
				} else {
					$this->debug->info('returning filepath');
					$return = $opts['output_file'];
				}
			} else {
				$this->debug->log('unable to begin pdf');
				$return = false;
			}
			$p->delete();
		} catch (PDFlibException $e) {
			trigger_error('PDFlib exception ['.$e->get_errnum().'] '.$e->get_apiname().' : '.$e->get_errmsg());
		}
		$this->debug->groupEnd();
		return $return;
	}
59530
public static void merge(List<File> inputFiles, File outputFile) throws IOException {
        ImageOutputStream output = null;
        try {
            output = ImageIO.createImageOutputStream(outputFile);

            for (File file : inputFiles) {
                ImageInputStream input = null;
                try {
                    input = ImageIO.createImageInputStream(file);
                    List<TIFFPage> pages = getPages(input);
                    writePages(output, pages);
                }
                finally {
                    if (input != null) {
                        input.close();
                    }
                }
            }
        }
        finally {
            if (output != null) {
                output.flush();
                output.close();
            }
        }
    }
951776
public static void copyStream( File inputFile, File outputFile ) throws IOException {
		InputStream is = new FileInputStream( inputFile );
		try {
			copyStream( is, outputFile );
		} finally {
			is.close();
		}
	}
966302
@Override
    public T merge(Archive<?> source, Filter<ArchivePath> filter) throws IllegalArgumentException {
        return merge(source, new BasicPath(), filter);
    }
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)
439097
public static void mergeTiff(List<IIOImage> imageList, File outputTiff) throws IOException {
        mergeTiff(imageList, outputTiff, null);
    }
1047360
public static void zipFolderToFile(final File pDestinationFile, final File pFolderToZip){
		try {
			//create ZipOutputStream object
			final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(pDestinationFile));

			String baseName = pFolderToZip.getParent();
               if (baseName==null)
                    baseName="";

			addFolderToZip(pFolderToZip, out, baseName);

			StreamUtils.closeStream(out);
		} catch (final FileNotFoundException e) {
			e.printStackTrace();
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}
738441
public static void unZipFiles(InputStream inputStream, File outputFolder) throws IOException {
        ZipInputStream zis = new ZipInputStream(inputStream);
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            File file = new File(outputFolder, ze.getName());
            OutputStream os = new BufferedOutputStream(FileUtils.openOutputStream(file));

            try {
                IOUtils.copy(zis, os);
            } finally {
                IOUtils.closeQuietly(os);
            }

            zis.closeEntry();
            ze = zis.getNextEntry();
        }
    }