Попытка понять алгоритм формирования отчета ...

Обсуждение извечных проблем кларионовских (и не только) отчетов

Модератор: Дед Пахом

Правила форума
При написании вопроса или обсуждении проблемы, не забывайте указывать версию Clarion который Вы используете.
А так же пользуйтесь спец. тегами при вставке исходников!!!
Ответить
Аватара пользователя
Игорь Столяров
Ветеран движения
Сообщения: 7322
Зарегистрирован: 07 Июль 2005, 10:19
Откуда: г. Ростов-на-ДоМу
Благодарил (а): 13 раз
Поблагодарили: 48 раз

Попытка понять алгоритм формирования отчета ...

Сообщение Игорь Столяров »

Привет всем !

Не раз уже замечал - что когда хочешь сделать средствами Clarion, что то нестандартное
(с точки зрения его разработчиков), начинаются, даже не проблемы, а чудеса ... :)
Вопрос чисто теоритический, для обсуждения, если кому-нибудь интересно это интересно.

Есть некий элементарный отчет, в нем итог по листу PageFooter.
По описанию алгоритм формирования печатного листа следующий (упрощенно):
- формируется пустой лист, на него сразу выводится Form (если есть).
- далее перед первым выводом структуры Detail выводится PageHeader (если есть)
- далее осуществляется заполнение зоны печати структурами Detail с учетом Break (если есть)
- когда очередная структура Detail или ее компонент не может быть размещена на печатном листе - печатается PageFooter.
- формирование страницы завершено, добавляется новый лист и все начинается сначала.

Ничего не упустил ? Вроде бы все просто и понятно. Теперь попробуем выйти за рамки этой красивой идеи.
Структура PageFooter использует абсолютные координаты - это нормально и понятно, иначе она не смогла бы, в общем случае, быть напечатана.
Но нигде не сказано, что PageFooter ОБЯЗАТЕЛЬНО должен быть напечатан в одном и том же месте на всех листах.
Пробуем, по какому-нибудь признаку (например данные в выводимом Detail) изменить координаты PageFooter{Prop:YPos}.
Структура PageFooter послушно изменяет местополжение ... но в отчете НА ВСЕХ ЛИСТАХ она оказывается в том месте, которое указано последним !
Причем данные на всех PageFooter соответсвуют своим страницам (например сумма по листу) !

Это полностью не соответсвует алгоритму формирования печатного листа и наводит на мысль, что реальное формирование PageFooter
на всех листах производится только при закрытии отчета по текущим координатам ... Или я в чем-то ошибcя ?

Кто-нибудь знает способ напечатать PageFooter в разных местах на листах одного отчета ? Заранее спасибо .... :)
За теми кто отстал - не возвращаться. (С) Кодекс
BOB
Ветеран
Сообщения: 336
Зарегистрирован: 17 Июль 2005, 5:43

Re: Попытка понять алгоритм формирования отчета ...

Сообщение BOB »

У меня во всех отчетах в PageFooter есть только линия подчеркивания , а настоящий PageFooter печатается как detail c итогами и подписями, перед печатью итогового детайл обнуляю линию подчеркивания в PageFooter и все красиво .
Аватара пользователя
Игорь Столяров
Ветеран движения
Сообщения: 7322
Зарегистрирован: 07 Июль 2005, 10:19
Откуда: г. Ростов-на-ДоМу
Благодарил (а): 13 раз
Поблагодарили: 48 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение Игорь Столяров »

BOB писал(а):а настоящий PageFooter печатается как detail c итогами и подписями
А можно тогда спросить, как определяется момент печати этого Detail ? Т.е. когда лист заполнен и нужно выводить итог по листу и переходить на новый лист ?
За теми кто отстал - не возвращаться. (С) Кодекс
BOB
Ветеран
Сообщения: 336
Зарегистрирован: 17 Июль 2005, 5:43

Re: Попытка понять алгоритм формирования отчета ...

Сообщение BOB »

