Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / PowerBuilder [игнор отключен] [закрыт для гостей] / The printable area of the page / 9 сообщений из 9, страница 1 из 1
27.02.2008, 20:59
    #35159241
Black Savage
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
Имеем PowerBuilder 10.5.2 Build 7564 . Можно как-то получить размер области печати
для DataWindow с установленными Orientation и Paper.Size свойствами?

Тут уже поднимался и обсуждался данный вопрос, но что-то не канает меня идея добавлять
по одному объекту и смотреть увеличивается количество листов или нет.

Седня рылся в Тырнете, ничего умного не нашел. Казалось бы вот это должно работать:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
// Declaration
// Win32 API function for printer

function integer openprinter (  string pPrinterName, ref ulong phPrinter,  long pDefault ) library "winspool.drv" alias for "OpenPrinterA;Ansi"

function boolean closeprinter (ulong printerhandle)  library "winspool.drv" alias for "ClosePrinter;Ansi"

function long GetDeviceCaps ( ulong wHndl, long nIndex )  library "gdi32.dll"

// Get the print area function
ulong 	lul_hprinter
integer	li_error
long 	ll_null, ll_dpix, ll_dpiy

// Reset size
al_width  =  0 
al_height =  0 

// Get printer handle
SetNull(ll_null)
li_error =  OpenPrinter(as_printer_name, ref lul_hprinter, ll_null)

ll_dpix = GetDeviceCaps(lul_hprinter,  8 )	/* the width, in pixels, of the printable area of the page  */
ll_dpiy = GetDeviceCaps(lul_hprinter,  10 ) 	/* the height, in pixels, of the printable area of the page */

// Close printer
ClosePrinter(lul_hprinter)

// Return values
al_width  = ll_dpix
al_height = ll_dpiy

Засада в том, что GetDeviceCaps возвращает всегда НОЛЬ . ХЗ почему.

На данный момент, размер области печати получаем следующим образом:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
//************************************************************************************
// Author Name			:	urvas
// Creation Date 		:  	 27 -Oct- 2006 
// Definition of Parameters	:
// Description 			:	convert metric to PBU (PowerBuildel Units)
//					wf_convertmetrictopbu function
// Modification history 
//====================================================================================
// Version !   Date	!  Author  ! 	Description
//====================================================================================
//  3 . 0        27 -Oct- 2006    urvas		Initial Version
//************************************************************************************

long 		ll_dpix, ll_dpiy, ll_dc, ll_pixels
decimal 	lc_inchtocm, lc_x_cm, lc_y_cm, lc_inches

lc_inchtocm =  2 . 54 

// get dpi for x and y axis
ll_dc = GetDC( 0 )
ll_dpix = GetDeviceCaps(ll_dc,  88 );
ll_dpiy = GetDeviceCaps(ll_dc,  90 );
ReleaseDC( 0 , ll_dc);

// convert metric to inches
lc_inches 	= ac_dimention/lc_inchtocm

// convert inches to pixels
// convert pixels to PBU
choose case as_xy
	case 'x'
		ll_pixels	= lc_inches * ll_dpix
		return PixelsToUnits(ll_pixels, XPixelsToUnits!)
	case 'y'
		ll_pixels	= lc_inches * ll_dpiy
		return PixelsToUnits(ll_pixels, YPixelsToUnits!)
end choose

return  0 

Ну и вызов этой функции:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
//************************************************************************************
// Author Name			:	Black Savage
// Creation Date 		:  	 11 -Feb- 2008 
// Definition of Parameters	:
// Description 			:	Get the print paper area in PowerBuilder units
//											
// Modification history 
//====================================================================================
// Version !   Date	!  Author	! 	Description
//====================================================================================
//  3 . 0        11 -Feb- 2008    Black Savage   Initial Version
//************************************************************************************

long	ll_width, ll_height, ll_top, ll_bottom, ll_left, ll_right
string	ls_value

// Reset size
al_width  =  0 
al_height =  0 

// Page height and width without margins
choose case ii_papersize
	case  1  // Letter
		choose case ii_paperorientation
			case  1 	// Landscape
				ll_height	= wf_convertmetrictopbu( 21 . 59 , "y")
				ll_width	= wf_convertmetrictopbu( 27 . 94 , "x")
			case  2 	// Portrait
				ll_height	= wf_convertmetrictopbu( 27 . 94 , "y")
				ll_width	= wf_convertmetrictopbu( 21 . 59 , "x")
		end choose
	case  9  // A4
		choose case ii_paperorientation
			case  1 	// Landscape
				ll_height = wf_convertmetrictopbu( 21 . 00 , "y")
				ll_width  = wf_convertmetrictopbu( 29 . 70 , "x")
			case  2 	// Portrait
				ll_height	= wf_convertmetrictopbu( 29 . 70 , "y")
				ll_width	= wf_convertmetrictopbu( 21 . 00 , "x")
		end choose
