Add watermark to PDF by merging original PDF and watermark file.
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()
473507
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):
    
    append_memory_pdf_to_writer(input_pdf=input_pdf,
                                writer=output_writer)
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);
            }
        }
    }
439158
public void add(PdfContentByte other) {
        if (other.writer != null && writer != other.writer)
            throw new RuntimeException("Inconsistent writers. Are you mixing two documents?");
        content.append(other.content);
    }
1286696
public function addImageWatermark(Image $image, array $parameters): Image
    {
        $watermark = new Image($this->secret, $parameters['file'], null, $this->autorotate);

        // temporarily enable alphablending to be able to use 32-bit images
        imagealphablending($watermark->getData(), true);
        imagealphablending($image->getData(), true);

        // determine watermark position from config
        if (true === isset($parameters['position'])) {
            $top = intval($parameters['position']['top']) / 100;
            $left = intval($parameters['position']['left']) / 100;
        } else {
            $top = 1;
            $left = 1;
        }

        // determine watermark size from config
        if (true === isset($parameters['size'])) {
            if (self::WATERMARK_SIZE_COVER === $parameters['size']) {
                // cover dimensions are the same as crop dimensions
                $dimensions = $this->getAdjustedImageCropDimensions(
                    $watermark,
                    $image->getWidth(),
                    $image->getHeight(),
                    true
                );
                imagecopyresampled(
                    $image->getData(),
                    $watermark->getData(),
                    0,
                    0,
                    (int)(($watermark->getWidth() - $dimensions['width']) * $left),
                    (int)(($watermark->getHeight() - $dimensions['height']) * $top),
                    $image->getWidth(),
                    $image->getHeight(),
                    $dimensions['width'],
                    $dimensions['height']
                );
            } elseif (self::WATERMARK_SIZE_CONTAIN === $parameters['size']) {
                $dimensions = $this->getAdjustedImageDimensions($watermark, $image->getWidth(), $image->getHeight());
                imagecopyresampled(
                    $image->getData(),
                    $watermark->getData(),
                    (int)(($image->getWidth() - $dimensions['width']) * $left),
                    (int)(($image->getHeight() - $dimensions['height']) * $top),
                    0,
                    0,
                    $dimensions['width'],
                    $dimensions['height'],
                    $watermark->getWidth(),
                    $watermark->getHeight()
                );
            } else {		// percentage
                $dimensions = $this->getAdjustedImageDimensions($watermark, $image->getWidth(), $image->getHeight());
                $dimensions['width'] *= (intval($parameters['size']) / 100);
                $dimensions['height'] *= (intval($parameters['size']) / 100);
                imagecopyresampled(
                    $image->getData(),
                    $watermark->getData(),
                    (int)(($image->getWidth() - $dimensions['width']) * $left),
                    (int)(($image->getHeight() - $dimensions['height']) * $top),
                    0,
                    0,
                    $dimensions['width'],
                    $dimensions['height'],
                    $watermark->getWidth(),
                    $watermark->getHeight()
                );
            }
        } else {
            imagecopy(
                $image->getData(),
                $watermark->getData(),
                (int)(($image->getWidth() - $watermark->getWidth()) * $left),
                (int)(($image->getHeight() - $watermark->getHeight()) * $top),
                0,
                0,
                $watermark->getWidth(),
                $watermark->getHeight()
            );
        }

        // disable alphablending again to be able to save transparency
        imagealphablending($watermark->getData(), false);
        imagealphablending($image->getData(), false);

        return $image;
    }
86681
def overlay_pdfs(top_pdf, bottom_pdf, destination):
    
    drawing = PdfFileReader(top_pdf)  # Create new PDF object
    template = PdfFileReader(bottom_pdf)  # read your existing PDF

    # add the "watermark" (which is the new pdf) on the existing page
    page = template.getPage(0)
    page.mergePage(drawing.getPage(0))
    output = PdfFileWriter()  # Create new PDF file
    output.addPage(page)

    # finally, write "output" to a real file
    with open(destination, "wb") as outputStream:
        output.write(outputStream)
881559
protected void updatePdfImage(  int x0 , int y0 , int x1 , int y1 ) {

		for( int y = y0; y < y1; y++ ) {
			int indexOut = pdf.startIndex + pdf.stride*y + x0;
			for( int x = x0; x < x1; x++ , indexOut++ ) {

				if( pdf.data[indexOut] < 0 )
					pdf.data[indexOut] = targetModel.compute(x, y);
			}
		}

		// update the dirty region
		if( dirty.x0 > x0 )
			dirty.x0 = x0;
		if( dirty.y0 > y0 )
			dirty.y0 = y0;
		if( dirty.x1 < x1 )
			dirty.x1 = x1;
		if( dirty.y1 < y1 )
			dirty.y1 = y1;
	}
