﻿

# 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,
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.
Output: Drawacirclecenteredat
0
0
from-10,-10to10,10.
Drawahorizontallineacrossthewindowwiththegiveny-intercept.
Drawthetwopointsofintersectioninred.
Printoutthexvaluesofthepointsofintersection.
Formula:x
r2
y2
11. LineInformation.
Thisprogramallowstheusertodrawalinesegmentandthendisplayssomegraphicalandtextual
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.
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 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.
Youaretowriteaprogramthatallowstheusertodrawasimplehouseusingﬁvemouse-clicks. The
ﬁrsttwoclickswillbetheoppositecornersoftherectangularframeofthehouse.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.
Chapter6
DeﬁningFunctions
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.
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
theloop,andthesubsequentbarsaredrawninsideoftheloop.
Havingsimilarcodelikethisintwoplaceshassomedrawbacks.Obviously,oneissueishavingtowrite
thecodetwice.Amoresubtleproblemisthatthecodehastobemaintainedintwodifferentplaces.Shouldwe
decidetochangethecolororotherfacetsofthebars,wewouldhavetomakesurethesechangesoccurredin
bothplaces.Failingtokeeprelatedpartsofthecodeinsynchisacommonprobleminprogrammaintenance.
Functionscanbeusedtoreducecodeduplicationandmakeprogramsmoreunderstandableandeasierto
maintain.Beforeﬁxingupthefuturevalueprogram,let
'
stakelookatwhatfunctionshavetooffer.
6.2 Functions,Informally
Youcanthinkofafunctionasasubprogram—asmallprogram insideofaprogram. . Thebasicideaofa
functionisthatwewriteasequenceofstatementsandgivethatsequenceaname.Theinstructionscanthen
beexecutedatanypointintheprogrambyreferringtothefunctionname.
Thepartoftheprogramthatcreatesafunctioniscalledafunctiondeﬁnition. Whenafunctionis
subsequentlyusedinaprogram,wesaythatthedeﬁnitioniscalledorinvoked.Asinglefunctiondeﬁnition
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. Youmightwanttoﬁreup
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.
6.2. FUNCTIONS,INFORMALLY
87
Obviously,thereissomeduplicatedcodeinthisprogram. Forsuchasimpleprogram,that
'
snotabig
deal,butevenhereit
'
sabitannoyingtokeepretypingthesameline. Let
'
sintroduceafunctionthatprints
thelyricsoftheﬁrst,second,andfourthlines.
>>> def happy():
print "Happy birthday to you!"
Wehavedeﬁnedanewfunctioncalledhappy.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
'
>>> def singLucy():
happy()
happy()
print "Happy birthday, dear Lucy."
happy()
NowwecanwriteamainprogramthatsingstobothFredandLucy.
>>> def main():
singFred()
print
singLucy()
Thebareprintbetweenthetwofunctioncallsputsaspacebetweentheversesinouroutput. Andhere
'
s
theﬁnalproductinaction.
>>> 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
'
veremovedsomeoftheduplicationbydeﬁningthe
happyfunction.However,somethingstilldoesn
'
tfeelquiteright.Wehavetwofunctions,singFredand
createasingElmerfunctionthatlooksjustlikethoseforFredandLucy.Can
'
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
'
sﬁnishwithaprogramthatsingstoallthreeofourbirthdaypeople.
>>> def main():
sing("Fred")
print
sing("Lucy")
print
sing("Elmer")
Itdoesn
'
tgetmucheasierthanthat.
Hereisthecompleteprogramasamoduleﬁle.
# 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
'
veseenhowdeﬁningfunctionscanhelpsolvethecodeduplicationproblem,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.Speciﬁcally,weneedtoknowwhatyearthebarwill
befor,howtallthebarwillbe,andwhatwindowthebarwillbedrawnin.Thesethreevalueswillbesupplied
asparametersforthefunction.Here
'
sthefunctiondeﬁnition.
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,thedeﬁnitionofdrawBar.Don
'
tworry
yetifyoudon
'
6.4 FunctionsandParameters:TheGoryDetails
whichabarisbeingdrawnandtheheightofthebararethechangeablepartsinthedrawingofabar. But,
whyiswindowalsoaparametertothisfunction?Afterall,wewillbedrawingallofthebarsinthesame
window;itdoesn
'
tseemtochange.
Thereasonformakingwindowaparameterhastodowiththescopeofvariablesinfunctiondeﬁnitions.
Scopereferstotheplacesinaprogramwhereagivenvariablemaybereferenced.Remembereachfunction
isitsownlittlesubprogram.Thevariablesusedinsideofonefunctionarelocaltothatfunction,evenifthey
happentohavethesamenameasvariablesthatappearinsideofanotherfunction.
Theonlywayforafunctiontoseeavariablefromanotherfunctionisforthatvariabletobepassedasa
parameter.SincetheGraphWin(inthevariablewin)iscreatedinsideofmain,itisnotdirectlyaccessible
indrawBar. However,thewindowparameterindrawBargetsassignedthevalueofwinfrommain
whendrawBariscalled. Toseehowthishappens,weneedtotakeamoredetailedlookatthefunction
invocationprocess.
Afunctiondeﬁnitionlookslikethis.
def <name>(<formal-parameters>):
<body>
Thenameofthefunctionmustbeanidentiﬁer,andformal-parameters isa(possiblyempty)listof
variablenames(alsoidentiﬁers). 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
looksupthedeﬁnitionofsingandseesthatithasasingleformalparameter,person.Theformalparameter
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.Theﬁrststatementisanotherfunctioncall,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