На главную

On-line справка по Win32 API

Написать письмо
БЕСПЛАТНАЯ ежедневная online лотерея! Выигрывай каждый день БЕСПЛАТНО!
Список всех статей A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z | Скачать Вниз

Printing a Document



Once the application initializes the necessary variables, registers its AbortProc function, and displays its modeless Cancel dialog box, it can start the print job by calling the StartDoc function.

After the application begins a print job, it can define individual pages in the document by calling the StartPage and EndPage functions and embedding the appropriate calls to GDI drawing functions within this bracket. After the application has defined the last page, it can close the document and end the print job by calling the EndDoc function.
The following example shows the code required to print a string of text and a bitmapped image. The string of text, centered at the top of the page, identifies the path and filename for the file that contains the bitmapped image. The bitmapped image, centered vertically and horizontally on the page, is drawn so that the same proportions used to draw the image in the application's window are maintained.

/*
* Initialize the members of a DOCINFO
* structure.
*/

di.cbSize = sizeof(DOCINFO);
di.lpszDocName = "Bitmap Printing Test";
di.lpszOutput = (LPTSTR) NULL;
di.lpszDataType = (LPTSTR) NULL;
di.fwType = 0;

/*
* Begin a print job by calling the StartDoc
* function.

*/

nError = StartDoc(pd.hDC, &di);
if (nError == SP_ERROR) {
errhandler("StartDoc", hwnd);
goto Error;
}

/*
* Inform the driver that the application is
* about to begin sending data.
*/

nError = StartPage(pd.hDC);
if (nError <= 0) {

errhandler("StartPage", hwnd);
goto Error;
}

/*
* Retrieve the number of pixels-per-logical-inch
* in the horizontal and vertical directions
* for the display upon which the bitmap
* was created.
*/

fLogPelsX1 = (float) GetDeviceCaps(pd.hDC, LOGPIXELSX);
fLogPelsY1 = (float) GetDeviceCaps(pd.hDC, LOGPIXELSY);



/*
* Retrieve the number of pixels-per-logical-inch
* in the horizontal and vertical directions
* for the printer upon which the bitmap
* will be printed.
*/

fLogPelsX2 = (float) GetDeviceCaps(pd.hDC,
LOGPIXELSX);
fLogPelsY2 = (float) GetDeviceCaps(pd.hDC,
LOGPIXELSY);


/*
* Determine the scaling factors required to
* print the bitmap and retain its original
* proportions.
*/

if (fLogPelsX1 > fLogPelsX2)
fScaleX = (fLogPelsX1 / fLogPelsX2);
else
fScaleX = (fLogPelsX2 / fLogPelsX1);

if (fLogPelsY1 > fLogPelsY2)
fScaleY = (fLogPelsY1 / fLogPelsY2);

else
fScaleY = (fLogPelsY2 / fLogPelsY1);

/*
* Compute the coordinate of the upper left
* corner of the centered bitmap.
*/

cWidthPels = GetDeviceCaps(pd.hDC, HORZRES);
xLeft = ((cWidthPels / 2) -
((int) (((float) bmih.biWidth)
* fScaleX)) / 2);
cHeightPels = GetDeviceCaps(pd.hDC, VERTRES);

yTop = ((cHeightPels / 2) -
((int) (((float) bmih.biHeight)
* fScaleY)) / 2);

/*
* Create a memory DC that is compatible with
* the printer and select the bitmap (which
* the user requested) into this DC.
*/

hdcMem = CreateCompatibleDC(pd.hDC);

if (!SelectObject(hdcMem, hbm))

errhandler("SelectObject Failed", hwnd);


/*
* Use the StretchBlt function to scale the
* bitmap and maintain its original proportions
* (that is, if the bitmap was square when it
* appeared in the application's client area,
* it should also appear square on the page).
*/


if (!StretchBlt(pd.hDC, xLeft, yTop,

(int) ((float) bmih.biWidth * fScaleX),
(int) ((float) bmih.biHeight * fScaleY),
hdcMem, 0, 0,
bmih.biWidth, bmih.biHeight,
SRCCOPY))
errhandler("StretchBlt Failed", hwnd);


/* Delete the memory DC. */

DeleteDC(hdcMem);

/*
* Retrieve the width of the string that

* specifies the full path and filename for the
* file that contains the bitmap.
*/

GetTextExtentPoint32(pd.hDC, ofn.lpstrFile,
ofn.nFileExtension + 3,
&szMetric);

/*
* Compute the starting point for the
* text-output operation. The string will
* be centered horizontally and positioned

* three-lines down from the top of the page.
*/

xLeft = ((cWidthPels / 2) - (szMetric.cx / 2));
yTop = (szMetric.cy * 3);

/*
* Print the path and filename for the bitmap,
* centered at the top of the page.
*/

TextOut(pd.hDC, xLeft, yTop, ofn.lpstrFile,
ofn.nFileExtension + 3);


/*
* Determine whether the user has pressed
* the Cancel button in the AbortPrintJob
* dialog box; if the button has been pressed,
* call the AbortDoc function. Otherwise, inform
* the spooler that the page is complete.
*/

