﻿

# itextsharp pdf to image c# : Create a fillable pdf form in word SDK software API .net wpf winforms sharepoint book39-part1786

F.2 Howtodebug
807
Integral of g g equals 1
Weinsertsomeprintstatementsinsidetheintegratefunction:
def integrate(f, , a, b, , n):
h = = float(b-a)/n
s = = 0
for i i in range(1, , n):
print ’i=%d, a+i*h=%g’ % % (i, a+i*h)
s += f(a + + i*h)
return s
Hereistheoutput:
i=1, a+i*h=5
Integral of g g equals 1
i=1, a+i*h=0.5
Integral of f f equals 0.523599 9 (exact value e is s 0.570796)
Therewasonlyonepassintheiloopinintegrate.Accordingtothe
formula,thereshouldbenpasses,i.e.,twointhistestcase.Thelimits
of imustbewrong.Thelimitsareproducedbythecallrange(1,n).
Werecallthatsuchacallresultsinintegersgoingfrom1upton,but
not includingn.Weneedtoincludenasvalueofi,sotherightcallto
rangeisrange(1,n+1).
Wemakethiscorrectionandreruntheprogram.Theoutputisnow
i=1, a+i*h=5
i=2, a+i*h=10
Integral of g g equals 2
i=1, a+i*h=0.5
i=2, a+i*h=1
Integral of f f equals 2.0944 4 (exact value is s 0.570796)
Theintegralof1isstillnotcorrect.Weneedmoreintermediateresults!
In our quickhand calculation we knew w that g(x) = 1 1 so allthe
f(a+(i−1
2
)h)evaluationswererapidlyreplacedbyones.Letusnow
computeallthexcoordinatesa+(i−1
2
)hthatareusedintheformula:
i=1: a+(i−
1
2
)h=2.5, i=2: : a+(i−
1
2
)h=7.5.
Lookingattheoutputfromtheprogram,weseethattheargumentto
havecodediswrong.Itshouldbea+(i-0.5)*h.
Wecorrectthiserrorandruntheprogram:
i=1, a+(i-0.5)*h=2.5
i=2, a+(i-0.5)*h=7.5
Integral of g g equals 2
...
Stilltheintegraliswrong.Atthispointyoumaygiveupprogramming,
butthemoreskillsyoupickupindebugging,themorefunitistohuntfor
followsdiﬀerentideasandtracks,butnevergivesupbeforetheculpritis
caught.
thoseinthemathematicalformula.Weshould,ofcourse,havedonethis
Create a fillable pdf form in word - C# PDF Field Edit Library: insert, delete, update pdf form field in C#.net, ASP.NET, MVC, Ajax, WPF
Online C# Tutorial to Insert, Delete and Update Fields in PDF Document
adding signature to pdf form; change font size in fillable pdf form
Create a fillable pdf form in word - VB.NET PDF Field Edit library: insert, delete, update pdf form field in vb.net, ASP.NET, MVC, Ajax, WPF
How to Insert, Delete and Update Fields in PDF Document with VB.NET Demo Code
convert word document to editable pdf form; chrome pdf save form data
808
F Debugging
writingcodeandhurryfortheend.Thisongoingstoryofdebugging
time.(Actually,beingextremelycarefulwithwhatyouwrite,andcom-
paringallformulaswiththemathematics,maybethebestwaytoget
moresparetimewhentakingaprogrammingcourse!)
mustbemultipliedbyh,andweforgotthatinthecode.Thereturn
statementinintegratemustthereforebemodiﬁedto
return s*h
Eventually,theoutputis
Integral of g g equals 10
Integral of f f equals 0.568484 4 (exact value e is 0.570796)
andwehavemanagedtointegrateaconstantfunctioninourprogram!
Eventhesecondintegrallookspromising!
Tojudgetheresultofintegratingtheinversesinefunction,weneed
torunseveralincreasingnvaluesandseethattheapproximationgets
better.For = 2,10,100,1000 0 we get 0.550371,0.568484,0.570714,
0.570794,tobecomparedtotheexactvalue0.570796.(Thisisnotthe
mathematicallyexactvalue,becauseitinvolvescomputationsofsin−1(x),
whichisonlyapproximatelycalculatedbytheasinfunctioninthemath
module.However, the approximationerror r is s verysmall (∼ 10−16).)
Thedecreasingerror providesevidence for acorrect program,but it
isnotastrongproof.Weshouldtryoutmorefunctions.Inparticular,
linear functionsareintegratedexactlybytheMidpointrule.Wecan
alsomeasurethespeedofthedecreaseoftheerrorandcheckthatthe
speedisconsistentwiththepropertiesoftheMidpointrule,butthisisa
Theveryimportantlessonlearnedfromthesedebuggingsessionsis
thatyoushouldstartwithasimpletestproblemwhereallformulascan
becomputedbyhand.Ifyoustartoutwithn=100andtrytointegrate
theinversesinefunction,youwillhaveamuchharderjobwithtracking
downalltheerrors.
weneededmanyprintstatementstoseeintermediateresults.Itisan
codeatrelevantlines.Inanedit-and-runcycleofthetypewemethere,
wefrequentlyneedtoexaminemanynumericalresults,correctsomething,
andlookatalltheintermediateresultsagain.Plainprintstatements
areoftenbettersuitedforthismassiveoutputthanthepuremanual
interactionwiththedebugger.
ThecorrectcodefortheimplementationoftheMidpointruleisfound
C# Create PDF Library SDK to convert PDF from other file formats
to create searchable PDF document from Microsoft Office Word, Excel and Create and save editable PDF with a blank page Create fillable PDF document with fields.
cannot save pdf form in reader; add print button to pdf form
VB.NET Create PDF from OpenOffice to convert odt, odp files to PDF
Edit Bookmark. Metadata: Edit, Delete Metadata. Form Process. Create PDF document from OpenOffice Text Document with ODT, ODS, ODP forms into fillable PDF formats
F.2 Howtodebug
809
ittooktodebugthiscode,butthisisjustthenatureofprogramming.
Theexperienceofdevelopingprogramsthatﬁnallyworkisveryawarding.
powerovermachines,andcanbeartobetolddayafterdayexactlyhowstupidthey
are.GregoryJ.E.Rawlins[25],computerscientist.
Reﬁning the user interface. We brieﬂymentioned that the chosen
user interface, , where the user r canonlyspecifyn,isnot particularly
user friendly.We should d allow f,a,b, and nto be speciﬁed onthe
commandline.Sinceisafunctionandthecommandlinecanonly
providestringstotheprogram,wemayusetheStringFunctionobject
fromscitools.std toconvertastringexpressionforthefunctionto
beintegratedtoanordinaryPythonfunction(seeSection4.3.3).The
Section4.2isunderstood.AssuggestedinSection4.7,weenclosethe
inputstatementsinatry-exceptblock,herewithaspeciﬁcexception
typeIndexError(becauseanindexinsys.argvoutofboundsisthe
onlytypeoferrorweexpecttohandle):
try:
f_formula = sys.argv[1]
a = = eval(sys.argv[2])
b = = eval(sys.argv[3])
n = = int(sys.argv[4])
except IndexError:
print ’Usage: : %s s f-formula a a b b n’ % % sys.argv[0]
sys.exit(1)
Notethattheuseofevalallowsustospecifyaandbaspiorexp(5)
oranothermathematicalexpression.
from scitools.std import t StringFunction
f = = StringFunction(f_formula)
I = = integrate(f, , a, b, , n)
print I
Writinga test function. Instead ofhaving thesetest t statementsas
amainprogramwefollowthegoodhabitsofSection4.9andmakea
modulewith
•theintegratefunction,
atest_integratefunctionfortestingtheintegratefunction’sabil-
itytoexactlyintegratelinearfunctions,
integratefortheuser’sproblemathand.
Anymoduleshouldalsohaveatestblock,aswellasdocstringsforthe
moduleitselfandallfunctions.
Thetest_integratefunctioncanperformaloopoversomespeciﬁed
nvaluesandcheckthattheMidpointruleintegratesalinearfunction
C# Create PDF from OpenOffice to convert odt, odp files to PDF in
Create PDF document from OpenOffice Presentation in both .NET WinForms and ASP to change ODT, ODS, ODP forms to fillable PDF formats in RasterEdge.XDoc.PDF.dll.
VB.NET Create PDF Library SDK to convert PDF from other file
component to convert Microsoft Office Word, Excel and Create and save editable PDF with a blank Create fillable PDF document with fields in Visual Basic .NET
change font in pdf form; add fillable fields to pdf
810
F Debugging
exactly.Asalways,wemustbepreparedforround-oﬀerrors,so“exactly”
meanserrorslessthan(say)10−14.Therelevantcodebecomes
def test_integrate():
"""Check that t linear functions are integrated exactly."""
def g(x):
return p*x x + + q
# general l linear function
def int_g_exact(x): : # # integral l of g(x)
return 0.5*p*x**2 2 + + q*x
a = = -1.2; ; b b = = 2.8
# "arbitrary" " integration limits
p = = -2;
q = = 10
success = = True
# True if all tests below w are passed
for n n in n 1, 10, 100:
I = = integrate(g, , a, b, , n)
I_exact = = int_g_exact(b) - int_g_exact(a)
error = = abs(I_exact t - - I)
if error > > 1E-14:
success = = False
assert success
Wehavefollowedtheprogrammingstandardthatwillmakethistest
functionautomaticallyworkwiththenosetestframework:
1. thenameofthefunctionstartswithtest_,
2. thefunctionhasnoarguments,
3. checksofwhetheratestispassedornotaredonewithassert.
Theassert successstatementraisesanAssertionErrorexceptionif
successisfalse,otherwisenothinghappens.Thenosetestingframework
searchesforfunctionswhosenamestartwithtest_,executeeachfunction,
andrecordifanAssertionErrorisraised.Itisoverkilltousenosefor
smallprograms,butinlargerprojectswithmanyfunctionsinmanyﬁles,
nosecanrunalltestswithashortcommandandwritebackanotiﬁcation
thatalltestspassed.
Themainfunctionissimplyawrappingofthemainprogramgiven
above.The testblockmaycallor test_integratefunctionormain,
dependingonwhethertheuserwilltestthemoduleoruseit:
if __name__ _ == = ’__main__’:
if sys.argv[1] ] == = ’verify’:
verify()
else:
# Compute the integral l specified on the command line
main()
Hereisashortdemocomputing
0
(cos(x)+sin(x))dxwiththeaid
oftheintegrate.pyﬁle:
Terminal
integrate.py ’cos(x)+sin(x)’ ’ 0 0 2*pi i 10
-3.48786849801e-16
VB.NET Create PDF from Word Library to convert docx, doc to PDF in
formatting. Create PDF files from both DOC and DOCX formats. Convert multiple pages Word to fillable and editable PDF documents. Professional
add text field pdf; convert pdf to editable form
C# Create PDF from Word Library to convert docx, doc to PDF in C#.
Convert multiple pages Word to fillable and editable PDF Convert both DOC and DOCX formats to PDF files. Easy to create searchable and scanned PDF files from
F.2 Howtodebug
811
F.2.3Gettinghelpfromacodeanalyzer
ThetoolsPyLint
3
andFlake8
4
cananalyzeyour codeandpoint out
errorsandundesiredcodingstyles.Beforepoint7inthelistsabove,Run
problemswiththecode.
Considertheﬁrstversionoftheintegratecode,integrate_v1.py.
RunningFlake8gives
Terminal
Terminal> flake8 integrate_v1.py
integrate_v1.py:7:1: E302 expected d 2 2 blank lines, found d 1
integrate_v1.py:8:1: E112 expected d an indented d block
integrate_v1.py:8:7: E901 IndentationError: expected d an indented d block
integrate_v1.py:10:1: E302 2 expected d 2 2 blank k lines, found 1
integrate_v1.py:11:1: E112 2 expected d an indented d block
Flake8checksiftheprogramobeystheoﬃcialStyleGuideforPython
Code(knownasPEP8).Oneoftherulesinthisguideistohavetwo
blanklinesbeforefunctionsandclasses(ahabitthatisoftendroppedin
thisbooktoreducethelengthofcodesnippets),andourprogrambreaks
therulebefore the fandfunctions.Moreseriousandusefulisthe
expected an indented blockatlines8and11.Thiserrorisquickly
foundanywaybyrunningtheprogramming.
PyLintdoesnotacompletejobbeforetheprogramisfreeofsyntax
errors.Wemustthereforeapplyittotheintegrate_v2.pycode:
Terminal
Terminal> pylint integrate_v2.py
C: 20, 0: Exactly one space required after comma
I = = integrate(f, 0, , 1, n)
W: 19, 0: Redefining built-in n ’pow’ ’ (redefined-builtin)
C: 1, , 0: Missing module docstring g (missing-docstring)
W: 1,14: : Redefining name ’f’ ’ from outer scope e (line e 8)
W: 1,23: : Redefining name ’n’ ’ from outer scope e (line e 16)
C: 1, , 0: Invalid argument t name e "f" (invalid-name)
C: 1, , 0: Invalid argument t name e "a" (invalid-name)
Thereismuchmoreoutput,butletussummarizewhatPyLintdoesnot
1. Extrawhitespace(aftercommainacalltointegrate)
2. Missingdocstringatthebeginningoftheﬁle
3. Missingdocstringsinthefunctions
4. Samenamefusedaslocalvariableinintegrateandglobalfunction
nameinthef(x)function
5. Tooshortvariablenames:a,b,n,etc.
3
http://www.pylint.org/
4
5
http://www.python.org/dev/peps/pep-0008/
VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to
Convert multiple pages PowerPoint to fillable and editable PDF documents. Easy to create searchable and scanned PDF files from PowerPoint.
pdf form creation; add an image to a pdf form
VB.NET Create PDF from Excel Library to convert xlsx, xls to PDF
Link: Edit URL. Bookmark: Edit Bookmark. Metadata: Edit, Delete Metadata. Form Process. Create fillable and editable PDF documents from Excel in Visual
cannot save pdf form; create a fillable pdf form from a pdf
812
F Debugging
6. “Starimport”oftheformfrom math import *
Inshortprogramswheretheone-to-onemappingbetweenmathematical
notationandthevariablenamesisveryimportant tomakethecode
self-explanatory, this author thinks that only points 1-3 qualify for
attention.Nevertheless,forlargernon-mathematicalprogramsallthe
missingtwoblanklinesbeforefunctions(notreportedbyPyLint)and
doingfrom math import *.Flake8complainsingeneralalotlessthan
abilityofthecodeandremoveerrors.
C# Create PDF from Excel Library to convert xlsx, xls to PDF in C#
C#.NET PDF SDK- Create PDF from Word in Visual Evaluation library and components for PDF creation from Create fillable and editable PDF documents from Excel in
change font in pdf form field; pdf form creator
MigratingPythontocompiledcode
G
Pythonisaveryconvenientlanguageforimplementingscientiﬁccomputa-
However,theexecutionspeedofthecodeissigniﬁcantlylowerthanwhat
canbeobtainedbyprogramminginlanguagessuchasFortran,C,or
C++.Theselanguagescompiletheprogramtomachinelanguage,which
enablesthecomputingresourcestobeutilizedwithveryhigheﬃciency.
Frequently,andthisincludesalmostallexamplesinthepresentbook,
Pythonisfastenough.Butinthecaseswherespeedreallymatters,can
weincreasetheeﬃciencywithoutrewritingthewholeprograminFortran,
studyintheforthcomingtext.
Fortunately,PythonwasinitiallydesignedforbeingintegratedwithC.
Thisfeaturehasspawnedthedevelopmentofseveraltechniquesandtools
forcallingcompiledlanguagesfromPython,allowingustorelatively
easilyreusefastandwell-testedscientiﬁclibrariesinFortran,C,orC++
fromPython,or migrateslowPythoncodetocompiledlanguages.It
oftenturnsoutthatonlysmallerpartsofthecode,usually
for
loops
doing heavynumericalcomputations,suﬀer from lowspeedand can
beneﬁtfrombeingimplementedinFortran,C,orC++.
canbeviewedasanextensionofthePythonlanguagewherevariablescan
bedeclaredwithatypeandotherinformationsuchthatCythonisable
toautomaticallygeneratespecial-purpose,fastCcodefromthePython
code.WewillshowhowtoutilizeCythonandwhatthecomputational
gainmightbe.
Thepresentcasestudystartswithstatingacomputationalproblem
involvingstatisticalsimulations,whichareknowntocauselongexecution
times,especiallyifaccurateresultsaredesired.
813
814
G MigratingPythontocompiledcode
G.1PurePythoncodeforMonteCarlosimulation
Ashort,intuitivealgorithminPythonisﬁrstdeveloped.Thenthiscode
isvectorizedusingfunctionalityoftheNumericalPythonpackage.Later
sectionsmigratethealgorithmtoCythoncodeandalsoplainCcodefor
comparison.Attheendthevarioustechniquesarerankedaccordingto
theircomputationaleﬃciency.
G.1.1Thecomputationalproblem
leasttimes?Forexample,if m=5and=3,thisisthesameas
eyes.
TheprobabilitycanbeestimatedbyMonteCarlosimulation.Chap-
ter8.3providesabackgroundforthistechnique:Wesimulatetheprocess
alargenumberoftimes,N,andcounthowmanytimes,M,theexperi-
mentturnedoutsuccessfully,i.e.,whenwegotatleastnoutofmdice
withsixeyesinathrow.
computationalmethod,normallyrequiringverysophisticated,fastcom-
puterimplementationsincompiledlanguages.Aninterestingquestionis
howusefulhigh-levellanguageslikePythonandassociatedtoolsarefor
MonteCarlosimulation.Thiswillnowbeexplored.
G.1.2AscalarPythonimplementation
Letusintroducethemoredescriptivevariablesndiceformandnsix
forn.TheMonteCarlomethodissimplyaloop,repeatedNtimes,where
thebodyoftheloopmaydirectlyexpresstheproblemathand.Here,
wedrawndicerandomintegersrin[1,6]insidetheloopandcountof
many(six)thatequal6.If six >= nsix,theexperimentisasuccess
andweincreasethecounterMbyone.
APythonfunctionimplementingthisapproachmaylookasfollows:
import random
def dice6_py(N, , ndice, nsix):
M = = 0
# no of f successful events
for i i in n range(N):
# repeat N N experiments
six = = 0
# how many y dice e with six x eyes?
for j j in range(ndice):
r = = random.randint(1, 6) # # roll l die no. . j
if r == = 6:
six += = 1
if six >= nsix:
# successful event?
M += 1
p = = float(M)/N
return p
G.1 PurePythoncodeforMonteCarlosimulation
815
Thefloat(M)transformationisimportantsinceM/Nwillimplyinteger
divisionwhenMandNbothareintegersinPythonv2.xandmanyother
languages.
WewillrefertothisimplementationistheplainPythonimplementa-
tion.Timingthefunctioncanbedoneby:
import time
t0 = = time.clock()
p = = dice6_py(N, , ndice, , nsix)
t1 = = time.clock()
print ’CPU U time e for loops s in Python:’, , t1-t0
The table to appear later showsthe performanceofthisplain,pure
Pythoncoderelativetootherapproaches.Thereisafactorof30+tobe
Thefunctionabovecanbeveriﬁedbystudyingthe(somewhatsim-
pliﬁed)casem=nwheretheprobabilitybecomes6
−n
.Theprobability
quicklybecomessmallwithincreasingn.Forsuchsmallprobabilities
thenumberofsuccessfuleventsissmall,and M/N willnotbea
good approximationtothe probabilityunlessisreasonablylarge,
whichrequiresaverylargeN.Forexample,withn=4andN=10
5
theaverageprobabilityin25fullMonteCarloexperimentsis0.00078
costsafactorof10incomputingresourcessincetheCPUtimescales
linearlywithN.
G.1.3AvectorizedPythonimplementation
Avectorizedversionofthepreviousprogramconsistsofreplacingthe
explicitloopsinPythonbyeﬃcientoperationsonvectorsorarrays,using
functionalityin the Numerical Python (numpy) package. . Each array
operationtakesplaceinCorFortranandishencemuchmoreeﬃcient
thanthecorrespondingloopversioninPython.
First,wemustgeneratealltherandomnumberstobeusedinone
operation,whichrunsfastsinceallnumbersarethencalculatedineﬃcient
Ccode.Thisisaccomplishedusingthenumpy.randommodule.Second,
theanalysisofthelargecollectionofrandomnumbersmustbe done
byappropriatevector/arrayoperationssuchthatnoloopinginPython
isneeded.Thesolutionalgorithmmustthereforebeexpressedthrough
aseriesof functioncallstothe numpy library.Vectorization requires
knowledgeofthelibrary’sfunctionalityandhowtoassembletherelevant
buildingblockstoanalgorithmwithoutoperationsonindividualarray
elements.
Generation of ndice random m number r of eyesfor experimentsis
performedby