after cloning a object, we does not want to clone all the front informations
because it take a lot a time and a lot of memory => we use reference

@param myPdf &$pdf
@access public
183902
public function cloneFontFrom(&$pdf)
    {
        $this->n                = &$pdf->getN();
        $this->fonts            = &$pdf->getFonts();
        $this->FontFiles        = &$pdf->getFontFiles();
        $this->diffs            = &$pdf->getDiffs();
        $this->fontlist         = &$pdf->getFontList();
        $this->numfonts         = &$pdf->getNumFonts();
        $this->fontkeys         = &$pdf->getFontKeys();
        $this->font_obj_ids     = &$pdf->getFontObjIds();
        $this->annotation_fonts = &$pdf->getAnnotFonts();
    }
1167280
public function process_assignfeedback_editpdf_files($data) {
        $data = (object)$data;

        // In this case the id is the old gradeid which will be mapped.
        $this->add_related_files('assignfeedback_editpdf',
            \assignfeedback_editpdf\document_services::FINAL_PDF_FILEAREA, 'grade', null, $data->gradeid);
        $this->add_related_files('assignfeedback_editpdf',
            \assignfeedback_editpdf\document_services::PAGE_IMAGE_READONLY_FILEAREA, 'grade', null, $data->gradeid);
        $this->add_related_files('assignfeedback_editpdf', 'stamps', 'grade', null, $data->gradeid);
    }
738429
protected function setHeaderAndFooter(PdfTransfer $pdf)
    {
        $header = $pdf->getHeader();
        $footer = $pdf->getFooter();

        if ($pdf->getUseDefaultLayout()) {
            $header = $this->config->getDefaultHeader();
            $footer = $this->config->getDefaultFooter();
        }

        if ($header !== null) {
            $headerString = $this->renderTemplate($header);
            $this->pdfGenerator->setHeaderHtml($headerString);
        }

        if ($footer !== null) {
            $footerString = $this->renderTemplate($footer);
            $this->pdfGenerator->setFooterHtml($footerString);
        }
    }
1359787
public function setup(): void
    {
        parent::setup();

        // Setup the PDF class with custom size pages because WT supports more page sizes. If WT sends an unknown size name then the default would be A4
        $this->pdf = new ReportTcpdf($this->orientation, parent::UNITS, [
            $this->page_width,
            $this->page_height,
        ], self::UNICODE, 'UTF-8', self::DISK_CACHE);

        // Setup the PDF margins
        $this->pdf->SetMargins($this->left_margin, $this->top_margin, $this->right_margin);
        $this->pdf->setHeaderMargin($this->header_margin);
        $this->pdf->setFooterMargin($this->footer_margin);
        //Set auto page breaks
        $this->pdf->SetAutoPageBreak(true, $this->bottom_margin);
        // Set font subsetting
        $this->pdf->setFontSubsetting(self::SUBSETTING);
        // Setup PDF compression
        $this->pdf->SetCompression(self::COMPRESSION);
        // Setup RTL support
        $this->pdf->setRTL($this->rtl);
        // Set the document information
        $this->pdf->SetCreator(Webtrees::NAME . ' ' . Webtrees::VERSION);
        $this->pdf->SetAuthor($this->rauthor);
        $this->pdf->SetTitle($this->title);
        $this->pdf->SetSubject($this->rsubject);
        $this->pdf->SetKeywords($this->rkeywords);

        $this->pdf->setReport($this);

        if ($this->show_generated_by) {
            // The default style name for Generated by.... is 'genby'
            $element = new ReportPdfCell(0, 10, 0, 'C', '', 'genby', 1, ReportBaseElement::CURRENT_POSITION, ReportBaseElement::CURRENT_POSITION, 0, 0, '', '', true);
            $element->addText($this->generated_by);
            $element->setUrl(Webtrees::NAME . ' ' . Webtrees::VERSION);
            $this->pdf->addFooter($element);
        }
    }
307057
public function addReference($p1, $p2 = null)
    {
        if (is_array($p1)) {
            $this->addReference(@$p1["local"], @$p1["foreign"]);
        } else {
            if ($p1 instanceof Column) {
                $p1 = $p1->getName();
            }
            if ($p2 instanceof Column) {
                $p2 = $p2->getName();
            }
            $this->localColumns[] = $p1;
            $this->foreignColumns[] = $p2;
        }
    }