nError = EndPage(pd.hDC);

if (nError <= 0) {
errhandler("EndPage", hwnd);

goto Error;
}

/* Inform the driver that document has ended. */

nError = EndDoc(pd.hDC);
if (nError <= 0)
errhandler("EndDoc", hwnd);

Error:
/* Enable the application's window. */

EnableWindow(hwnd, TRUE);

/* Remove the AbortPrintJob dialog box. */

DestroyWindow(hdlgCancel);


/* Delete the printer DC. */

DeleteDC(pd.hDC);


Because the pixels on a screen typically have different dimensions than the dots on a printer, it is necessary to scale bitmapped images to obtain a WYSIWYG effect. This is done by obtaining horizontal and vertical scaling factors and then applying those factors to the width and height values passed to the StretchBlt function. In the sample application, the scaling factors were obtained by retrieving the horizontal and vertical logical-pixel count for the two devices. Once the scaling factors were obtained, they were used to adjust the bitmap width and height.

To center the bitmap on the page, the application first computed the width and height of the scaled bitmap. (The bitmap was scaled to maintain the original proportions of the image.) These values were divided by two and then subtracted from half of the width and height of the page. The result defines the coordinates of the upper left corner of the bitmap.
To center the text at the top of the page, the application called the GetTextExtentPoint32 function to retrieve the width and height of the string specifying the path names and filenames. Once these values were obtained, the application used the height to position the string three lines down the page and the width to position the string horizontally centered on the page.

The following illustration shows a representation of the page that appeared when the application printed the bitmapped image in the WINLOGO.BMP file. This illustration also depicts the variables used to position the text and to position and scale the bitmap.



Пригласи друзей и счет твоего мобильника всегда будет положительным!
Предыдущая статья
 
Сайт Народ.Ру Интернет
Следующая статья
Пригласи друзей и счет твоего мобильника всегда будет положительным!

Печать Документа



Как только приложение инициализирует необходимые переменные, регистрирует свою функцию AbortProc, и отображает свой диалоговый ящик независимой Отмены, это может запустить работу отпечатка вызывая функцию StartDoc.

После того, как приложение начнет работу отпечатка, оно может определить индивидуальные страницы в документе вызывая StartPage и функции EndPage и вставляя подходящие вызовы на GDI, рисующий функции в пределах этой скобки. После того, как приложение определило последнюю страницу, оно может закрыть документ и заканчивать работу отпечатка вызывая функцию EndDoc.
Следующий пример показывает код требовавшийся, чтобы печатать строку текста и образ bitmapped. Строка текста, отцентрированного на верхе страницы, идентифицирует путь и filename для файла, который содержит образ bitmapped. Образ bitmapped, отцентрированный вертикально и горизонтально на странице, сделан чтобы те же пропорции использованные, чтобы делать образом в прикладном окне поддержаны.

/*
* Инициализируйте участников DOCINFO
* структура.
*/

di.cbSize = sizeof(DOCINFO);
di.lpszDocName = "ПОБИТОВОЕ отображение, печатающее Тест";
di.lpszOutput = (LPTSTR) НЕДЕЙСТВИТЕЛЬНЫЙ;
di.lpszDataType = (LPTSTR) НЕДЕЙСТВИТЕЛЬНЫЙ;
di.fwType = 0;

/*
* Начните работу отпечатка вызывая StartDoc
* функция.

*/

nError = StartDoc(pd.hDC, &di);
если (nError == SP_ERROR) { errhandler("StartDoc", hwnd);
goto Ошибка;
}

/*
* Сообщите водителя, что приложение
* соберитесь начинать посылать данные.
*/

nError = StartPage(pd.hDC);
если (nError <= 0) {

errhandler("StartPage", hwnd);
goto Ошибка;
}

/*
* Извлеките количество пикселей-за-логический-дюйм
* в горизонтальном и вертикальном направлениях
* для дисплея на котором побитовое отображение
* был создан.
*/

fLogPelsX1 = (функция преобразования) GetDeviceCaps(pd.hDC, LOGPIXELSX);
fLogPelsY1 = (функция преобразования) GetDeviceCaps(pd.hDC, LOGPIXELSY);



/*
* Извлеките количество пикселей-за-логический-дюйм
* в горизонтальном и вертикальном направлениях
* для принтера на котором побитовое отображение
* будет напечатан.
*/

fLogPelsX2 = (функция преобразования) GetDeviceCaps(pd.hDC, LOGPIXELSX);
fLogPelsY2 = (функция преобразования) GetDeviceCaps(pd.hDC, LOGPIXELSY);


/*
* Определите коэффициенты масштабирования требовавшиеся, чтобы
* напечатайте побитовое отображение и сохраняйте свой подлинник
* пропорции.
*/

если (fLogPelsX1 > fLogPelsX2) fScaleX = (fLogPelsX1 / fLogPelsX2);
еще
fScaleX = (fLogPelsX2 / fLogPelsX1);

если (fLogPelsY1 > fLogPelsY2) fScaleY = (fLogPelsY1 / fLogPelsY2);