end choose

// Get Top Margin
ls_value = dw_preview.Describe("DataWindow.Print.Margin.Top")
if IsNull(ls_value) then ls_value = "0"
if IsNumber(ls_value) = false then ls_value = "0"
ll_top = Long(ls_value)

// Get Bottom Margin
ls_value = dw_preview.Describe("DataWindow.Print.Margin.Bottom")
if IsNull(ls_value) then ls_value = "0"
if IsNumber(ls_value) = false then ls_value = "0"
ll_bottom = Long(ls_value)

// Get Left Margin
ls_value = dw_preview.Describe("DataWindow.Print.Margin.Left")
if IsNull(ls_value) then ls_value = "0"
if IsNumber(ls_value) = false then ls_value = "0"
ll_left = Long(ls_value)

// Get Right Margin
ls_value = dw_preview.Describe("DataWindow.Print.Margin.Right")
if IsNull(ls_value) then ls_value = "0"
if IsNumber(ls_value) = false then ls_value = "0"
ll_right = Long(ls_value)

// Get print area
al_height	= ll_height	- ( ll_top + ll_bottom )
al_width	= ll_width	- ( ll_left + ll_right )

return  1 

По сути ничего умного здесь не написано: взяли лист A4 или Letter , его ориентацию,
физические размеры известны - дальше перевели все в PowerBuilder units. Все бы хорошо,
но здесь есть некая ошибка, при широких отчетах - это сильно видно. Ну и с PDF принтером лажа
полная.

Вообщем, посоветуйте чего-нибудь, плиЗЗ.

P.S.: Прошу прощения, что тут много буквЪ...
...
Рейтинг: 0 / 0
28.02.2008, 10:05
    #35159738
Локшин Марк
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
Black SavageЗасада в том, что GetDeviceCaps возвращает всегда НОЛЬ. ХЗ почему.
Сдается мне, что даже если будет и не 0, то результат будет все равно
Black Savageно здесь есть некая ошибка, при широких отчетах - это сильно видно
т.к. мнение программистов из Sybase о том что этот объект нужно начать печатать с новой страницы или нет может расходиться с вашими вычислениями. Не стоит основываться на каких-то внутренних недокументированных особенностях построения отчетов в PB которые могут измениться в любом релизе.
...
Рейтинг: 0 / 0
28.02.2008, 11:58
    #35160169
Black Savage
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
Локшин Маркт.к. мнение программистов из Sybase о том что этот объект нужно начать
печатать с новой страницы или нет может расходиться с вашими вычислениями. Не стоит
основываться на каких-то внутренних недокументированных особенностях построения отчетов
в PB которые могут измениться в любом релизе
.

Да я уже давно говорю нОчальству, что надо прекращать делание навороченного объекта для
печати. Постоянно лезет какая-то хрень. Дак ведь, хто ж меня будет слушать то? Вот и пытаюсь
сделать невозможное возможным...
...
Рейтинг: 0 / 0
07.08.2008, 01:27
    #35475044
