insert method

PdfPage insert(
  1. int index, [
  2. Size? size,
  3. PdfMargins? margins,
  4. PdfPageRotateAngle? rotation,
  5. PdfPageOrientation? orientation,
])

Inserts a page at the specified index to the last section in the document.

index - The index of the page in the section. size - The page size. margins - The page margin. rotation - The PDF page rotation angle. orientation - The PDF page orientation.

Implementation

PdfPage insert(int index,
    [Size? size,
    PdfMargins? margins,
    PdfPageRotateAngle? rotation,
    PdfPageOrientation? orientation]) {
  if (size == null || size.isEmpty) {
    size = PdfPageSize.a4;
  }
  rotation ??= PdfPageRotateAngle.rotateAngle0;
  orientation ??= (size.width > size.height)
      ? PdfPageOrientation.landscape
      : PdfPageOrientation.portrait;
  final PdfPage page = PdfPage();
  final PdfPageSettings settings = PdfPageSettings(size, orientation);
  if (margins == null) {
    margins = PdfMargins();
    margins.all = PdfDocumentHelper.defaultMargin;
  }
  settings.margins = margins;
  settings.rotate = rotation;
  final PdfSection sec = PdfSectionHelper.load(_helper.document, settings);
  PdfSectionHelper.getHelper(sec).dropCropBox();
  PdfSectionHelper.getHelper(sec).add(page);
  PdfDictionary dic = IPdfWrapper.getElement(sec)! as PdfDictionary;
  int? localIndex = 0;
  final Map<String, dynamic> result =
      _getValidParent(index, localIndex, false);
  final PdfDictionary parent = result['node'] as PdfDictionary;
  localIndex = result['index'] as int?;
  if (parent.containsKey(PdfDictionaryProperties.rotate)) {
    final int rotationValue = page.rotation.index * 90;
    final PdfNumber parentRotation =
        parent[PdfDictionaryProperties.rotate]! as PdfNumber;
    if (parentRotation.value!.toInt() != rotationValue &&
        (!dic.containsKey(PdfDictionaryProperties.rotate))) {
      PdfPageHelper.getHelper(page)
              .dictionary![PdfDictionaryProperties.rotate] =
          PdfNumber(rotationValue);
    }
  }
  dic[PdfDictionaryProperties.parent] = PdfReferenceHolder(parent);
  final PdfArray kids = _getNodeKids(parent)!;
  kids.insert(localIndex!, PdfReferenceHolder(dic));
  _updateCount(parent);
  dic = IPdfWrapper.getElement(page)! as PdfDictionary;
  _helper._pageCache![dic] = page;
  page.graphics.colorSpace = _helper.document!.colorSpace;
  PdfPageLayerHelper.getHelper(
          PdfGraphicsHelper.getHelper(page.graphics).layer!)
      .colorSpace = _helper.document!.colorSpace;
  return page;
}