Printing files using CPrintDialog

Source: Internet
Author: User
Tags textout
Some time ago you need to print the log information through the printer.
Summed up some of these uses:
1: Use the CPrintDialog can exhale the window lets the user select the printer or uses the default printer to print directly.
StartPage .....  EndPage to finish printing a page of documents. If you need to change the DC settings, call RESETDC ()
Call these two functions multiple times to print multiple pages
Determination of 2:textout coordinates.
The coordinates in the textout are the logical coordinates in the DC.
and the actual physical coordinates need to be converted.
Getdevicecpas (); Gets the device information in the DC.
GetTextMetrics (); Gets the information for the font. The height of the font and its height + spacing.
The fonts in 3:textout can be set.
The key code is as follows:
CFont MyFont;
Myfont.createpontfont (...);
Oldfont = DC. SelectObject ();
Myfont.delectobject () ';


Attached
1: Reprint Related documents:
Conversion of print Units


The key to this is that we need to get the DPI of the display device, that is, the number of devices supported per inch. With the DPI we can switch between our accustomed units and unit units, using the API GetDeviceCaps (), which is powerful and can be referenced by MSDN, where we are only able to get the device dpi. Look at the sample code:

[CPP] View plaincopy
Some devices may be different in both horizontal and vertical dpi, so get them separately.

To get the conversion ratio of the horizontal direction
Float Getxscale (HDC printdc)//PRINTDC: Printer DC device handle
{
The DPI that gets the printer's horizontal orientation
int xdpi = GetDeviceCaps (PRINTDC, logpixelsx);

254.0:25.4 mm per inch
Float XScale = (float) (254.0/xdpi);

return XScale;
}

To get the conversion ratio in the vertical direction
Float Getyscale (HDC printdc)//PRINTDC: Printer DC device handle
{
The DPI that gets the printer's vertical orientation
int ydpi = GetDeviceCaps (PRINTDC, logpixelsy);

float Yscale = (float) (254.0/ydpi);

return yscale;
}

Centimeter to device pixel, horizontal direction
Double Cm2unit_w (float XScale, double W)//w unit is cm
{
return w*100/xscale;
}

Centimeter to device pixel, vertical direction
Double Cm2unit_h (float Yscale, double H)//h unit is cm
{
return h*100/yscale;
}


In the code above, if you change the PRINTDC to a display device DC handle, you can get centimeters to display pixel units, which are used when printing preview. Get display device handle available:: GetDC (NULL).
Print Basic Process


With the knowledge in front, we can print it now. Windows printing has a fixed process, and the process is simpler. Call the print API in a fixed order: StartDoc ()-> startpage ()-> Print specific content-> endpage ()-> enddoc (). If you want to print multiple pages, loop StartPage () to EndPage ().
Sample code:

[CPP] View plaincopy
DocInfo Doc;
ZeroMemory (&doc,sizeof (DOC));
doc.cbsize = sizeof (DOC);
Doc.lpszdocname = (LPCTSTR) "Print Test File";

StartDoc (PRINTDC, &doc); Ready to print

StartPage (PRINTDC); Start Printing page

Print text at (2.5cm, 2.5cm)
char* Text = "Print Test text";

Float XScale = Getxscale (PRINTDC);
float Yscale = Getyscale (PRINTDC);

Double x = cm2unit_w (XScale, 2.5);
Double y = cm2unit_h (Yscale, 2.5);

Print text at a specified location
TextOut (PRINTDC, (int) x, (int) y, (LPTSTR) text, strlen (text));

EndPage (PRINTDC); End Print Page

EndDoc (PRINTDC); End Printing


Print Settings for fonts


Most of the time we want to be able to control the print font, the following code can create the font format you want:

[CPP] View plaincopy
/* Create a custom print font
Fontface: Font name, if NULL, by default "XXFarEastFont-Arial"
Fontheight: Font height, in centimeters
IsBold: whether Bold
Isitalic: Italic
Isunderline: Underline
Isstrikeout: Whether to delete lines
*/
Hfont GetFont (LPCTSTR fontface, double fontheight, bool IsBold, BOOL isitalic, BOOL Isunderline, BOOL isstrikeout)
{
int width = 0; Font width determined by system
int weight = Fw_normal;
DWORD italic = 0;
DWORD underline = 0;
DWORD strikeout = 0;
DWORD charSet = Default_charset;
LPCTSTR face = (LPCTSTR) "Song Body";

float height = cm2unit_h (fontheight);

if (fontface!= 0)
{
face = Fontface;
}

if (isbold)
{
Weight = Fw_bold;
}

if (isitalic)
{
Italic = 1;
}

if (isunderline)
{
underline = 1;
}

if (isstrikeout)
{
strikeout = 1;
}

Hfont font = createfont (int) height, width, 0, 0,
Weight, italic, underline, strikeout, CharSet,
Out_default_precis, Clip_default_precis, Proof_quality,
Default_pitch | Ff_dontcare, face);
return font;
}