772688
function it_should_replace_input_message_references_by_reference_html_link($reference1, $reference2) {
        $reference1->getStartIndice()->willReturn(5);
        $reference1->getEndIndice()->willReturn(10);
        $reference1->getType()->willReturn(ReferenceType::USER);
        $reference1->getData()->willReturn(array(
            "id"          => 6844292,
            "name"        => "John Doe",
            "type"        => "user",
            "offset"      => 5,
            "length"      => 5
        ));

        $reference2->getStartIndice()->willReturn(12);
        $reference2->getEndIndice()->willReturn(17);
        $reference2->getType()->willReturn(ReferenceType::PAGE);
        $reference2->getData()->willReturn(array(
            "id"          => 32425,
            "name"        => "test",
            "type"        => "page",
            "offset"      => 5,
            "length"      => 5
        ));

        $this->format('test @jdoe, @test bar', [$reference2, $reference1])
            ->shouldReturn('test <a href="https://www.facebook.com/6844292" target="_blank">@jdoe</a>, <a href="https://www.facebook.com/32425" target="_blank">@test</a> bar');

        $this->format('foo #média bar', [])
            ->shouldReturn('foo <a href="https://www.facebook.com/hashtag/média" target="_blank">#média</a> bar');

        $this->format('foo http://test.com bar', [])
            ->shouldReturn('foo <a href="http://test.com" target="_blank">http://test.com</a> bar');
    }
1262842
public function handleCopy(CopyEvent $event)
    {
        $document = $event->getDocument();
        if (!$document instanceof ArticleDocument) {
            return;
        }

        $uuid = $event->getCopiedNode()->getIdentifier();
        $this->documents[$uuid] = [
            'uuid' => $uuid,
            'locale' => $document->getLocale(),
        ];
    }
416381
private function renderReference($value, $reference, &$isRendered)
    {
        if ((true === $isRendered) || !isset($reference[$value])) {
            return $value;
        }

        $isRendered = true;

        if (\is_array($reference[$value])) {
            return $reference[$value][0];
        }

        return $reference[$value];
    }
707757
def <<(object)
            owner = object.document

            #
            # Does object belongs to another PDF ?
            #
            if owner and not owner.equal?(self)
                import object
            else
                add_to_revision(object, @revisions.last)
            end
        end
71460
public function onAfterWrite()
    {
        parent::onAfterWrite();

        //creation will only be considered if the object has no folder relation
        if ($this->owner->AssetsFolderID == 0) {
            $url = $this->owner->assetsFolderUrlToBeWritten();

            if ($url) {
                //this creates the directory, and attaches it to the page,
                //as well as saving the object one more time - with the attached folder
                $this->findOrMakeAssetsFolder($url, true);
            }
        }
    }
707855
protected function _prepareSubObj()
    {
        $pdf = null;

        // create the sub object
        self::$_subobj = new Html2Pdf(
            $this->_orientation,
            $this->_format,
            $this->_langue,
            $this->_unicode,
            $this->_encoding,
            array($this->_defaultLeft,$this->_defaultTop,$this->_defaultRight,$this->_defaultBottom),
            $this->_pdfa
        );

        // init
        self::$_subobj->setSentenceMaxLines($this->_sentenceMaxLines);
        self::$_subobj->setTestTdInOnePage($this->_testTdInOnepage);
        self::$_subobj->setTestIsImage($this->_testIsImage);
        self::$_subobj->setDefaultFont($this->_defaultFont);
        self::$_subobj->setFallbackImage($this->_fallbackImage);
        self::$_subobj->parsingCss->css            = &$this->parsingCss->css;
        self::$_subobj->parsingCss->cssKeys        = &$this->parsingCss->cssKeys;

        // add all the extensions
        foreach ($this->extensions as $extension) {
            self::$_subobj->addExtension($extension);
        }

        // clone font from the original PDF
        self::$_subobj->pdf->cloneFontFrom($this->pdf);

        // remove the link to the parent
        self::$_subobj->parsingCss->setPdfParent($pdf);
    }