Daniel Ferreira
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
Sorry guys, I don't know the russian language, so I'll post in english (I'll paste a little google translation at the end). I can't find this anywhere on the web, and seems like you got it to work!
Black Savage, have you successfully used the GetDeviceContest in PB? I'm trying to use it here, same script as yours, but I always get 0 (zero) for any call I make to it! :(
Please, do you have any ideas??
I've tried PB 8.0.4 Build 1051 and PB 10.2.1 Build 9914

Please, try to help me!!! :(

/* Local External Functions */
Function Long GetDeviceCaps (uLong aul_DC, Long al_Index) Library "GDI32.DLL"
FUNCTION boolean ClosePrinter( ulong aul_printerhandle ) Library "Winspool.drv"

// PB8
FUNCTION boolean OpenPrinter( string as_printername, ref ulong aul_printerhandle, ulong aul_printerdefaults) Library "Winspool.drv" Alias For "OpenPrinterA"
// PB10
FUNCTION boolean OpenPrinter( string as_printername, ref ulong aul_printerhandle, ulong aul_printerdefaults) Library "Winspool.drv" Alias For "OpenPrinterA;ansi"

/* My Script */
Constant Long HORZRES = 8
Constant Long VERTRES = 10
Constant Long LOGPIXELSX = 88
Constant Long LOGPIXELSY = 90
Constant Long PHYSICALWIDTH = 110
Constant Long PHYSICALHEIGHT = 111
Constant Long PHYSICALOFFSETX = 112
Constant Long PHYSICALOFFSETY = 113

Long ll_resolution_X, ll_resolution_Y, ll_printorigin_X, ll_printorigin_Y, ll_pagerect_Left, ll_pagerect_Right, ll_pagerect_Top, ll_pagerect_Bottom
uLong lul_null, lul_Printer
String ls_PrinterName

SetNull(lul_Null)

// Get Current Printer Name
ls_PrinterName = PrintGetPrinter()
ls_PrinterName = Left(ls_PrinterName, Pos(ls_PrinterName, "~t") - 1)

// Open Current Printer and get Handle to it
IF OpenPrinter( ls_PrinterName, lul_Printer, lul_Null ) THEN
ll_resolution_X = GetDeviceCaps( lul_Printer, HORZRES )
ll_resolution_Y = GetDeviceCaps( lul_Printer, VERTRES )
ll_printorigin_X = GetDeviceCaps( lul_Printer, PHYSICALOFFSETX )
ll_printorigin_Y = GetDeviceCaps( lul_Printer, PHYSICALOFFSETY )
ll_pagerect_Left = 0
ll_pagerect_Right = GetDeviceCaps( lul_Printer, PHYSICALWIDTH )
ll_pagerect_Top = 0
ll_pagerect_Bottom = GetDeviceCaps( lul_Printer, PHYSICALHEIGHT )


// Clean Up
ClosePrinter(lul_Printer)
END IF

Google Russian:
Извините ребята, я не знаю русский язык, поэтому я пост на английском (я пасты мало google перевод на конце). Я не могу найти это в любом месте сети, и, по-видимому, как и вы получили его на работе!
Черный Savage, вы успешно используется в GetDeviceContest PB? Я пытаюсь использовать его здесь, тот же сценарий, как ваша, но я всегда получите 0 (ноль) на любой призыв я делаю на него! :(
Пожалуйста, есть ли у вас каких-либо идей?
Я попытался PB 8.0.4 Build 1051 и PB 10.2.1 Build 9914

Пожалуйста, попробуйте мне помочь! :(
...
Рейтинг: 0 / 0
07.08.2008, 09:01
    #35475197
Black Savage
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
To Daniel Ferreira

I have resolved the issue in the following way:

1. Get a rough width of the printable area. I used my examples above.
2. Correct the value. I add an object on a paper and move it to the right on 1 PB unit.
Check if the report has an additional paper after that.

The implementation works correctly for all our complicated reports.
If you have any questions, please don't hesitate to ask me directly.
If you don't mind, we may continue this discussion over e-mails...
...
Рейтинг: 0 / 0
07.08.2008, 09:05
    #35475200
urvas
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
Попытаюсь сформулировать свою мысль, Черный Savage! :-)))))))))))))

Может, мы шли не совсем правильным путём, когда для широких отчетов расчитывали каждый лист самостоятельно, т.е. как отдельную единицу? Может, надо учитывать предыдущие листы, чтобы не набегала ошибка округления?

Я извиняюсь за нечеткое формулирование мысли, т.к. в данный момент имею только некие ощущения проблемы, а не точное понимание.
...
Рейтинг: 0 / 0
07.08.2008, 09:23
    #35475233
Black Savage
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
Мысь, в принципе верная, тока она тоже не поможет в старой реализации.
Я весь твой код переделал. Только добавление объекта и проверка появления
новой страницы дает более или менее надежный результат. Это работает стопудово,
даже для PDF, Microsoft XPS Document Writer и Microsoft Office Document Image Writer
принтеров. Идею позаимствовал у Марк, где-то мне об этом написал.

P.S.: Кстате, urvas теперь окно Print Preview даже мне порой нравится по своему
функци аналу и работе...
...
Рейтинг: 0 / 0
07.08.2008, 16:59
    #35476810
Daniel Ferreira
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
Bro, thank you for the "technical resource" :-)
I´ll try to implement this asap!
TY!!
...
Рейтинг: 0 / 0
08.08.2008, 09:02
    #35477645
