private boolean calculateNumberOfPages(final Graphics2D g2d, final PageFormat pageFormat) {
    myNumberOfPages = 0;
    final Ref<Boolean> firstPage = new Ref<>(Boolean.TRUE);
    final Ref<RangeMarker> tmpMarker = new Ref<>();
    while (ReadAction.compute(() -> {
      if (firstPage.get()) {
        if (!isValidRange(myRangeToPrint)) {
          return false;
        }
        tmpMarker.set(myDocument.createRangeMarker(myRangeToPrint.getStartOffset(), myRangeToPrint.getEndOffset()));
        firstPage.set(Boolean.FALSE);
      }
      RangeMarker range = tmpMarker.get();
      if (!isValidRange(range)) {
        return false;
      }
      tmpMarker.set(printPage(g2d, pageFormat, range));
      range.dispose();
      return true;
    })) {
      if (myProgress.isCanceled()) {
        return false;
      }
      myNumberOfPages++;
    }
    if (!tmpMarker.isNull()) {
      tmpMarker.get().dispose();
    }
    return true;
  }
private boolean calculateNumberOfPages(final Graphics2D g2d, final PageFormat pageFormat)