673942
def setup_output_document(input_doc, tmp_input_doc, metadata_info,
                                                    copy_document_catalog=True):
    """"""
    # NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters
    # seems to cause problems (writer can hang on write), so only one is used.
    # This is why the tmp_input_doc file was created earlier, to get copies of
    # the page objects which are independent of those in input_doc.  An ugly
    # hack for a nasty bug to track down.

    # NOTE: You can get the _root_object attribute (dict for the document
    # catalog) from the output document after calling cloneReaderDocumentRoot
    # or else you can just directly get it from the input_doc.trailer dict, as
    # below (which is from the code for cloneReaderDocumentRoot), but you
    # CANNOT set the full _root_object to be the _root_object attribute for the
    # actual output_doc or else only blank pages show up in acroread (whether
    # or not there is any attempt to explicitly copy the pages over).  The same
    # is true for using cloneDocumentFromReader (which just calls
    # cloneReaderDocumentRoot followed by appendPagesFromReader).  At least the
    # '/Pages' key and value in _root_object cause problems, so they are
    # skipped in the partial copy.  Probably a bug in PyPDF2.  See the original
    # code for the routines on the github pages below.
    #
    # https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/pdf.py
    # https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/generic.py
    #
    # Files still can change zoom mode on clicking outline links, but that is
    # an Adobe implementation problem, and happens even in the uncropped files:
    # https://superuser.com/questions/278302/

    output_doc = PdfFileWriter()

    def root_objects_not_indirect(input_doc, root_object):
        """This can expand some of the `IndirectObject` objects in  a root object to
        see the actual values.  Currently only used for debugging.  May mess up the
        input doc and require a temporary one."""
        if isinstance(root_object, dict):
            return {root_objects_not_indirect(input_doc, key):
                    root_objects_not_indirect(input_doc, value) for
                                                  key, value in root_object.items()}
        elif isinstance(root_object, list):
            return [root_objects_not_indirect(input_doc, item) for item in root_object]
        elif isinstance(root_object, IndirectObject):
            return input_doc.getObject(root_object)
        else:
            return root_object

    doc_cat_whitelist = args.docCatWhitelist.split()
    if "ALL" in doc_cat_whitelist:
        doc_cat_whitelist = ["ALL"]

    doc_cat_blacklist = args.docCatBlacklist.split()
    if "ALL" in doc_cat_blacklist:
        doc_cat_blacklist = ["ALL"]

    # Partially copy over document catalog data from input_doc to output_doc.
    if not copy_document_catalog or (
            not doc_cat_whitelist and doc_cat_blacklist == ["ALL"]):
        # Check this first, to completely skip the possibly problematic code getting
        # document catalog items when possible.  Does not print a skipped list, though.
        if args.verbose:
            print("\nNot copying any document catalog items to the cropped document.")
    else:
        try:
            root_object = input_doc.trailer["/Root"]

            copied_items = []
            skipped_items = []
            for key, value in root_object.items():
                # Some possible keys can be:
                #
                # /Type -- required, must have value /Catalog
                # /Pages -- required, indirect ref to page tree; skip, will change
                # /PageMode -- set to /UseNone, /UseOutlines, /UseThumbs, /Fullscreen,
                #              /UseOC, or /UseAttachments, with /UseNone default.
                # /OpenAction -- action to take when document is opened, like zooming
                # /PageLayout -- set to /SinglePage, /OneColumn, /TwoColumnLeft,
                #                /TwoColumnRight, /TwoPageLeft, /TwoPageRight
                # /Names -- a name dictionary to avoid having to use object numbers
                # /Outlines -- indirect ref to document outline, i.e., bookmarks
                # /Dests -- a dict of destinations in the PDF
                # /ViewerPreferences -- a viewer preferences dict
                # /MetaData -- XMP metadata, as opposed to other metadata
                # /PageLabels -- alternate numbering for pages, only affect PDF viewers
                if key == "/Pages":
                    skipped_items.append(key)
                    continue
                if doc_cat_whitelist != ["ALL"] and key not in doc_cat_whitelist:
                    if doc_cat_blacklist == ["ALL"] or key in doc_cat_blacklist:
                        skipped_items.append(key)
                        continue
                copied_items.append(key)
                output_doc._root_object[NameObject(key)] = value

            if args.verbose:
                print("\nCopied these items from the document catalog:\n   ", end="")
                print(*copied_items)
                print("Skipped copy of these items from the document catalog:\n   ", end="")
                print(*skipped_items)

        except (KeyboardInterrupt, EOFError):
            raise
        except: # Just catch any errors here; don't know which might be raised.
            # On exception just warn and get a new PdfFileWriter object, to be safe.
            print("\nWarning: The document catalog data could not be copied to the"
                  "\nnew, cropped document.  Try fixing the PDF document using"
                  "\n'--gsFix' if you have Ghostscript installed.", file=sys.stderr)
            output_doc = PdfFileWriter()

    #output_doc.appendPagesFromReader(input_doc) # Works, but wait and test more.
    for page in [input_doc.getPage(i) for i in range(input_doc.getNumPages())]:
        output_doc.addPage(page)

    tmp_output_doc = PdfFileWriter()
    #tmp_output_doc.appendPagesFromReader(tmp_input_doc)  # Works, but test more.
    for page in [tmp_input_doc.getPage(i) for i in range(tmp_input_doc.getNumPages())]:
        tmp_output_doc.addPage(page)

    ##
    ## Copy the metadata from input_doc to output_doc, modifying the Producer string
    ## if this program didn't already set it.  Get bool for whether this program
    ## cropped the document already.
    ##

    already_cropped_by_this_program = set_cropped_metadata(input_doc, output_doc,
                                                           metadata_info)
    return output_doc, tmp_output_doc, already_cropped_by_this_program