286657
public static <K, V> void addMappableCopiesToMap(Collection<Mappable<K, V>> aMappables, Map<K, V> aMap)
	{
		if (aMappables == null || aMap == null)
			return;

		Mappable<K, V> mappable = null;
		Copier previous = null;
		for (Iterator<Mappable<K, V>> i = aMappables.iterator(); i.hasNext();)
		{
			mappable = i.next();

			previous = (Copier) aMap.get(mappable.getKey());

			if (previous != null)
			{
				// copy data
				previous.copy((Copier) mappable);
			}
			else
			{
				// add to map
				aMap.put((K) mappable.getKey(), (V) mappable.getValue());
			}
		}
	}
277750
def combine_pdf_as_bytes(pdfs: List[BytesIO]) -> bytes:
    
    writer = PdfWriter()
    for pdf in pdfs:
        writer.addpages(PdfReader(pdf).pages)
    bio = BytesIO()
    writer.write(bio)
    bio.seek(0)
    output = bio.read()
    bio.close()
    return output
665195
public function watermark() {
		
		$args = func_get_args();

		if(!count($args)) {
			throw new ImageModifierException('Insufficient arguments for watermarking.');
		}
		
		if(!file_exists(realpath($args[0]))) {
			throw new ImageModifierException('Watermark file not found.');
		}
		
		$todo = new \stdClass();

		$todo->method		= __FUNCTION__;
		$todo->parameters	= array($args[0]);

		$this->queue[] = $todo;

	}
919758
def merge(self, dct=None, **kwargs):
        
        if dct is None:
            dct = {}
        if kwargs:
            dct.update(**kwargs)

        for key, value in dct.items():
            if all((
                    isinstance(value, dict),
                    isinstance(self.get(key), Configuration),
                    getattr(self.get(key), "__merge__", True),
            )):
                # recursively merge
                self[key].merge(value)
            elif isinstance(value, list) and isinstance(self.get(key), list):
                # append
                self[key] += value
            else:
                # set the new value
                self[key] = value
374535
def upscale(file_name, scale=1.5, margin_x=0, margin_y=0, suffix='scaled', tempdir=None):
    """"""
    # 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 = PdfFileReader(file_name)
    writer = PdfFileWriter()
    dims = dimensions(file_name)
    target_w = dims['w'] * scale
    target_h = dims['h'] * scale

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

    for page_number in range(page_count):
        wtrmrk = reader.getPage(page_number)

        page = PageObject.createBlankPage(width=target_w, height=target_h)
        page.mergeScaledTranslatedPage(wtrmrk, scale, margin_x, margin_y)
        writer.addPage(page)

    with open(output, "wb") as outputStream:
        writer.write(outputStream)

    return output
741683
def pdfdump(self, filename=None, **kargs):
        
        from scapy.config import conf
        from scapy.utils import get_temp_file, ContextManagerSubprocess
        canvas = self.canvas_dump(**kargs)
        if filename is None:
            fname = get_temp_file(autoext=kargs.get("suffix", ".pdf"))
            canvas.writePDFfile(fname)
            if WINDOWS and conf.prog.pdfreader is None:
                os.startfile(fname)
            else:
                with ContextManagerSubprocess("pdfdump()",
                                              conf.prog.pdfreader):
                    subprocess.Popen([conf.prog.pdfreader, fname])
        else:
            canvas.writePDFfile(filename)
        print()
10971
def merge_pdfs(pdf_names, output) -> None:
    
    merger = PyPDF2.PdfFileMerger()

    for filename in pdf_names:
        merger.append(filename)
    merger.write(output)
    merger.close()
982628
def add_file(self, filename):
        """"""

        assert not self.final, 'Trying to mutate a final graph.'
        self.add_source_file(filename)
        resolved, unresolved = self.get_file_deps(filename)
        self.graph.add_node(filename)
        for f in resolved:
            self.graph.add_node(f)
            self.graph.add_edge(filename, f)
        for imp in unresolved:
            self.broken_deps[filename].add(imp)
1000507
def merge (dst, src):
        """"""
        for key in src.keys():
                if key not in dst:
                        dst[key] = src[key]
964418
public void setWaterMarks(String source, long lwmScn, long hwmScn) {
        WaterMarkEntry e = sourceWaterMarkMap.get(source);
        if (e == null) {
            e = new WaterMarkEntry(source);
            sourceWaterMarkMap.put(source, e);
        }
        e.setLWMScn(lwmScn);
        e.setHWMScn(hwmScn);
    }