Summary


These are the common problems we encounter in implementing printing, and I believe we understand these, and it is no longer difficult to implement printing in our own programs.



http://msdn.microsoft.com/zh-cn/library/cc485711 (vs.71). aspx#_core_printer_pages_vs.._document_pages
Print protocol
To print a multi-page document, the frame interacts with the view in the following way. First, the frame displays the Print dialog box, creates a device context for the printer, and calls
Cdc
object's
StartDoc
member functions. Then, for each page in the document, the framework calls the CDC object's
StartPage
A member function that instructs the View object to print the page and calls the
EndPage
member functions. If you must change the printer mode before starting a particular page, the view will call
ResetDC
, it updates the DEVMODE structure that contains the new printer mode information. After all the documents have been printed, the framework calls
EndDoc
member functions.
overriding view class functions
CView
The class defines several member functions that are called by the frame during the printing process. By overriding these functions in the view class, you provide a connection between the frame printing logic and the view class print logic. The following table lists the member functions.
CView overridable functions for printing
Name
overriding reason
OnPreparePrinting
Insert a value in the Print dialog box, especially the length of the document
OnBeginPrinting
assigning fonts or other GDI resources
OnPrepareDC
Adjust the device context properties for a given page, or print a time page
OnPrint
Print a given page
OnEndPrinting
DEALLOCATE GDI Resources
Other functions can also be used to perform printing-related processing, but these functions are functions that drive the printing process.
The following illustration illustrates the steps involved in the printing process and shows where to invoke each print member function of the CView. The remainder of this article is a more detailed explanation of most of the steps. The article on allocating GDI resources describes the other parts of the printing process.
Print loops