617474
public function copy($proto){
		$this->id = $proto->id;
		$this->relation_id = $proto->relation_id;
		$this->text = $proto->text;
		$this->data = $proto->data;			
	}
1213276
public function process_assignfeedback_editpdf_pagerotation($data) {
        global $DB;
        $data = (object)$data;
        $oldgradeid = $data->gradeid;
        $data->gradeid = $this->get_mappingid('grade', $oldgradeid);
        $DB->insert_record('assignfeedback_editpdf_rot', $data);
    }
125002
function insert_child_after(Frame $new_child, Frame $ref, $update_node = true) {
    if ( $ref === $this->_last_child ) {
      $this->append_child($new_child, $update_node);
      return;
    }

    if ( is_null($ref) ) {
      $this->prepend_child($new_child, $update_node);
      return;
    }
    
    if ( $ref->_parent !== $this )
      throw new DOMPDF_Exception("Reference child is not a child of this node.");

    // Update the node
    if ( $update_node ) {
      if ( $ref->_next_sibling ) {
        $next_node = $ref->_next_sibling->_node;
        $this->_node->insertBefore($new_child->_node, $next_node);
      } else {
        $new_child->_node = $this->_node->appendChild($new_child);
      }
    }
    
    // Remove the child from its parent
    if ( $new_child->_parent)
      $new_child->_parent->remove_child($new_child, false);
    
    $new_child->_parent = $this;
    $new_child->_prev_sibling = $ref;
    $new_child->_next_sibling = $ref->_next_sibling;

    if ( $ref->_next_sibling ) 
      $ref->_next_sibling->_prev_sibling = $new_child;

    $ref->_next_sibling = $new_child;
  }
50949
function reference(node, clone)
			{
				clone.originalNode = node;
				
				node = node.firstChild;
				var child = clone.firstChild;
				
				while (node != null && child != null)
				{
					reference(node, child);
					node = node.nextSibling;
					child = child.nextSibling;
				}
				
				return clone;
			}
646877
protected function _place_objects() {
		//Helpers::dompdf_debug("trace", "()");

		foreach ($this->_objs as $obj=>$props) {
			//var_dump($props);

			$start = $props["start_page"];
			$where = $props["where"];

			// Place the object on this page if required
			$page_number = $this->_pdf->PageNo();
			if ($page_number >= $start &&
			(($page_number % 2 == 0 && $where == "even") ||
			($page_number % 2 == 1 && $where == "odd") ||
			($where == "all"))) {
				$data = $this->_pdf->getObject($obj);
				//Helpers::dompdf_debug("trace", "object data = " . $data['c']);
				$this->_pdf->setPageBuffer($page_number, $data['c'], true);
			}
		}

	}