Лет 15 как убедил бухгалтеров что итог по листу это анахронизм и печатаю только итог по отчету перед endpage.
Аватара пользователя
Игорь Столяров
Ветеран движения
Сообщения: 7322
Зарегистрирован: 07 Июль 2005, 10:19
Откуда: г. Ростов-на-ДоМу
Благодарил (а): 13 раз
Поблагодарили: 48 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение Игорь Столяров »

BOB писал(а):печатаю только итог по отчету перед endpage.
Это уже больше похоже на правду. Давайте я уточню.
Ответы в стиле "а нафиг вообще использовать PageFooter" имеют право на жизнь из-за того, что PageFooter работает через ж ...
Но я пытаюсь разобраться именно с работой структуры REPORT, а мнение отдельных взятых бухгалтеров до того же места ...

К тому же есть варианты отчетов, где PageFooter предлагает уникальные возможности оформления, заменить которые чем либо - сложно.
Использование Detail для вывода итогов - это сразу либо головная боль с расчетом итоговых сумм, либо их тупой расчет вручную и просто печать.
В этом тоже ничего плохого нет - но не всегда подходит и не для всех задач ...
За теми кто отстал - не возвращаться. (С) Кодекс
kreator
✯ Ветеран ✯
Сообщения: 4960
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 6 раз
Поблагодарили: 19 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение kreator »

В Хелпе нашёл:
Page-based Printing



Clarion reports use a page-based printing paradigm instead of the line-based paradigm used by some older report generators. Instead of printing each line as its values are generated, nothing is sent to the printer until an entire page is ready to print. This means that the "print engine" in the Clarion runtime library can do a lot of work for you, based on the attributes you specify in the REPORT structure.

Some of the things that the "print engine" in the Clarion runtime library does for you are:

· Prints "pre-printed" forms on each page, that are then filled in by the data

· Calculates totals (count, sum, average, minimum, maximum)

· Automatically handles page breaks, including page headers and footers

· Automatically handles group breaks, including group headers and footers

· Provides complete widow/orphan control.

This automatic functionality makes the executable code required to print a complex report very small, making your programming job easier. Since the "print engine" is page-based, the concepts of headers and footers lose their context indicating both page positioning and print sequence, and only retain their meaning of print sequence. Headers are printed at the beginning of a print sequence, and footers are printed at the end--their actual positioning on the page is irrelevant. For example, you could position the page footer, containing page totals, to print at the top of the page.
Есть некий смысл в последнем абзаце. Т.е. для получения тоталов пользуйтесь футером всего отчета, а если нужны page footer'ы, то его позиция один раз задается, хотя б и наверху страницы.
Игорь, а задача стоит получить в одном отчете разные страницы? Когда-то у Велосипедистов был пример объединения двух структур в один отчет. Но сходу по Мануалу не нашёл.
We are hard at work… for you. :)
Аватара пользователя
Игорь Столяров
Ветеран движения
Сообщения: 7322
Зарегистрирован: 07 Июль 2005, 10:19
Откуда: г. Ростов-на-ДоМу
Благодарил (а): 13 раз
Поблагодарили: 48 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение Игорь Столяров »

Да, я пытался решить задачу именно получить на разных страницах разное расположение PageFooter.
Да, я понимаю, что расположение PageFooter может быть на странице любым.
Это описание тоже знаю. И вот как раз таки проблема в том, что оно некорректное.

Точнее правда, но не вся. Пока получается, что описание должны быть следующим:
1. Расположение PageFooter может быть любым на листе, но будет одинаковым на всех листах.
2. Расположение PageFooter будет таким, каким оно задано последним.

И если это действительно так - то это уже бред, ставящий большой вопрос на всем страничном формировании отчета.
Если отчет формируется по листам - откуда на первой странице координаты и печать по ним PageFooter, которые я задаю при
формировании сотого листа отчета (или перед закрытием отчета) ? Вот это есть то, что я пытаюсь понять ... ;)
За теми кто отстал - не возвращаться. (С) Кодекс
kreator
✯ Ветеран ✯
Сообщения: 4960
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 6 раз
Поблагодарили: 19 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение kreator »