Paging
Framework in
CPrintInfo
Structure to store a lot of information about print jobs. Several values in the CPrintInfo are related to paging, and these values are shown in the following table.
Page number information stored in CPrintInfo
Name of member variable or function
Number of references
Getminpage/setminpage
First page of document
Getmaxpage/setmaxpage
Last page of document
GetFromPage
The first page to print
GetToPage
The last page to print
m_nCurPage
The page that is currently being printed
The page number starts at 1, that is, the first page is numbered 1 instead of 0. The above and other
CPrintInfo
For more information about members, see "MFC references."
At the beginning of the printing process, the frame calls the view's
OnPreparePrinting
A member function that passes a pointer to the CPrintInfo structure. The Application Wizard provides another member function that invokes CView
DoPreparePrinting
Implementation of the OnPreparePrinting. DoPreparePrinting is a function that displays the Print dialog box and creates a printer device context.
At this point, the application does not know the number of pages in the document. It uses default values of 1 and 0xFFFF for the page numbers on the first and last pages of the document. If you know the number of pages in the document, override OnPreparePrinting and call the CPrintInfo structure before sending the document to DoPreparePrinting
SetMaxPage
。 This allows you to specify the length of the document.
Next DoPreparePrinting Displays the Print dialog box. When it returns, the CPrintInfo structure contains the values specified by the user. If the user wants to print only the document within the range of the selected page number, he or she can specify the starting and ending page numbers in the Print dialog box. Framework uses
CPrintInfo
GetFromPage and GetToPage functions to retrieve these values. If the user does not specify a page range, the framework invokes GetMinPage and GetMaxPage and uses the returned value to print the entire document.
For each page that will be printed in the document, the frame calls the two member functions in the View class (
OnPrepareDC
And
OnPrint
and passed to two parameters per function: A pointer to the
Cdc
The pointer to the object and a pointer to the CPrintInfo structure. Each time the frame calls OnPrepareDC and OnPrint, it passes a different value in the m_nCurPage member of the CPrintInfo structure. In this way, the framework informs the view which pages to print.
OnPrepareDC
member functions can also be used for on-screen display. It adjusts the device context before drawing. OnPrepareDC play the same role in printing, but there are two different: first, the CDC object represents the printer device context rather than the screen device contexts; second, the CPrintInfo object is passed as the second parameter. (This parameter is NULL when ONPREPAREDC is invoked for screen display.) ) Overrides OnPrepareDC to adjust the device context based on the difference between the pages being printed. For example, you can make sure that the appropriate parts of your document are printed by moving the viewport origin and clipping region.
OnPrint
The member function performs the actual printing of the page. How the default print is implemented shows how the framework is invoked with the printer device context
OnDraw
To perform the printing. More specifically, the framework uses the CPrintInfo structure and device context to invoke Onprint,onprint to pass the device context to OnDraw. Rewrite OnPrint to perform any rendering that should only be completed during printing rather than on-screen display. For example, print a header or footer (for more information, see the article Header and footer). Then, from the OnPrint rewrite call OnDraw to do the screen display and printing of the common rendering.
The fact that OnDraw both screen rendering and print rendering means that your application is WYSIWYG (WYSIWYG). However, suppose you are writing a "WYSIWYG" application. For example, a text editor uses bold as a print font, but also displays control codes that indicate bold text on the screen. For this situation, you should strictly use OnDraw for screen display. When you override OnPrint, a call to the OnDraw is replaced with a call to a separate drawing function. This function draws the document as it appears on paper, using properties that are not displayed on the screen.
Printer pages and document pages
When it comes to page numbers, you sometimes have to differentiate between the concept of printer pages and the concept of document pages. From the printer's point of view, a page is a piece of paper. However, a piece of paper does not necessarily equal one page in the document. For example, if you print a newsletter, the paper will be folded, and a sheet of paper may contain both the first and last pages of the document (they are side by side). Similarly, if you print a spreadsheet, the document is not made up of pages at all. Instead, a sheet of paper may contain the first to the 20th row, the sixth to the tenth column.
All
CPrintInfo
The page number in the structure refers to the printer page. The framework calls ONPREPAREDC and OnPrint once for each sheet of paper that passes through the printer. When overriding
OnPreparePrinting
function to specify the length of the document, you must use the printer page. If there is a one by one correspondence (that is, a printer page equals a document page), then things are simple. Conversely, if the document page is not one by one corresponding to the printer page, you must convert between the two. For example, print a spreadsheet. When overriding OnPreparePrinting, you must calculate the number of sheets required to print the entire spreadsheet and use this value when calling CPrintInfo's SetMaxPage member function. Similarly, when overriding OnPrepareDC, you must convert the m_nCurPage to a range of rows and columns that appear on a specific sheet of paper, and then adjust the viewport origin accordingly.
Print Time page
In some cases, your view class might not know the length of the document before it actually prints. For example, if your application is not "WYSIWYG", the length of the document on the screen does not correspond to the length at which it is printed.
When you override a view class
OnPreparePrinting
, this problem arises: unable to
CPrintInfo
The SetMaxPage function of the struct passes the value because you do not know the length of the document. If the user does not use the Print dialog box to specify the ending page number, the frame does not know when to stop the print loop. The only way to determine when to stop the print loop is to print out all the documents and figure out when they will terminate. Your view class must check that the end of the document is reached during document printing and notify the frame when it arrives.
The framework depends on your view class's
OnPrepareDC
function to tell when to stop. After each call to OnPrepareDC, the framework checks for a member of the CPrintInfo structure named m_bContinuePrinting. The default value for this member is TRUE. As long as it retains this default value, the framework continues to print loops. If it is set to FALSE, the frame stops. To perform a print time page, override OnPrepareDC to check whether the end of the document has been reached, and set the m_bcontinueprinting to FALSE if it has arrived.
If the current page is greater than the default implementation of 1,ONPREPAREDC, the m_bcontinueprinting is set to FALSE. This means that if the document length is not specified, the frame assumes that the length of the document is one page. One result of this is that you must be cautious when invoking the base class version of OnPrepareDC. Do not assume that m_bcontinueprinting will be true after invoking the base class version.
A sample code on the 2:MSDN:
[CPP] View plaincopy
Get the default printer
CPrintDialog dlg (FALSE);
Dlg. GetDefaults ();

is a default printer set up?
HDC hdcprinter = dlg. GETPRINTERDC ();
if (hdcprinter = NULL)
{
MessageBox (_t ("Buy a printer!"));
}
Else
{
Create a CDC and attach it to the default printer
CDC Dcprinter;
Dcprinter.attach (Hdcprinter);

Call StartDoc () to begin printing
DocInfo DocInfo;
memset (&docinfo, 0, sizeof (docinfo));
docinfo.cbsize = sizeof (DocInfo);
Docinfo.lpszdocname = _t ("Cdc::startdoc () Code Fragment");

If it fails, complain and exit gracefully
if (Dcprinter.startdoc (&docinfo) < 0)
{
MessageBox (_t ("Printer wouldn ' T initalize"));
}
Else
{
Start a page
if (Dcprinter.startpage () < 0)
{
MessageBox (_t ("Could not start Page"));
Dcprinter.abortdoc ();
}
Else
{
Actually do some printing
cgdiobject* Poldfont = Dcprinter.selectstockobject (System_font);

Dcprinter.textout (_t ("Hello world!"), 12);

Dcprinter.endpage ();
Dcprinter.enddoc ();
Dcprinter.selectobject (Poldfont);
}
}
}




Turn from: http://www.cntxk.com/CataNews/60/info8939.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.