Black Savage
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
The printable area of the page
To Daniel Ferreira

I see your problem. As I wrote above your code will not work. So, you have my example
when a rough width of a printable area is received. Please, look at below. This is a piece of code to
shift the temporary object, which is used to detect that a new paper has appeared:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
public function integer wf_get_width_absolute_precision (ref long al_width)

//************************************************************************************
// Author Name					:		Black Savage
// Creation Date 				:  		 29 -Feb- 2008 
// Definition of Parameters	:
// Description 					:		Get absolute precision for paper Width in PowerBuilder Units
//											It is used to correct the approximate value
// Modification history 
//====================================================================================
// Version !   Date			!  Author			! 	Description
//====================================================================================
//  1 . 0          29 -Feb- 2008    Black Savage   Initial Version
//************************************************************************************

long		ll_initial_horizontal_pages, ll_horizontal_pages, ll_old_horizontal_pages, ll_y, ll_x, ll_old_x, ll_object_width, ll_item, ll_item_number
string		ls_return, ls_modstring, ls_test_object
boolean	lb_corrected

// Check parameter
if IsNull(al_width) then al_width =  0 
if al_width <=  0  then return guo_variables.FAILURE

// Total horizontal pages
ll_initial_horizontal_pages = Long(dw_preview.Describe("Evaluate('PageCountAcross()',0)"))

// Choose the test object name
ll_item =  0 
ls_test_object = "test_object_t"
do 
	// Check if the object name exists
	ls_return = dw_preview.Describe(ls_test_object + ".Type")
	if IsNull(ls_return) then ls_return = ""
	ls_return = Trim(Lower(ls_return))
	if ls_return = "!" or ls_return = "?" then ls_return = ""
	if ls_return = "" then exit
	
	ll_item ++
	ls_test_object = "test_object_t" + String(ll_item)
loop while true

// The test object has to be width enough to make a round-off error as less as possible
ll_object_width = al_width /  2 

// Set coordinates
ll_y =  1 
ll_old_x = ll_initial_horizontal_pages * al_width - ll_object_width

ll_item_number = al_width /  2 
lb_corrected = false
ll_old_horizontal_pages = ll_initial_horizontal_pages
ll_x = ll_old_x
for ll_item =  1  to ll_item_number
	
	// Create the test object
	ls_modstring = "create text(band=foreground alignment=~'0~' text=~'~' border=~'0~' color=~'33554432~' x=~'" + String(ll_x) + "~' y=~'" + String(ll_y) + &
							"~' height=~'64~' width=~'" + String(ll_object_width) + "~' html.valueishtml=~'0~'  name=" + ls_test_object + &
							" visible=~'1~' font.face=~'Tahoma~' font.height=~'-8~' font.weight=~'400~'  font.family=~'2~' font.pitch=~'2~' font.charset=~'204~'" + &
							" background.mode=~'2~' background.color=~'1073741824~' )"
	ls_return = dw_preview.Modify(ls_modstring)
	
	// Total horizontal pages
	ll_horizontal_pages = Long(dw_preview.Describe("Evaluate('PageCountAcross()',0)"))
	
	// Destroy the test object
	ls_return = dw_preview.Modify("destroy " + ls_test_object)
	
	// Compare result
	if ll_initial_horizontal_pages = ll_horizontal_pages then
		// Keep old data
		ll_old_x = ll_x
		ll_old_horizontal_pages = ll_horizontal_pages
		
		ll_x ++
	else
		if ll_horizontal_pages > ll_initial_horizontal_pages then 
			if ll_x - ll_old_x =  1  and ll_old_horizontal_pages = ll_initial_horizontal_pages then
				// The ll_old_x is the right coordinate
				lb_corrected = true
				exit
			else
				// Keep old data
				ll_old_x = ll_x
				ll_old_horizontal_pages = ll_horizontal_pages
				
				ll_x --
			end if
		else
			// That is impossible!
			exit
		end if
	end if
	
next

// Correct the width
if lb_corrected then 
	if ll_initial_horizontal_pages =  0  then ll_initial_horizontal_pages =  1 
	
	al_width = Round((ll_old_x + ll_object_width) / ll_initial_horizontal_pages,  0 )
end if

return guo_variables.SUCCESS
...
Рейтинг: 0 / 0
Форумы / PowerBuilder [игнор отключен] [закрыт для гостей] / The printable area of the page / 9 сообщений из 9, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]