Почитал еще Хелп.
Before learning how to create a report using the Report Designer, it's important to understand how Clarion executes a report--in other words, the division of labor between the print engine and your source code, and the order in which Clarion processes all the sections of your report. Each section of the report is a data structure, and each in turn is contained in the REPORT structure.

Smart Processing

The REPORT data structure contains all the information necessary for formatting and printing each page. It automatically handles page overflow management, including widow and orphan control. This frees you from worrying about the "mechanics."

This means that the Clarion executable code to print a report is simple and clean. The following example shows how a total of six lines of executable code can access the file and print a fully-formatted listing of all Customers. Since the Report Designer writes the entire REPORT data structure, this is all the code the programmer has to write:

CODE

OPEN(CustReport) !Open report for processing

SET(Cus:NameKey) !Top of file, alpha order

LOOP !Process the entire file

NEXT(CustomerFile) !one record at a time

IF ERRORCODE() THEN BREAK. !Check for errors

PRINT(Rpt:Detail) !PRINT tells the REPORT structure to do the work.

END

Of course, if you're using the Application Generator, you don't even have to write that much! In the example above, the PRINT statement prints a DETAIL structure for each record in the file retrieved with the NEXT statement inside the LOOP .

The REPORT data structure contains the items that belong on the page, plus the attributes that determine how they appear there. Since you visually design these in the Report Designer, the code example above really is all you have to do to print the report.

The PRINT statement automatically initiates the page overflow handling. This means that when the LOOP goes through enough records to fill up the page, it automatically generates any other structures on the page--the FOOTER, for example. Then it sends the entire page to the print spooler.

Order

The parts are wholly contained and managed within the REPORT data structure. The parts of the data structure are the FORM, PAGE, HEADER, DETAIL, and page FOOTER; their functions are fully described below. The REPORT data structure may also contain group BREAK structures. Each group BREAK structure can contain its own group HEADER, DETAIL, and FOOTER.

Normally, you want to design reports with only one DETAIL. When you generate reports using the Application Generator, they will probably have only one. This usually is the one inside the group BREAK structure. The Report Designer adds a DETAIL for each BREAK, for flexibility. You can delete the ones not used.

Once you know the order in which the parts generate at print time, you can understand how to use them better. For the following example, assume a report utilizing all the parts listed above, containing one group structure, with a DETAIL inside. Immediately upon the PRINT command:

1. The print engine composes the FORM, but does not send it to the print spooler yet. The FORM generates only once; the application repeats the FORM and does not recompose it for additional pages.

2. The print engine composes the page HEADER.

3. The print engine processes the group HEADER.

4. The application generates the DETAIL section (within the BREAK) for as many times as will fill the first page, continuously checking for group BREAKs.

If a BREAK occurs on the page:

5. The print engine composes the group FOOTER for the first group.

6. The print engine composes the group HEADER for the next group.

7. The application generates the DETAIL section for the next group of records, continuously checking for further group BREAKs.

At the bottom of the page:

8. The print engine checks for widows, increments the page count, and checks the next page for orphans.

9. The print engine composes the page FOOTER.

10. The print engine sends the entire first page to the print spooler.

11. For page two, since the FORM was composed already, it does not get regenerated, though it will print on the page. The application proceeds directly to the page HEADER.

12. The application repeats the procedures above for this and any additional pages.

Flexibility

The page-oriented nature of the Report Designer is the key to its flexibility. The print engine composes each page in its entirety before sending it to the printer. This means you may arrange the parts of the report into any page layout you wish.

You can place the FORM, page HEADER, and page FOOTER structures anywhere on the page, within certain limitations. Their placement does not affect the order that the application generates the parts.

That means you can physically place a page FOOTER above a page HEADER. Since the FOOTER generates only after the report processes all the records on the page, this allows you, for example, to place a page total above the records on the page.

You set the position and size of the DETAIL structure as an offset vs. the last DETAIL printed. The print engine prints each DETAIL from page top to page bottom. If the DETAIL is narrow enough so that more than one fits across the width of the page, they print in order left to right, top to bottom.