еще
fScaleY = (fLogPelsY2 / fLogPelsY1);

/*
* Вычислите координату верхнего левого
* поставьте в безвыходное положение отцентрированное побитовое отображение.
*/

cWidthPels = GetDeviceCaps(pd.hDC, HORZRES);
xLeft = ((cWidthPels / 2) - ((int) (((Функция преобразования) bmih.biWidth)
* fScaleX)) / 2);
cHeightPels = GetDeviceCaps(pd.hDC, VERTRES);

yTop = ((cHeightPels / 2) - ((int) (((Функция преобразования) bmih.biHeight)
* fScaleY)) / 2);

/*
* Создайте память DC, которая совместимая с
* принтер и выбор побитовое отображение (какое
* пользователь запрашивал) в этот DC.
*/

hdcMem = CreateCompatibleDC(pd.hDC);

если (!SelectObject(hdcMem, hbm))

errhandler("SelectObject Потерпевший неудачу", hwnd);


/*
* Используйте функцию StretchBlt, чтобы масштабировать the
* побитовое отображение и поддерживает свои оригинальные пропорции
* (то есть, если побитовое отображение было квадратом когда это
* оказавшееся в прикладной области клиента,
* это должно также появиться квадрат на странице).
*/


если (!StretchBlt(pd.hDC, xLeft, yTop,

(int) ((функция преобразования) bmih.biWidth * fScaleX), (int) ((функция преобразования) bmih.biHeight * fScaleY), hdcMem, 0, 0, bmih.biWidth, bmih.biHeight, SRCCOPY)) errhandler("StretchBlt Потерпевший неудачу", hwnd);


/* Удалите память DC. */

DeleteDC(hdcMem);

/*
* Извлеките ширину строки это

* определяет полный путь и filename для the
* файл, который содержит побитовое отображение.
*/

GetTextExtentPoint32(pd.hDC, ofn.lpstrFile, ofn.nFileExtension + 3, &szMetric);

/*
* Вычислите отправной пункт для the
* текстовая-выходная операция. Строка будет
* центрироваться горизонтально и спозиционированное

* трех строка с верха страницы.
*/

xLeft = ((cWidthPels / 2) - (szMetric.cx / 2));
yTop = (szMetric.cy * 3);

/*
* Напечатайте путь и filename для побитового отображения,
* отцентрированное на верхе страницы.
*/

TextOut(pd.hDC, xLeft, yTop, ofn.lpstrFile, ofn.nFileExtension + 3);


/*
* Определите нажался пользователь
* кнопка Отмены в AbortPrintJob
* диалоговый блок; если кнопка нажата,
* назовите функцию AbortDoc. В противном случае, сообщите
* spooler, что страница завершенна.
*/

nError = EndPage(pd.hDC);

если (nError <= 0) { errhandler("EndPage", hwnd);

goto Ошибка;
}

/* Сообщите драйвер, что документ имеет ended. */

nError = EndDoc(pd.hDC);
если (nError <= 0) errhandler("EndDoc", hwnd);

Ошибка:
/* Приспособьтесь приложение window. */

EnableWindow(hwnd, ИСТИНА);

/* Удалите диалог AbortPrintJob box. */

DestroyWindow(hdlgCancel);


/* Удалите принтер DC. */

DeleteDC(pd.hDC);


Поскольку пиксели на экране обычно имеют другие измерения чем точки в принтере, необходимо должно масштабировать bitmapped образы, чтобы получать эффект WYSIWYG. Это сделан посредством получающих горизонтальных и вертикальных коэффициентов масштабирования и затем прилагая те показатели к ширине и величины высоты проходили в функцию StretchBlt. В приложении образца, коэффициенты масштабирования были получены поиском горизонтальный и вертикальный логический-пиксель иметь значение два устройства. Как только коэффициенты масштабирования будут получены, они имели обыкновение, чтобы регулировать ширину побитового отображения и высоты.

Чтобы центрировать побитовое отображение на странице, приложение сначала вычисляло ширину и высоту масштабированного побитового отображения. ( Побитовое отображение было масштабировано, чтобы поддерживать оригинальные пропорции образа.) Эти величины были поделены к двум и затем вычтенное из половины ширины и высоты страницы. Результат определяет координаты верхнего левого угла побитового отображения.
Для того, чтобы центрировать текст на верхе страницы, приложение было названо функция GetTextExtentPoint32, чтобы извлекать ширину и высоту строки, определяющие имена пути и filenames. Как только эти величины будут получены, приложение использовало высоту, чтобы позиционировать строку три строки вниз страница и ширина, чтобы позиционировать строку горизонтально отцентрированную на странице.

Следующая иллюстрация показывает представление страницы, что оказавшееся когда приложение печатало образ bitmapped в файле WINLOGO.BMP. Эта иллюстрация также изображает переменные использованные, чтобы позиционировать текст и, чтобы позиционировать и масштабировать побитовое отображение.



Вверх Version 1.3, Oct 26 2010 © 2007, 2010, mrhx Вверх
 mrhx software  Русский перевод OpenGL  Русский перевод Win32 API
 
Используются технологии uCoz