Print Preview Without MFC

DocView architecture in MFC is not at all the fastest way to create a simple print preview. This article will explain How to create your own print preview. MFC DocView is designed to make the MSVC programmers get their works done in a minutes including print preview. Sometimes we need not to use DocView framework but we really need its print preview power. The key of this Print Preview is laying on the following function.
  1. CreateCompatibleBitmap
  2. CreateCompatibleDC
  3. GetDeviceCaps
  4. GetTextExtent
Beside those four functions, Print Preview needs a function that work for scaling and painting on the screen DC. We just lucky to have StretchBlt and BitBlt ready to do the dirty works but sometimes StretchBlt should be replaced by your favourite routine and then BitBlt comes into play. The reason is (maybe) dithering, filtering, antialiasing etc..
void CDlgAneh::OnButton1() 
{
// TODO: Add your control notification handler code here
//
//
// Design and implementation cinoban@yahoo.com 
// 13 Jan 2000 15:14
//

CString strWords;

// This is a rectangle control
CWnd* pWnd = GetDlgItem(IDC_STATIC_PREVIEW); 

CDC* dc;
CDC memoriDC;
CBitmap memBMP;
CBitmap* pOldBMP;
CFont fnt;
CFont* pOldFnt;
CRect rect;
CRect rectMemory;
CSize zMetrix;

//
//
//
CPrintDialog pdlg(FALSE);
DOCINFO di;
CDC prnDC;

di.cbSize = sizeof(DOCINFO);
di.lpszDocName = "This string will appear in Printer
Queue";
di.lpszOutput = NULL;     
di.lpszDatatype = NULL;
di.fwType = 0;

//
// Get current printer setting
//
pdlg.GetDefaults();


//
dc = pWnd->GetDC();
pWnd->GetClientRect(&rect);

// DC printer???
if( !prnDC.Attach(pdlg.GetPrinterDC()) )
AfxMessageBox("Invalid Printer DC");
memoriDC.CreateCompatibleDC(&prnDC); // Create DC for
Preview

//
// Get the resolution of Screen and Current Default
Printer
//
int iPrnX = prnDC.GetDeviceCaps(HORZRES);
int iPrnY = prnDC.GetDeviceCaps(VERTRES);
int iMonX = dc->GetDeviceCaps(HORZRES); // Device
Target is Monitor
int iMonY = dc->GetDeviceCaps(VERTRES);


rectMemory.top = 0;
rectMemory.left = 0;
rectMemory.bottom = iPrnY;
rectMemory.right = iPrnX;

//
// Create a Memory Bitmap that is compatible with the
Printer DC
// then select or make the bitmap as current GDI
active object
//
memBMP.CreateCompatibleBitmap(&prnDC,
rectMemory.Width(), rectMemory.Height());
pOldBMP = memoriDC.SelectObject(&memBMP);

//
// Clear memory DC or in other words
// paint the bitmap with white colour and transparent
text
//
memoriDC.SetBkMode(TRANSPARENT);
memoriDC.SetTextColor(RGB(0, 0, 0));
memoriDC.PatBlt(0, 0, rectMemory.Width(),
rectMemory.Height(), WHITENESS);

//
// Prepare the font
//
int iPointz = 100;
fnt.CreatePointFont(iPointz, "OCR A", &memoriDC);
strWords.Format("This is line number    ");        //
Test string
pOldFnt = memoriDC.SelectObject(&fnt);
zMetrix = memoriDC.GetTextExtent(strWords);
int iPos = 0;

//
// Write string or Paint something
//
int iMaksimal = 0;
int iLineHeight = 1;
int iLoop;
CString strPuncak;

//
// Calculate how many lines we could fit
//
for(iLoop = 1; iLoop < 100; iLoop++)
{
if( ((zMetrix.cy+iLineHeight)*iLoop) < iPrnY )
iMaksimal++;
}

strPuncak.Format("Maximum Amount of line(s) for %d
points are %d lines", iPointz, iMaksimal);

//
//
//
for(iLoop = 0; iLoop < iMaksimal; iLoop++)
{
strWords.Format("This is line %d", iLoop);
memoriDC.TextOut(0, iLoop*(zMetrix.cy+iLineHeight),
strWords);
}

//
// Reseting font
//
memoriDC.SelectObject(pOldFnt);

//
// Calculate ratio
//
float fXRatio = (float) iMonX/iPrnX;
float fYRatio = (float) iMonY/iPrnY;


//  iLebar = Width
//  iTinggi = Height
//  iXPosisiPreview = horisontal location of preview
//  iYPosisiPreview = vertical location of preview
//
int iLebar = rect.Width()*fXRatio;
int iTinggi = rect.Height()*fYRatio;
int iXPosisiPreview = (rect.Width() - iLebar)/2;
int iYPosisiPreview = (rect.Height() - iTinggi)/2;
CPen pen(PS_SOLID, 2, RGB(255, 0, 0));
CPen* pOldPen;

//
// Create an outline
// 
pOldPen = dc->SelectObject(&pen);
dc->Rectangle(iXPosisiPreview, iYPosisiPreview ,
iXPosisiPreview + iLebar + 2 , iYPosisiPreview +
iTinggi + 2);
dc->SelectObject(pOldPen);

//
// Put in the box
//
dc->StretchBlt(iXPosisiPreview , iYPosisiPreview ,
iLebar, iTinggi,
&memoriDC, 0, 0, rectMemory.Width(),
rectMemory.Height(), SRCCOPY);

//
// Cleaning Up
//
fnt.DeleteObject();
memoriDC.SelectObject(pOldBMP);
memoriDC.DeleteDC();
memBMP.DeleteObject();
prnDC.Detach();

//
pWnd->ReleaseDC(dc);
}


Comments

  • Chaque ghd pink aura un code de suivi unique qui peut être vérifié en suivant les instructions de la boîte

    Posted by esmhlh100 on 07/16/2013 02:02pm

    La meilleure chose à faire lorsque vous essayez de trouver défrisants bon marché est d'examiner la véritable valeur de n'importe quelle marque. Si vous allez à débourser plus de 100 £ pour quelqu'un, assurez-vous que vous obtenez votre argent vaut. Lire les commentaires des consommateurs, car ce sont les commentaires les plus honnêtes que vous obtiendrez dans l'industrie. Cela vous aidera à prendre la bonne décision lorsque vous êtes à la recherche pour les cheveux rettetang.Selvfølgelig pas cher est rose ghd n'est pas seulement une norme de tourbière styler ghd. C'est un ghd qui a été conçu pour recueillir des fonds pour des organisations caritatives du cancer du sein. En effet, un tel succès a été redresseurs rose que selon GHD il a abouti à 1 million de livres étant donné. Il ya aussi un grand succès auprès des célébrités comme Jennifer Aniston et Victoria Beckham. [url=http://ghdpascherfer.webgarden.es/]lisseur ghd styler[/url] Lorsque le mot settes bon marché dans le même théorème comme Journée Good Hair (GHD) GHD est le mot faux normalement pas si loin unna. Tout Dessverre qui a marqué GHD et semble trop beau pour être y intéressant de prix, normalement. Vous pouvez être désespérée pour GHD droit tige merke, mais vous devriez envisager d'autres rubans de nom aussi, car il est beaucoup plus sur le marché qui va donner deg le même vétérinaire results.I qu'il est souvent coutumier aux consommateurs un loquet en utsalgspris que le temps passe. La couche gjentatt de tendance avec les lecteurs DVD et autres appareils électroniques. C'est beaucoup moins cher de leur offrir une solution fiable sur le marché, c'est juste un notre web av magasiner. [url=http://bbeatsinorge.cabanova.com/]lisseur ghd pas cher[/url] GHD pas cher est tout ce que vous aviez trenge å lage parfait volum boucles de terrassement et de droite, grâce à sa technologie de pré-paiement et funksjoner intelligent. L'acquisition de nouveaux GHD plat Strykejern portée de main! Corps Avrundet donne une plus grande flexibilité dans le style et ils sont en mode veille - les plaines signifie que si vous n'avez pas Bruker pendant une demi-heure, ils ont juste si "bon taux" et détournez! Je appelant également tout un tas d'autres avanserte funksjoner, inkludert mode de protection contre la pluie j'aime tribunaux appelés ROM, réplique numérique de la température et céramique Høy-art plaqueur et vous verrez bientôt que noen spenning!

    Reply
  • Jordan shoes mentioned Gene to go for the variety, a division of Nike

    Posted by TaddyGaffic on 04/19/2013 01:28am

    In focus groups conducted at 80 community-based organizations around the country, Motivational Educational Entertainment of Philadelphia [url=http://markwarren.org.uk/goodbuy.cfm]nike free uk[/url] identified disturbing trends among youths ages 16 to 20. The "Just Say No" message of abstinence-only campaigns has been lost on this group of young people, who grew up during an era when the hip-hop sensibility of getting cash and clothes did not incorporate values of conscientious sexual behavior or social responsibility. Rappers who mingle [url=http://northernroofing.co.uk/roofins.cfm]nike free[/url] with glamorous-looking half-naked women rarely mention contraception while they're listing the number of compromising sexual situations they've been in lately. There are number of good brands in the market like Adidas, Nike, Reebok, Asics, Brooks, Puma etc. Most of these brands have shoes tailored for professional and amateur tennis players. New advanced technologies have made these shoes more player-friendly. After that, I eventually like to try to get down to the 150-160 range. I not entirely sure if that a healthy number for a gal my height or not, and I haven looked into it. But, I know that when I was 180 I still didn feel that [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] fit, so I think an extra 20 or so will help with that.. Lotto sneakers selling price are generally liable along with using the form of sneakers you choose on. Your Lotto sneakers established fact because of their style along with good quality plus the create. That they create sneakers coming from all varieties much like the loafers,Puma II Shoes, new sandals, sneakers along with task tennis shoes or anything else

    Reply
  • Blue can be another optionally available color regarding home litter.

    Posted by pletcherasy on 02/26/2013 11:53am

    Waste segregation could be the process involving sorting ones trash so that they can be properly dumped [url=http://www.sacmichaelkors.fr/michael-kors-montres-c-17.html]michael kors france[/url]. 2013 [url=http://www.achetersacslongchamp.net]sacs longchamp[/url]www.achetersacslongchamp.net is fearful to anticipate the fact years by now, the whole surrounding has already been health hazard. The good best way to try to make things easier is to have plastic-type bags using different colorations [url=http://www.burberrycanadaoutlet.org/burberry-wallet-c-30.html]burberry sale[/url] 2013. You don't need to plant shrubs nor pass the [url=http://www.sacmichaelkors.fr/sacs-michael-kors-nouvelle-c-10.html]michael kors[/url] road.

    Reply
  • Print on pages different from A4

    Posted by Legacy on 05/13/2003 12:00am

    Originally posted by: Gigo

    Trhere is way to make it?

    Reply
  • Print Preview Without MFC

    Posted by Legacy on 12/13/2002 12:00am

    Originally posted by: Dan

    Why is it in MFC if it says 'Without MFC'?

    Reply
  • Not proper Output

    Posted by Legacy on 05/23/2001 12:00am

    Originally posted by: Bakul

    Hi all,

    I have used this same code to generate Print Preview. I haven't changed even a bit of this code.

    But my problem is that I am getting a blank White Rectangle with Red Outline. Rectangel is also too small. There is nothing written on my screen in any part of output of my dialog box.

    So, can any of u suggest me solution to this problem?

    Reply
  • print preview command

    Posted by Legacy on 02/06/2000 12:00am

    Originally posted by: Anggy

    Wah gua kagak ngarti nang, yang paling gampang untuk print preview itu klik file-print preview..... :-)

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

Most Popular Programming Stories

More for Developers

RSS Feeds