Group BREAK structures--group HEADER, group DETAIL and group FOOTER--all print as offsets within the DETAIL area, one after the other.

You can do some fancy footwork in cooperation with the print engine. For example, because the DETAIL structure must be printed with the PRINT statement, you can utilize embedded source to place conditional statements within your executable code, to print one DETAIL upon one condition, and another upon a different condition.

As long as you remember the order in which the application generates each section, which determines the current record and the values of the totals, tallies and other operations on the fields in each structure, you can build in a great deal of flexibility within the REPORT data structure, and let the print engine worry about fitting it all onto the page at runtime.
The FOOTER structure declares the output which prints at the end of each page or group. A FOOTER structure must be terminated with a period or END statement.

A FOOTER structure that is not within a BREAK structure is a page footer. Only one page FOOTER is allowed in a REPORT. The page FOOTER is automatically printed whenever a page break occurs, at the page-relative position specified by its AT attribute.
Беру, наверное, свои слова обратно. Из этих кусков (особенно из второго) видно, что page FOOTER печатается, когда случается разрыв страницы. Ну и по идее его AT аттрибуты должны быть динамическими.
We are hard at work… for you. :)
Аватара пользователя
Игорь Столяров
Ветеран движения
Сообщения: 7322
Зарегистрирован: 07 Июль 2005, 10:19
Откуда: г. Ростов-на-ДоМу
Благодарил (а): 13 раз
Поблагодарили: 48 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение Игорь Столяров »

kreator писал(а):Ну и по идее его AT аттрибуты должны быть динамическими.
Да, я же о том и пишу ... Аттрибуты PageFooter менять можно, но их обработка идет в пику с концепцией страничного формирования отчетов.
Да, и вряд ли есть смысл вообще менять AT аттрибуты PageFooter - если это отображается сразу на всех листах. Здесь явно какой-то косяк или недоделка ...
Я эксперементирую на C6.3, надо попробовать C8 ...

А вообще принцип заполнения листов отчетов подразумевает, что где-то существует переменная, которая отображает заполнение зоны печати текущего
листа (или текущее смещение относительно начала зоны печати - X/Y) - иначе невозможно. Эх, найти бы к ней доступ ... Это решило бы многие вопросы формирования отчетов.
За теми кто отстал - не возвращаться. (С) Кодекс
kreator
✯ Ветеран ✯
Сообщения: 4960
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 6 раз
Поблагодарили: 19 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение kreator »

Игорь! Сделал я тестовый отчет в С8.
В точке вставки TakeRecord ставлю текст:

Код: Выделить всё

Report$?unnamed:2{prop:At,2} = Report$?unnamed:2{prop:At,2}-20
Где ?unnamed:2 - это Page Footer, A Detail такой высоты, что на странице помещается только одна запись (для упрощения ситуации).
Реально Page Footer меняет свое положение для каждой страницы.
We are hard at work… for you. :)
Аватара пользователя
Игорь Столяров
Ветеран движения
Сообщения: 7322
Зарегистрирован: 07 Июль 2005, 10:19
Откуда: г. Ростов-на-ДоМу
Благодарил (а): 13 раз
Поблагодарили: 48 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение Игорь Столяров »

Спасибо. Интересно. Я пробовал через {Prop:YPos} ... Попробую и сообщу.
За теми кто отстал - не возвращаться. (С) Кодекс
kreator
✯ Ветеран ✯
Сообщения: 4960
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 6 раз
Поблагодарили: 19 раз

Re: Попытка понять алгоритм формирования отчета ...

Сообщение kreator »

prop:YPos то же самое, что и prop:At,2. Где-то в другом собака порылась.
We are hard at work… for you. :)
Аватара пользователя
vea
Бывалый
Сообщения: 51
Зарегистрирован: 01 Сентябрь 2005, 15:48
Откуда: Иваново
Контактная информация:

Re: Попытка понять алгоритм формирования отчета ...

Сообщение vea »

А может не то же самое? В prop:YPos один параметр (x), а в prop:At,2 уже два (x и y), первый по-умолчанию... ИМХО
С уважением, vea
Ответить