c# display pdf in browser : Add pages to pdf without acrobat software Library dll winforms asp.net html web forms python-programming-an-introduction-to-computer-science9-part394

5.8. EXERCISES
83
5. Anarcherytargetconsistsofacentralcircleofyellowsurroundedbyconcentricringsofred,blue,
blackandwhite.Eachringhasthesame“width,”whichisthesameastheradiusoftheyellowcircle.
Writeaprogramthatdrawssuchatarget.Hint:Objectsdrawnlaterwillappearontopofobjectsdrawn
earlier.
6. Writeaprogramthatdrawssomesortofface.
7. WriteaprogramthatdrawsawinterscenewithaChristmastreeandasnowman.
8. Writeaprogramthatdraws5diceonthescreendepictingastraight(1,2,3,4,5or2,3,4,5,6).
9. Modifythegraphicalfuturevalueprogramsothattheinput(principalandapr)alsoaredoneina
graphicalfashionusingEntryobjects.
10. CircleIntersection. . Writeaprogramthatcomputestheintersectionofacirclewithahorizontalline
anddisplaystheinformationtextuallyandgraphically.
Input: Radiusofthecircleandthey-interceptoftheline.
Output: Drawacirclecenteredat
0
0
withthegivenradiusinawindowwithcoordinatesrunning
from-10,-10to10,10.
Drawahorizontallineacrossthewindowwiththegiveny-intercept.
Drawthetwopointsofintersectioninred.
Printoutthexvaluesofthepointsofintersection.
Formula:x
r2
y2
11. LineInformation.
Thisprogramallowstheusertodrawalinesegmentandthendisplayssomegraphicalandtextual
informationaboutthelinesegment.
Input: 2mouseclicksfortheendpointsofthelinesegment.
Output: Drawthemidpointofthesegmentincyan.
Drawtheline.
Printthelengthandtheslopeoftheline.
Formulas:
dx
x
2
x
1
dy
y
2
y
1
slope
dy
dx
length
dx2
dy2
12. RectangleInformation.
Thisprogramdisplaysinformationaboutarectangledrawnbytheuser.
Input: 2mouseclicksfortheoppositecornersofarectangle.
Output: Drawtherectangle.
Printtheperimeterandareaoftherectangle.
Formulas:
area
length
width
perimeter
2
length
width
13. TriangleInformation.
Sameaspreviousproblem,butwith3clicksfortheverticiesofatriangle.
Formulas: Forperimeter,seelengthfromlineproblem.
area
s
s
a
s
b
s
c
wherea
b
andcarethelengthsofthesidesands
a
b
c
2
Add pages to pdf without acrobat - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
add page number to pdf hyperlink; add page numbers pdf
Add pages to pdf without acrobat - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
add page number to pdf preview; add page numbers to pdf files
84
CHAPTER5. OBJECTSANDGRAPHICS
14. 5-clickhouse.
Youaretowriteaprogramthatallowstheusertodrawasimplehouseusingfivemouse-clicks. The
firsttwoclickswillbetheoppositecornersoftherectangularframeofthehouse.Thethirdclickwill
indicatethecenterofthetopedgeofarectangulardoor. Thedoorshouldhaveatotalwidththatis
1
5
ofthewidthofthehouseframe.Thesidesofthedoorshouldextendfromthecornersofthetopdown
tothebottomoftheframe.Thefourthclickwillindicatethecenterofasquarewindow.Thewindow
ishalfaswideasthedoor.Thelastclickwillindicatethepeakoftheroof.Theedgesoftheroofwill
extendfromthepointatthepeaktothecornersofthetopedgeofthehouseframe.
1
2
4
3
5
C# PDF Converter Library SDK to convert PDF to other file formats
manipulate & convert standard PDF documents in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat.
add a page to a pdf in acrobat; add and remove pages from a pdf
C# powerpoint - PowerPoint Conversion & Rendering in C#.NET
in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. PowerPoint to PDF Conversion.
adding a page to a pdf in reader; add page numbers to pdf in reader
Chapter6
DefiningFunctions
Theprogramsthatwehavewrittensofarcompriseasinglefunction,usuallycalledmain.Wehavealsobeen
usingpre-writtenfunctionsandmethodsincludingbuilt-inPythonfunctions(e.g.,abs),functionsfromthe
Pythonstandardlibraries(e.g.,math.sqrt,string.split),andobjectmethodsfromthegraphics
module(e.g.,myPoint.getX()).
Functionsareanimportanttoolforbuildingsophisticatedprograms. Thischaptercoversthewhysand
howsofdesigningyourownfunctionstomakeyourprogramseasiertowriteandunderstand.
6.1 TheFunctionofFunctions
Inthepreviouschapter,welookedatagraphicsolutiontothefuturevalueproblem.Thisprogrammakesuse
ofthegraphicslibrarytodrawabarchartshowingthegrowthofaninvestment.Hereistheprogramas
weleftit:
# futval_graph2.py
from graphics s import t *
def main():
# Introduction
print "This s program m plots the growth of a a 10-year r investment."
# Get principal l and d interest rate
principal = = input("Enter the initial principal: : ")
apr = input("Enter r the e annualized interest t rate: : ")
# Create a a graphics s window with labels on n left t edge
win = GraphWin("Investment t Growth h Chart", , 640, , 480)
win.setBackground("white")
win.setCoords(-1.75,-200, 11.5, , 10400)
Text(Point(-1, 0), , ' 0.0K').draw(win)
Text(Point(-1, 2500), , ' 2.5K').draw(win)
Text(Point(-1, 5000), , ' 5.0K').draw(win)
Text(Point(-1, 7500), , ' 7.5k').draw(win)
Text(Point(-1, 10000), , '10.0K').draw(win)
# Draw bar r for r initial principal
bar = Rectangle(Point(0, , 0), , Point(1, principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
85
C# Word - Word Conversion in C#.NET
Word documents in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. Word to PDF Conversion.
adding pages to a pdf document in preview; add page numbers to pdf files
C# Windows Viewer - Image and Document Conversion & Rendering in
image and document in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. Convert to PDF.
add pdf pages together; add page to pdf in preview
86
CHAPTER6. DEFININGFUNCTIONS
# Draw a bar r for r each subsequent year
for year in n range(1, , 11):
principal = = principal * (1 + apr)
bar = Rectangle(Point(year, 0), Point(year+1, , principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
raw_input("Press <Enter> > to quit.")
Thisiscertainlyaworkableprogram,butthereisanaggingissueofprogramstylethatreallyshouldbe
addressed. Noticethatthisprogramdrawsbarsintwodifferentplaces. Theinitialbarisdrawnjustbefore
theloop,andthesubsequentbarsaredrawninsideoftheloop.
Havingsimilarcodelikethisintwoplaceshassomedrawbacks.Obviously,oneissueishavingtowrite
thecodetwice.Amoresubtleproblemisthatthecodehastobemaintainedintwodifferentplaces.Shouldwe
decidetochangethecolororotherfacetsofthebars,wewouldhavetomakesurethesechangesoccurredin
bothplaces.Failingtokeeprelatedpartsofthecodeinsynchisacommonprobleminprogrammaintenance.
Functionscanbeusedtoreducecodeduplicationandmakeprogramsmoreunderstandableandeasierto
maintain.Beforefixingupthefuturevalueprogram,let
'
stakelookatwhatfunctionshavetooffer.
6.2 Functions,Informally
Youcanthinkofafunctionasasubprogram—asmallprogram insideofaprogram. . Thebasicideaofa
functionisthatwewriteasequenceofstatementsandgivethatsequenceaname.Theinstructionscanthen
beexecutedatanypointintheprogrambyreferringtothefunctionname.
Thepartoftheprogramthatcreatesafunctioniscalledafunctiondefinition. Whenafunctionis
subsequentlyusedinaprogram,wesaythatthedefinitioniscalledorinvoked.Asinglefunctiondefinition
maybecalledatmanydifferentpointsofaprogram.
Let
'
stakeaconcreteexample. Supposeyouwanttowriteaprogramthatprintsoutthelyricstothe
“HappyBirthday”song.Thestandardlyricslooklikethis.
Happy birthday y to o you!
Happy birthday y to o you!
Happy birthday, , dear r <insert-name>.
Happy birthday y to o you!
We
'
regoingtoplaywiththisexampleintheinteractivePythonenvironment. Youmightwanttofireup
Pythonandtrysomeofthisoutforyourself.
Asimpleapproachtothisproblemistousefourprintstatements. Here
'
saninteractivesessionthat
createsaprogramforsingingHappyBirthdaytoFred.
>>> def main():
print "Happy y birthday to you!"
print "Happy y birthday to you!"
print "Happy y birthday, dear Fred."
print "Happy y birthday to you!"
Wecanthenrunthisprogramtogetourlyrics.
>>> main()
Happy birthday y to o you!
Happy birthday y to o you!
Happy birthday, , dear r Fred.
Happy birthday y to o you!
C# Excel - Excel Conversion & Rendering in C#.NET
documents in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. Excel to PDF Conversion.
add page pdf reader; add page numbers to pdf online
6.2. FUNCTIONS,INFORMALLY
87
Obviously,thereissomeduplicatedcodeinthisprogram. Forsuchasimpleprogram,that
'
snotabig
deal,butevenhereit
'
sabitannoyingtokeepretypingthesameline. Let
'
sintroduceafunctionthatprints
thelyricsofthefirst,second,andfourthlines.
>>> def happy():
print "Happy birthday to you!"
Wehavedefinedanewfunctioncalledhappy.Hereisanexampleofwhatitdoes.
>>> happy()
Happy birthday y to o you!
InvokingthehappycommandcausesPythontoprintalineofthesong.
NowwecanredotheverseforFredusinghappy.Let
'
scallournewversionsingFred.
>>> def singFred():
happy()
happy()
print "Happy birthday, dear Fred."
happy()
Thisversionrequiredmuchlesstyping,thankstothehappycommand.Let
'
stryprintingthelyricsforFred
justtomakesureitworks.
>>> singFred()
Happy birthday y to o you!
Happy birthday y to o you!
Happy birthday, , dear r Fred.
Happy birthday y to o you!
Sofar,sogood.Nowsupposethatit
'
salsoLucy
'
sbirthday,andwewanttosingaverseforFredfollowed
byaverseforLucy.We
'
vealreadygottheverseforFred;wecanprepareoneforLucyaswell.
>>> def singLucy():
happy()
happy()
print "Happy birthday, dear Lucy."
happy()
NowwecanwriteamainprogramthatsingstobothFredandLucy.
>>> def main():
singFred()
print
singLucy()
Thebareprintbetweenthetwofunctioncallsputsaspacebetweentheversesinouroutput. Andhere
'
s
thefinalproductinaction.
>>> main()
Happy birthday y to o you!
Happy birthday y to o you!
Happy birthday, , dear r Fred.
Happy birthday y to o you!
Happy birthday y to o you!
Happy birthday y to o you!
Happy birthday, , dear r Lucy.
Happy birthday y to o you!
88
CHAPTER6. DEFININGFUNCTIONS
Wellnow,thatcertainlyseemstowork,andwe
'
veremovedsomeoftheduplicationbydefiningthe
happyfunction.However,somethingstilldoesn
'
tfeelquiteright.Wehavetwofunctions,singFredand
singLucy,thatarealmostidentical. Followingthisapproach,addingaverseforElmerwouldhaveus
createasingElmerfunctionthatlooksjustlikethoseforFredandLucy.Can
'
twedosomethingaboutthe
proliferationofverses?
NoticethattheonlydifferencebetweensingFredandsingLucyisthenameattheendofthethird
printstatement.Theversesareexactlythesameexceptforthisonechangingpart.Wecancollapsethese
twofunctionstogetherbyusingaparameter.Let
'
swriteagenericfunctioncalledsing.
>>> def sing(person):
happy()
happy()
print "Happy Birthday, dear", person + + "."
happy()
Thisfunctionmakesuseofaparameternamedperson. Aparameterisavariablethatisinitializedwhen
thefunctioniscalled.WecanusethesingfunctiontoprintaverseforeitherFredorLucy.Wejustneedto
supplythenameasaparameterwhenweinvokethefunction.
>>> sing("Fred")
Happy birthday y to o you!
Happy birthday y to o you!
Happy Birthday, , dear r Fred.
Happy birthday y to o you!
>>> sing("Lucy")
Happy birthday y to o you!
Happy birthday y to o you!
Happy Birthday, , dear r Lucy.
Happy birthday y to o you!
Let
'
sfinishwithaprogramthatsingstoallthreeofourbirthdaypeople.
>>> def main():
sing("Fred")
print
sing("Lucy")
print
sing("Elmer")
Itdoesn
'
tgetmucheasierthanthat.
Hereisthecompleteprogramasamodulefile.
# happy.py
def happy():
print "Happy y Birthday y to you!"
def sing(person):
happy()
happy()
print "Happy y birthday, , dear", person + "."
happy()
def main():
sing("Fred")
print
6.3. FUTUREVALUEWITHAFUNCTION
89
sing("Lucy")
print
sing("Elmer")
6.3 FutureValuewithaFunction
Nowthatyou
'
veseenhowdefiningfunctionscanhelpsolvethecodeduplicationproblem,let
'
sreturnto
thefuturevaluegraph.Recalltheproblemisthatbarsofthegraphareprintedattwodifferentplacesinthe
program.
Thecodejustbeforethelooplookslikethis.
# Draw bar for r initial l principal
bar = Rectangle(Point(0, , 0), , Point(1, principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
Andthecodeinsideoftheloopisasfollows.
bar = Rectangle(Point(year, , 0), , Point(year+1, , principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
Let
'
strytocombinethesetwointoasinglefunctionthatdrawsabaronthescreen.
Inordertodrawthebar,weneedsomeinformation.Specifically,weneedtoknowwhatyearthebarwill
befor,howtallthebarwillbe,andwhatwindowthebarwillbedrawnin.Thesethreevalueswillbesupplied
asparametersforthefunction.Here
'
sthefunctiondefinition.
def drawBar(window, , year, , height):
# Draw a bar r in n window for given year with h given n height
bar = Rectangle(Point(year, , 0), , Point(year+1, , height))
bar.setFill("green")
bar.setWidth(2)
bar.draw(window)
Tousethisfunction, wejustneedtosupplyvaluesforthethreeparameters. . Forexample, , ifwinisa
GraphWin,wecandrawabarforyear0andaprincipalof$2,000byinvokingdrawBarlikethis.
drawBar(win, 0, , 2000)
IncorporatingthedrawBarfunction,hereisthelatestversionofourfuturevalueprogram.
# futval_graph3.py
from graphics s import t *
def drawBar(window, , year, , height):
# Draw a bar r in n window starting at year with h given n height
bar = Rectangle(Point(year, , 0), , Point(year+1, , height))
bar.setFill("green")
bar.setWidth(2)
bar.draw(window)
def main():
# Introduction
print "This s program m plots the growth of a a 10-year r investment."
90
CHAPTER6. DEFININGFUNCTIONS
# Get principal l and d interest rate
principal = = input("Enter the initial principal: : ")
apr = input("Enter r the e annualized interest t rate: : ")
# Create a a graphics s window with labels on n left t edge
win = GraphWin("Investment t Growth h Chart", , 320, , 240)
win.setBackground("white")
win.setCoords(-1.75,-200, 11.5, , 10400)
Text(Point(-1, 0), , ' 0.0K').draw(win)
Text(Point(-1, 2500), , ' 2.5K').draw(win)
Text(Point(-1, 5000), , ' 5.0K').draw(win)
Text(Point(-1, 7500), , ' 7.5k').draw(win)
Text(Point(-1, 10000), , '10.0K').draw(win)
# Draw bar r for r initial principal
drawBar(win, 0, , principal)
# Draw a bar r for r each subsequent year
for year in n range(1, , 11):
principal = = principal * (1 + apr)
drawBar(win, year, , principal)
raw_input("Press <Enter> > to quit.")
YoucanseehowdrawBarhaseliminatedtheduplicatedcode.Shouldwewishtochangetheappearance
ofthebarsinthegraph,weonlyneedtochangethecodeinonespot,thedefinitionofdrawBar.Don
'
tworry
yetifyoudon
'
tunderstandeverydetailofthisexample.Youstillhavesomethingstolearnaboutfunctions.
6.4 FunctionsandParameters:TheGoryDetails
YoumaybewonderingaboutthechoiceofparametersforthedrawBarfunction. Obviously,theyearfor
whichabarisbeingdrawnandtheheightofthebararethechangeablepartsinthedrawingofabar. But,
whyiswindowalsoaparametertothisfunction?Afterall,wewillbedrawingallofthebarsinthesame
window;itdoesn
'
tseemtochange.
Thereasonformakingwindowaparameterhastodowiththescopeofvariablesinfunctiondefinitions.
Scopereferstotheplacesinaprogramwhereagivenvariablemaybereferenced.Remembereachfunction
isitsownlittlesubprogram.Thevariablesusedinsideofonefunctionarelocaltothatfunction,evenifthey
happentohavethesamenameasvariablesthatappearinsideofanotherfunction.
Theonlywayforafunctiontoseeavariablefromanotherfunctionisforthatvariabletobepassedasa
parameter.SincetheGraphWin(inthevariablewin)iscreatedinsideofmain,itisnotdirectlyaccessible
indrawBar. However,thewindowparameterindrawBargetsassignedthevalueofwinfrommain
whendrawBariscalled. Toseehowthishappens,weneedtotakeamoredetailedlookatthefunction
invocationprocess.
Afunctiondefinitionlookslikethis.
def <name>(<formal-parameters>):
<body>
Thenameofthefunctionmustbeanidentifier,andformal-parameters isa(possiblyempty)listof
variablenames(alsoidentifiers). Theformalparameters,likeallvariablesusedinthefunction,areonly
accessibleinthebodyofthefunction.Variableswithidenticalnameselswhereintheprogramaredistinct
fromtheformalparametersandvariablesinsideofthefunctionbody.
Afunctioniscalledbyusingitsnamefollowedbyalistofactualparametersorarguments.
<name>(<actual-parameters>)
6.4. FUNCTIONSANDPARAMETERS:THEGORYDETAILS
91
WhenPythoncomestoafunctioncall,itinitiatesafour-stepprocess.
1. Thecallingprogramsuspendsatthepointofthecall.
2. Theformalparametersofthefunctiongetassignedthevaluessuppliedbytheactualparametersinthe
call.
3. Thebodyofthefunctionisexecuted.
4. Controlreturnstothepointjustafterwherethefunctionwascalled.
ReturningtotheHappyBirthdayexample,let
'
stracethroughthesingingoftwoverses. Hereispartof
thebodyfrommain.
sing("Fred")
print
sing("Lucy")
...
WhenPythongetstosing("Fred"),executionofmainistemporarilysuspended.Atthispoint,Python
looksupthedefinitionofsingandseesthatithasasingleformalparameter,person.Theformalparameter
isassignedthevalueoftheactual,soitisasifwehadexecutedthisstatement:
person = "Fred"
AsnapshotofthissituationisshowninFigure6.1.Noticethevariablepersoninsideofsinghasjustbeen
initialized.
sing("Fred")
print
sing("Lucy")
def main():
def sing(person):
happy()
happy()
print "Happy birthday, dear", person + "."
happy()
person = "Fred"
person: "Fred"
Figure6.1:Illustrationofcontroltransferringtosing.
Atthispoint,Pythonbeginsexecutingthebodyofsing.Thefirststatementisanotherfunctioncall,this
onetohappy.Pythonsuspendsexecutionofsingandtransferscontroltothecalledfunction.Thebodyof
happyconsistsofasingleprint. Thisstatementisexecuted,andthencontrolreturnstowhereitleftoff
insing.Figure6.2showsasnapshotoftheexecutionsofar.
sing("Fred")
print
sing("Lucy")
def main():
def sing(person):
happy()
happy()
print "Happy birthday, dear", person + "."
happy()
def happy():
print "Happy Birthday to you!"
person = "Fred"
person: "Fred"
Figure6.2:Snaphotofcompletedcalltohappy.
ExecutioncontinuesinthismannerwithPythonmakingtwomoresidetripsbacktohappytocomplete
theexecutionofsing. WhenPythongettotheendofsing,controlthenreturnstomainandcontinues
immediatelyafterthefunctioncall. Figure6.3showswhereweareatthatpoint. . Noticethattheperson
92
CHAPTER6. DEFININGFUNCTIONS
sing("Fred")
print
sing("Lucy")
def main():
def sing(person):
happy()
happy()
print "Happy birthday, dear", person + "."
happy()
person = "Fred"
Figure6.3:Snaphotofcompletedcalltosing.
variableinsinghasdisappeared.Thememoryoccupiedbylocalfunctionvariablesisreclaimedwhenthe
functionfinishes.Localvariablesdonotretainanyvaluesfromonefunctionexecutiontothenext.
Thenextstatementtoexecuteisthebareprintstatementinmain. Thisproducesablanklineinthe
output.ThenPythonencountersanothercalltosing.Asbefore,controltransferstothefunctiondefinition.
Thistimetheformalparameteris"Lucy".Figure6.4showsthesituationassingbeginstoexecuteforthe
secondtime.
sing("Fred")
print
sing("Lucy")
def main():
def sing(person):
happy()
happy()
print "Happy birthday, dear", person + "."
happy()
person = "Lucy"
person: "Lucy"
Figure6.4:Snaphotofsecondcalltosing.
Nowwe
'
llfastforwardtotheend.ThefunctionbodyofsingisexecutedforLucy(withthreesidetrips
throughhappy)andcontrolreturnstomainjustafterthepointofthefunctioncall. Nowwehavereached
thebottomofourcodefragment,asillustratedbyFigure6.5. Thesethreestatementsinmainhavecaused
singtoexecutetwiceandhappytoexecutesixtimes.Overall,ninetotallinesofoutputweregenerated.
sing("Fred")
print
sing("Lucy")
def main():
def sing(person):
happy()
happy()
print "Happy birthday, dear", person + "."
happy()
person = "Lucy"
Figure6.5:Completionofsecondcalltosing.
Hopefullyyou
'
regettingthehangofhowfunctioncallsactuallywork. Onepointthatthisexampledid
notaddressistheuseofmultipleparameters. Whenafunctiondefinitionhasseveralparameters,theactual
parametersarematchedupwiththeformalparametersbyposition.Thefirstactualparameterisassignedto
thefirstformalparamter,thesecondactualisassignedtothesecondformal,etc.
Asanexample,lookagainattheuseofthedrawBarfunctionfromthefuturevalueprogram. Hereis
thecalltodrawtheinitialbar.
drawBar(win, 0, , principal)
WhenPythontransferscontroltodrawBar,theseparametersarematcheduptotheformalparametersin
thefunctionheading.
def drawBar(window, , year, , height):
Documents you may be interested
Documents you may be interested