c# split pdf into images : Add password to pdf file without acrobat Library application class asp.net azure winforms ajax ch050-part44

JohnnyWei-BingLin
AHands-OnIntroductiontoUsing
PythonintheAtmosphericand
OceanicSciences
http://www.johnny-lin.com/pyintro
2012
Add password to pdf file without acrobat - C# PDF Password Library: add, remove, edit PDF file password in C#.net, ASP.NET, MVC, WinForms, WPF
Help to Improve the Security of Your PDF Document by Setting Password
create password protected pdf online; break a pdf password
Add password to pdf file without acrobat - VB.NET PDF Password Library: add, remove, edit PDF file password in vb.net, ASP.NET, MVC, WinForms, WPF
Help to Improve the Security of Your PDF Document by Setting Password
add password to pdf file; adding password to pdf
c
2012JohnnyWei-BingLin.
Somerightsreserved.Printedversion:ISBN978-1-300-07616-2.PDFver-
sions:NoISBNsareassigned.
ThisworkislicensedundertheCreativeCommonsAttribution-Noncom-
mercial-ShareAlike3.0UnitedStatesLicense(CCBY-NC-SA).Toviewa
copyofthislicense,visithttp://creativecommons.org/licenses/by-nc-sa/3.0/
usorsendalettertoCreativeCommons,171SecondStreet,Suite300,San
Francisco,California,94105,USA.
Whowouldnotwanttopaymoneyforthisbook?:ifyoudonotneed
ablack-and-whitepapercopyofthebook,acolorPDFcopywithfunctional
hyperlinks,havelimitedfunds,orareinterestedinsuchasmallportionof
thebookthatitmakesnosensetobuythewholething.Thebook’swebsite
(http://www.johnny-lin.com/pyintro)hasavailable,forfree,PDFsofevery
chapterasseparatefiles.
Whowouldwanttopaymoneyforthisbook?:ifyouwantablack-
and-whitepapercopyofthe book, acolorPDFcopywithfunctionalhy-
perlinks,oryouwanttohelpsupporttheauthorfinancially. Youcanbuy
a black-and-white papercopy ofthe bookathttp://www.johnny-lin.com/
pyintro/buypaper.shtmlandahyperlink-enabledcolorPDFcopyofthebook
athttp://www.johnny-lin.com/pyintro/buypdf.shtml.
Aspecialappealtoinstructors:Instructionatfor-profitinstitutions,as
acommercialuse,isnotcoveredunderthetermsoftheCCBY-NC-SA,and
soinstructorsatthoseinstitutionsshouldnotmakecopiesofthebookfor
studentsbeyondcopyingpermittedunderFairUse. Instructionatnot-for-
profitinstitutionsisnotacommercialuse,soinstructorsmaylegallymake
copiesofthisbookforthestudentsintheirclasses,underthetermsoftheCC
BY-NC-SA,solongasnoprofitismadethroughthecopyandsale(orFair
Useisnotexceeded).However,mostinstructionatnot-for-profitinstitutions
stillinvolvespaymentoftuition: lots s ofpeoplearegettingpaidfortheir
contributions.Pleaseconsideralsopayingtheauthorofthisbooksomething
forhiscontribution.
Regardlessofwhetherornotyoupaidmoneyforyourcopyofthebook,
youarefreetouseanyandallpartsofthebookunderthetermsoftheCC
BY-NC-SA.
C# PDF Converter Library SDK to convert PDF to other file formats
NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. to conduct high fidelity PDF file conversion in
pdf open password; change password on pdf file
C# powerpoint - PowerPoint Conversion & Rendering in C#.NET
documents in .NET class applications independently, without using other easily achieve the following PowerPoint file conversions. PowerPoint to PDF Conversion.
add copy protection pdf; annotate protected pdf
Chapter5
FileInputandOutput
Theatmospheric and oceanic sciences (AOS)are“data” intensivefields,
whetherdatareferstoobservationsormodeloutput. Mostoftheanalysis
wedoinvolvedatasets,andsofacilitiesforfileinput/output(i/o)arecritical.
Fortunately,Pythonhasveryrobustfacilitiesforfilei/o.Inthischapter,we
willsort-oftouchonthosefacilities.
WhydoIsay“sort-of?”:becauseIaminsomewhatofaquandarywhen
itcomestotalkingaboutfileinput/output.Ontheonehand,Iwanttoshow
youhowtouseroutinesthatyouwillwanttouseforyourownresearchand
analysis.Ontheotherhand,becausethisbookisanintroductiontoPython,
Iwanttoshowyouthefundamentalsofhowtodothingsinthelanguage.In
Python,themostrobustfilei/opackages,whilenotdifficulttouse,arestill
ratherconceptuallyadvanced.
1
Theintroductionofthesepackagesmight
distractfromthelargergoalofshowingyouthefundamentals. Asacom-
promise,thischapterwilldescribewaysofhandlingfilei/othat,whilenot
themostefficientoroptimized,nonethelesswillworkformany(ifnotmost)
AOSusesandwhichillustratebasicmethodsinusingPython(thisispartic-
ularlytruewhenIdiscusshandlingstrings).InthesummaryinSection5.4,
Iwillbrieflydescribeadditionalpackagesforfilei/othatyoumaywantto
lookinto.
Inthis chapterwewilllookatinput/outputtoandfromtextfilesand
netCDFfiles.Butbeforewedoso,Iwanttomakesomecommentsaboutfile
objects,whicharefoundationaltohowPythoninterfaceswithafile,whether
text,netCDF,oranotherformat.
1
Anexampleis thePyTables package, , areallygreatpackageforlarge e datasets that
utilizessomeveryadvancedoptimizationmethods.
73
C# Word - Word Conversion in C#.NET
standard Word documents in .NET class applications independently, without using other the function of converting Word to ODT file in C# PDF to Word Conversion.
adding a password to a pdf; create pdf password
C# Windows Viewer - Image and Document Conversion & Rendering in
image and document in .NET class applications independently, without using other toolkit in C#, you can easily perform file conversion from Convert to PDF.
break pdf password online; add password to pdf file without acrobat
5.1. FILEOBJECTS
5.1 Fileobjects
Afileobjectisa“variable”thatrepresentsthefiletoPython.Thisisasubtle
Fileobjects
representthe
filetothe
interpreter.
butrealdifferencewithprocedurallanguages. Forinstance,inFortran,you
usefunctionstooperateonafileandunitnumberstospecifythefileyou’re
operatingon(e.g.,read(3,*),where3istheunitnumberthatrepresents
thefiletoFortran). InPython,youusemethodsattachedtofileobjectsto
operateonthefile.(MoreonobjectsisinCh.7.)
FileobjectsarecreatedlikeanyotherobjectinPython,thatis,byas-
signment. Fortextfiles,youinstantiateafileobjectwiththebuilt-inopen
Creatingfile
objectsusing
theopen
statement.
statement:
fileobj = open(’foo.txt’, , ’r’)
Thefirstargumentintheopenstatementgivesthefilename. Thesecond
argumentsetsthemodeforthefile:’r’forreading-onlyfromthefile,’w’
forwritingafile,and’a’forappendingtothefile.
Pythonhas anumberofmodulesavailableforhandlingnetCDFfiles;
forthenetCDFpackagewe’llbeusinginthischapter,thereisadifferent
Creating
netCDFfile
objects.
commandtocreatefileobjectsthatcorrespondtothenetCDFfile,butthe
syntaxissimilar:
fileobj = S.NetCDFFile(’air.mon.mean.nc’,
mode=’r’)
As withopen, thestring’r’meansread, etc. . InSection5.3, , whenwe
discussnetCDFinput/outputinmoredetail,I’llexplaintherestofthesyntax
oftheabovefileobjectcreationstatement.Fornow,Ijustwanttopointout
thatthefileobjectfileobjiscreatedbyassignmenttothereturnofthe
S.NetCDFFilecommand.
OnemethodcommontoboththetextandnetCDFfileobjectswe’llbe
Theclose
methodoffile
objects.
lookingatistheclosemethod,which,asyoumightexpect,closesthefile
object.Thus,tocloseafileobjectfileobj,execute:
fileobj.close()
5.2 Textinput/output
Onceyou’vecreatedthetextfileobject, youcanusevariousmethodsat-
tachedtothefileobjecttointeractwiththefile.
74
C# Excel - Excel Conversion & Rendering in C#.NET
Excel documents in .NET class applications independently, without using other may easily achieve the following Excel file conversions. Excel to PDF Conversion.
convert password protected pdf to normal pdf; crystal report to pdf with password
JPEG to PDF Converter | Convert JPEG to PDF, Convert PDF to JPEG
image files to PDF directly without the software high speed; Get a compressed PDF file after conversion; Support Password protection to protect users' privacy;
password on pdf file; change password on pdf document
5.2. TEXTINPUT/OUTPUT
5.2.1 Textinput/output:Readingafile
Toreadonelinefromthefile,usethereadlinemethod:
aline = fileobj.readline()
Becausethefileobjectisconnectedtoatextfile, alinewillbeastring.
Notethatalinecontainsthenewlinecharacter,becauseeachlineinafileis
terminatedbythenewlinecharacter.
Toreadtherestofafilethatyoualreadystartedreading,ortoreadan
entirefileyouhaven’tstartedreading,andthenputthereadcontentsintoa
The
readlines
method.
list,usethereadlinesmethod:
contents = fileobj.readlines()
Here,contentsisalistofstrings,andeachelementincontentsisaline
inthefileobjfile.Eachelementalsocontainsthenewlinecharacter,from
theendofeachlineinthefile.
Notethatthevariablenamesalineandcontentsarenotspecial;use
whatevervariablenameyouwouldliketoholdthestringsyouarereadingin
fromthetextfile.
5.2.2 Textinput/output:Writingafile
Towriteastringtothefilethatisdefinedbythefileobjectfileobj,usethe
writemethodattachedtothefileobject:
fileobj.write(astr)
Here,astristhestringyouwanttowritetothefile. Notethatanewline
characterisnotautomaticallywrittentothefileafterthestringiswritten.If
youwantanewlinecharactertobeadded,youhavetoappendittothestring
priortowriting(e.g.,astr+’\n’).
Towritealistofstringstothefile,usethewritelinesmethod:
The
writelines
method;
writeand
writelines
donotwrite
newlineby
default.
fileobj.writelines(contents)
Here,contentsisalistofstrings,and,again,anewlinecharacterisnot
automaticallywrittenafterthestring(soyouhavetoexplicitlyadditifyou
wantitwrittentothefile).
75
TIFF to PDF Converter | Convert TIFF to PDF, Convert PDF to TIFF
to TIFF Converter can protect PDF files with password. files to multi-page TIFF files without losing any Able to preserve text and PDF file's vector drawings;
password pdf; creating password protected pdf
GIF to PDF Converter | Convert GIF to PDF, Convert PDF to GIF
as easy-to-use and reliable software to convert GIF file to PDF and convert PDF files to It can be functioned as an integrated component without the use of
pdf document password; pdf user password
5.2. TEXTINPUT/OUTPUT
5.2.3 Textinput/output:Processingfilecontents
Let’ssayyou’veread-inthecontentsofafilefromthefileandnowhave
thefilecontentsasalistofstrings. Howdoyoudothingswiththem? ? In
particular,howdoyouturnthemintonumbers(orarraysofnumbers)that
youcananalyze?Pythonhasahostofstringmanipulationmethods,built-in
tostringvariables(a.k.a.,objects),whichareidealfordealingwithcontents
fromtextfiles.Wewillmentiononlyafewofthesemethods.
Thesplitmethodofastringobjecttakesastringandbreaksitintoa
Thestring
method
split.
listusingaseparator.Forinstance:
a = = ’3.4 4 2.1 -2.6’
print a.split(’ ’)
[’3.4’, ’2.1’, , ’-2.6’]
willtakethestringa,lookforablankspace(whichispassedinastheargu-
menttosplit,andusethatblankspaceasthedelimiterorseparatorwith
whichonecansplitupthestring.
Thejoinmethodtakesaseparatorstringandputsitbetweenitemsofa
Thestring
methodjoin.
list(oranarray)ofstrings.Forinstance:
a = = [’hello’, , ’there’, , ’everyone’]
’\t’.join(a)
’hello\tthere\teveryone’
willtakethelistofstringsaandconcatenatetheseelementstogether,using
thetabstring(’\t’)toseparatetwoelementsfromeachother.(Forashort
listofsomespecialstrings,seep.19.)
Finally,oncewehavethestringswedesire,wecanconvertthemtonu-
Converting
stringsto
numerical
types.
mericaltypesinordertomakecalculations. Herearetwowaysofdoing
so:
• Ifyouloopthroughalistofstrings,youcanusethefloatandint
functionsonthestringtogetanumber.Forinstance:
import numpy as s N
anum = = N.zeros(len(a), ’d’)
for i in xrange(len(a)):
anum[i] = float(a[i])
76
5.2. TEXTINPUT/OUTPUT
takesa listofstringsaandturnsitintoa NumPyarrayofdouble-
precisionfloatingpointnumbersanum.
2
• IfyoumakethelistofstringsaNumPyarrayofstrings,youcanuse
theastypemethodfortypeconversiontofloatingpointorinteger.For
instance:
anum = N.array(a).astype(’d’)
takesalistofstringsa,convertsitfromalisttoanarrayofstrings
usingthearrayfunction,andturnsthatarrayofstringsintoanar-
rayofdouble-precisionfloatingpointnumbersanumusingtheastype
methodofthearrayofstrings.
Agotcha:Differentoperatingsystemsmaysettheend-of-linecharacter
Different
OSeshave
different
end-of-line
characters.
tosomethingbesides’\n’. Makesureyouknowwhatyourtextfileuses.
(Forinstance,MS-DOSuses’\r\n’,whichisacarriagereturnfollowed
byaline feed.) ) Bytheway, , Python hasaplatformindependentway of
referringtotheend-of-linecharacter: theattributelinesepinthemodule
os.Ifyouwriteyourprogramusingthatvariable,insteadofhard-codingin
’\n’,yourprogramwillwriteoutthespecificend-of-linecharacterforthe
systemyou’rerunningon.
Example41(Writingandreadingasinglecolumnfile):
TakethefollowinglistoftemperaturesT:
T = = [273.4, 265.5, , 277.7, , 285.5]
writeittoafileone-col
temp.txt,thenreadthefilebackin.
Solutionanddiscussion:Thiscodewilldothetrick(noteIusecomment
linestohelpguidethereader):
2Notethatyoucanspecifythearraydtypewithoutactuallywritingthedtypekey-
word;NumPyarrayconstructorslikezeroswillunderstandatypecodegivenasthesecond
positionalinputparameter.
77
5.2. TEXTINPUT/OUTPUT
import numpy as N
outputstr = [’\n’]*len(T)
#- Convert to string
for i i in xrange(len(T)):
# and d add newlines
outputstr[i] = = \
str(T[i]) + + outputstr[i]
fileout = open(’one-col_temp.txt’, ’w’) ) #- - Write e out
fileout.writelines(outputstr)
# to o the
fileout.close()
# file
filein = = open(’one-col_temp.txt’, , ’r’)
#- Read in
inputstr = = filein.readlines()
# from m the
filein.close()
# file
Tnew = N.zeros(len(inputstr), ’f’)
#- Convert
for i i in xrange(len(inputstr)):
# string g to
Tnew[i] = = float(inputstr[i])
# numbers
Noteyoudon’thavetostripoffthenewlinecharacterbeforeconverting
thenumbertofloatingpointusingfloat.
Acaveataboutreadingtextfiles:Inthebeginningofthischapter,Isaid
Iwouldtalkaboutfilereadinginawaythatteachesthefundamentals of
Python,notinawaythatgivesyouthemostefficientsolutiontofilei/ofor
AOSapplications.ThisisparticularlytrueforwhatI’vejusttoldyouabout
readingtextfiles. Stringmethods,whilepowerful,areprobablytoolow-
leveltobotherwitheverytimeyouwanttoreadatextfile;you’dexpect
someonesomewherehasalreadywrittenafunctionthatautomaticallypro-
cessestextformatstypicallyfoundinAOSdatafiles.Indeed,thisisthecase:
seetheasciireadfunctioninPyNGL,
3
thereadAsciifunctionintheCli-
mateDataAnalysisTools(CDAT),
4
andtheSciPyCookbooki/opage
5
for
examples.
3http://www.pyngl.ucar.edu/Functions/Ngl.asciiread.shtml(accessedAugust16,2012).
4
http://www2-pcmdi.llnl.gov/cdat/tips
and
tricks/file
IO/reading
ASCII.html(accessed
August16,2012).
5
http://www.scipy.org/Cookbook/InputOutput(accessedAugust16,2012).
78
5.3. NETCDFINPUT/OUTPUT
5.2.4 Exercisetoreadamulti-columntextfile
Exercise16(Readinginamulti-columntextfile):
Youwillfindthefiletwo-col
rad
sine.txtinthedatasetssub-directoryof
course
files.Writecodetoreadthetwocolumnsofdatainthatfileintotwo
arrays,oneforangleinradians(column1)andtheotherforthesineofthe
angle(column2). (Thecourse
filesdirectoryoffilesisavailableonlineat
thebook’swebsite.Seep.viiifordetailsonobtainingthefiles.Alternately,
feelfreetouseatextdatafileofyourown.)
Thetwocolumnsoftwo-col
rad
sine.txtareseparatedbytabs.Thefile’s
newlinecharacterisjust’\n’(thoughthisisn’tsomethingyou’llneedto
knowtodothisexercise).Thefilehasnoheaders.
Solutionanddiscussion:Here’smysolution:
import numpy y as N
fileobj = open(’two-col_rad_sine.txt’, ’r’)
data_str = fileobj.readlines()
fileobj.close()
radians = N.zeros(len(data_str), ’f’)
sines = N.zeros(len(data_str), , ’f’)
for i i in xrange(len(data_str)):
split_istr = = data_str[i].split(’\t’)
radians[i] = = float(split_istr[0])
sines[i] = = float(split_istr[1])
Thearrayradiansholdstheangles(inradians)andthearraysinesholds
thesineofthoseangles. Notethattheabovecodedoesnotneedtoknow
aheadoftimehowmanylinesareinthefile;allthelineswillbereadinby
thereadlinesmethodcall.
5.3 NetCDFinput/output
NetCDFisaplatform-independentbinaryfileformatthatfacilitatesthestor-
ageandsharingofdataalongwithitsmetadata.Versionsofthetoolsneeded
toreadandwritetheformatareavailableonpracticallyeveryoperatingsys-
temandineverymajorlanguageusedintheatmosphericandoceanicsci-
ences.
79
5.3. NETCDFINPUT/OUTPUT
BeforediscussinghowtodonetCDFi/oinPython,let’sbrieflyreviewthe
structureofnetCDF.TherearefourgeneraltypesofparametersinanetCDF
file:globalattributes,variables,variableattributes,anddimensions.Global
attributesareusuallystringsthatdescribethefileasawhole,e.g.,atitle,who
Thestructure
ofnetCDF
files.
createdit,whatstandardsitfollows,etc.
6
Variablesaretheentitiesthathold
data.Theseincludeboththedata-proper(e.g.,temperature,meridionalwind,
etc.),thedomainthedataisdefinedon(delineatedbythedimensions),and
metadataaboutthedata(e.g.,units). Variableattributesstorethemetadata
associatedwithavariable.Dimensionsdefineadomainforthedata-proper,
buttheyalsohavevaluesoftheirown(e.g.,latitudevalues,longitudevalues,
etc.),andthusyouusuallycreatevariablesforeachdimensionthatarethe
samenameasthedimension.
7
AsanexampleofasetofvariablesanddimensionsforanetCDFfile,
considerthecasewhereyouhaveatimeseriesofsurfacetemperaturefora
latitude-longitudegrid. Forsuchadataset,youwoulddefine“lat”,“lon”,
and“time”dimensionsandcorrespondingvariablesforeachofthosedimen-
sions. Thevariable“lat”wouldbe1-Dwiththenumberofelementsgiven
forthe“lat”dimensionandlikewiseforthevariables“lon”and“time”,re-
spectively.Finally,youwoulddefinethevariable“Ts”as3-D,dimensioned
“lat”,“lon”,and“time”.
SeveralPythonpackagescanreadnetCDFfiles,including:theUltrascale
Visualization-ClimateDataAnalysisTools(UV-CDAT),CDAT,PyNIO,py-
sclint,PyTables,andScientificPython.We’llbediscussingScientificPython
inthissection,notbecauseit’sthebestpackageofthisbunchbutbecause
itwasoneoftheearliestPythonnetCDFinterfaces,andmanysubsequent
packageshaveemulateditsuser-interface.
5.3.1 NetCDFinput/output:Readingafile
ScientificPythonisanotheroneofthosepackageswhose“human-readable”
Importingthe
Scien-
tificPython
netCDF
submodule.
nameisdifferentfromits“imported”name. Inaddition,thenetCDFutil-
itiesareinasubpackageofScientificPython. Thus, , theimportnamefor
thenetCDFutilitiesislongandyouwillalmostalwayswanttoassignthe
importedpackagetoanalias:
import Scientific.IO.NetCDF F as s S
6
Itisunfortunatethat“globalattributes”and“variableattributes”arecalledattributes,
sincethetermattributeshasaveryspecificmeaninginobject-orientedlanguages. WhenI
talkaboutobjectattributesincloseproximitytonetCDFattributes,inthissection,I’lltryto
maketheobjectattributesoccurrenceglossary-linked.
7
FormoreonnetCDF,seehttp://www.unidata.ucar.edu/software/netcdf/docs(accessed
August16,2012).
80
Documents you may be interested
Documents you may be interested