Vous êtes sur la page 1sur 17

psliwa5daysago[#47]supportformaxwidthandmaxheightattributes

4contributors
M
Signup Signin
103 17 Star y Fork
psliwa/PHPPdf
PUBLIC
g
O

Q
+
@
y
y master branch:
PHPPdf/README.markdown _
_file 1092lines(840sloc) 40.013kb
Sampledocumentsareinthe"examples"directory."index.php"fileisthewebinterfacetobrowseexamples,"cli.php"isaconsole
interface.Viathewebinterface,thedocumentsareavailableinpdfandjpegformat(thejpegformatrequiresImagick).
1. Introduction
2. Installation
3. Symfony2bundle
4. FAQ
5. Documentparsingandcreatingpdffile
6. Basicdocumentstructure
7. Inheritance
8. Stylesheetstructure
9. Paletteofcolors
10. Standardtags
11. Attributes
12. Complexattributes
13. Units
14. Barcodes
15. Charts
16. Hyperlinks
17. Bookmarks
18. Stickynotes
19. Repetitiveheadersandfooters
20. Watermarks
21. Pagenumbering
22. Usingthepdfdocumentasatemplate
23. Separatepageoncolumns
24. Breakingpagesandcolumns
25. Metadata
Edit Raw Blame History Delete
Information
Examples
Documentation
Tableofcontents
Explore Features Enterprise Blog Searchortypeacommand Thisrepository @
26. Configuration
27. Markdownsupport
28. Imagegenerationengine
29. Knownlimitations
30. TODOplans
31. Technicalrequirements
PHPPdfislibrarythattransformsanXMLdocumenttoaPDFdocumentorgraphicsfiles.TheXMLsourcedocumentissimilarto
HTML,buttherearelotsofdifferencesinnamesandpropertiesofattributes,propertiesoftags,andtherearealotofnotstandard
tags,notalltagsfromhtmlaresupported,stylesheetisdescribedinanxmldocument,notincss.
AssumptionofthislibraryisnotHTML>PDF/JPEG/PNG,butXML>PDF/JPEG/PNGtransformation.Sometagsand
attributesarethesameasinHTMLinorderdecreasethelearningcurveofthislibrary.
PHPPdfisavailableatpackagist.org,soyoucanusecomposertodownloadthislibraryandalldependencies.
Pleaseconfigurethe"minimumstability"inyourcomposer.jsonfile,andsetittodev.
"minimumstability":"dev"
Ifyoudonotwanttousecomposer,followtheinstructionsbelowtomanuallyinstallthislibrarywithallthedependencies.
Thislibraryusesthefollowingexternaldependencies:
phpmarkdown
ZendPdf
Zend_Memory(ZendFrameworkin2.0.xversion)
Zend_Cache(ZendFrameworkin2.0.xversion)
Zend_Stdlib(ZendFrameworkin2.0.xversion)
Zend_EventManager(ZendFrameworkin2.0.xversion)
Zend_ServiceManager(ZendFrameworkin2.0.xversion)
Zend_Barcode(ZendFrameworkin2.0.xversion)
Imagine
Inordertousethelibrary,youmustdownloadallthesedependencies.
Executethefollowingcommandfromthemaindirectoryofthelibrary(makesureyouhaveGitinstalled):
phpvendors.php
Alternatively,youcandownloadthedependenciesmanuallyandcopythemintothe"lib/vendor"directory.
Bydefaultthevendors.phpfilewilldownloadtheentireZF2repository,butrememberthatonlyZendPdf,Zend_Memory,
Zend_Cache,Zend_Stdlib,Zend_ServiceManagerandZend_EventManagerarerequired.Toenablebarcodessupport,
Zend_Barcodemustalsobeinstalled.Theotherpackagesandfilescanberemoved.
ThereisaSymfony2bundlewhichintegratesthislibrarywiththeSymfony2framework.
Introduction
Installation
Symfony2bundle
FAQ
Diacriticalmarksarenotdisplayed,whatshouldIdo?
Youshouldsetafontthatsupportstheencodingthatyouareusing,andsetthisencodingas"encoding"attributefor"page"and/or
"dynamicpage"tags.PHPPdfprovidessomefreefontsthatsupportutf8encoding,forexample,DejaVuSans.The"Font"example
showshowtochangethefonttypebyusingastylesheet.
Youcanalsoaddcustomfonts,inorderthatyoushouldpreparexmlconfigfileandconfigureFacadeobjectasshownbelow:
<!xmlconfigfilecode>
<fonts>
<fontname="DejaVuSans">
<normalsrc="%resources%/fonts/DejaVuSans/normal.ttf"/><!"%resources%"willbereplacedbypathtoPHPPdf/Resourcesdirectory>
<boldsrc="%resources%/fonts/DejaVuSans/bold.ttf"/>
<italicsrc="%resources%/fonts/DejaVuSans/oblique.ttf"/>
<bolditalicsrc="%resources%/fonts/DejaVuSans/bold+oblique.ttf"/>
</font>
</fonts>
//phpcode
$loader=newPHPPdf\Core\Configuration\LoaderImpl()
$loader>setFontFile(/*pathtofontsconfigurationfile*/)
$builder=PHPPdf\Core\FacadeBuilder::create($loader)
$facade=$builder>build()
//xmldocumentcode
<pdf>
<dynamicpageencoding="UTF8"fonttype="DejaVuSans">
</dynamicpage>
</pdf>
YoucanfindmoredatailsintheConfigurationsection.
Generatingofasimplepdffilewithpngimagestakesalotoftimeandmemory,whatshouldIdo?
PHPPdfusestheZend_Pdflibrarythatpoorlysupportspngfileswithoutcompression.Youshouldcompressthepngfiles.
HowcanIchangethepagesize/orientation?
Tosetthepagedimensionsyouusethe"pagesize"attributeofthepageordynamicpagetags.
Thevaluesyntaxofthisattributeis"width:height".
Therearehoweverstandardpredefinedvalues:a4,a4landscape,letterandletterlandscape.
Example:
<pagepagesize="100:50">text</page>
<pagepagesize="a4">text</page>
<pagepagesize="letterlandscape">text</page>
Thesimplestwayofusingthelibraryis:
//registerthePHPPdfandvendor(Zend_Pdfandotherdependencies)autoloaders
require_once'PHPPdf/Autoloader.php'
PHPPdf\Autoloader::register()
PHPPdf\Autoloader::register('/path/to/library/lib/vendor/Zend/library')
//ifyouwanttogenerategraphicfiles
PHPPdf\Autoloader::register('sciezka/do/biblioteki/lib/vendor/Imagine/lib')
$facade=newPHPPdf\Core\Facade(newPHPPdf\Core\Configuration\Loader())
Documentparsingandcreatingapdffile
//$documentXmland$stylesheetXmlarestringscontainsXMLdocuments,$stylesheetXmlisoptional
$content=$facade>render($documentXml,$stylesheetXml)
header('ContentType:application/pdf')
echo$content
ThelibrarybasespagesonanXMLformatsimilartoHTML,butthisformatisn'tHTMLsometagsarediffrent,interpretationof
someattributesisnottheassameasintheHTMLandCSSstandards,addingattributesisalsodifferent.
Asimpledocumenthasfollowingstructure:
<pdf>
<dynamicpage>
<h1>Header</h1>
<p>paragraph</p>
<divcolor="red">Layer</div>
<table>
<tr>
<td>Column</td>
<td>Column</td>
</tr>
</table>
</dynamicpage>
</pdf>
AddingaDOCTYPEdeclarationisstronglyrecommendedinordertoreplacehtmlentitiesonvalues:
<!DOCTYPEpdfSYSTEM"%resources%/dtd/doctype.dtd">
Therootnameofadocumentmustbe"pdf".The"dynamicpage"tagisanautobreakablepage.The"page"tagisanalternative,
andrepresentsonlyasingle,nobreakablepage.
ThewayofattributesettingisdifferentthaninHTML.
Inordertosetabackgroundandborderyouneedtousecomplexattributes,wherefirstpartofattributenameisacomplexattribute
type,andthesecondpartisthepropertyofthisattribute.
Complexattributepartsareseparatedbyadot(".").
Ananotherwayofsettingcomplexattributesisbyusingthe"complexattribute"tag.
Example:
<pdf>
<dynamicpage>
<divcolor="red"border.color="black"background.color="pink">
Thistextisredonpinkbackgrounintoblackborder
</div>
</dynamicpage>
</pdf>
Alternativesyntax("stylesheet"tag):
<pdf>
<dynamicpage>
<div>
<stylesheet>
<attributecolor="red"/>
<complexattributename="border"color="black"/>
<complexattributename="background"color="pink"/>
</stylesheet>
Thistextisredonpinkbackgrounintoblackborder
</div>
Basicdocumentstructure
</dynamicpage>
</pdf>
AttributescanbysetasXMLattributes,directlyafteratagnameorbyusingthementioned"stylesheet"tag.TheHTML"style"
attributedoesnotexistthePHPPdfXMLdialect.
Thelibraryisverystrictinrespectingthecorectnessoftagsandattributes.Ifanunexistedtagorattributeisdetected,thedocument
parserwillstopandthrowanexception.
The"id"attributehasandifferentusagethaninHTML.Theidattributeisusedtoidentifytagswhenusinginheritance.
The"name"attributecanalsobeusedasanaliasto"id".
Anidmustbyuniquethroughoutthedocument,otherwiseaparsingerroristhrown.
Example:
<pdf>
<dynamicpage>
<divid="layer1"color="red"fonttype="judson"fontsize="16px">
<stylesheet>
<complexattributename="border"color="green"/>
</stylesheet>
Layer1
</div>
<divextends="layer1">
Layer2inheritsstyle(type,simpleandcomplexattributes)fromlayer1)
</div>
</dynamicpage>
</pdf>
TheSecondlayerinheritsallattributes(simpleandcomplex),andalsothosefromexternalstylesheets.
Prioritesinattributessetting:
1. Stylesheettagdirectlyinanelementtag
2. Attributesdirectlyafteratagname(XMLattributes)
3. Attributesfromexternalstylesheets
4. Inheritedattributesfromaparenttag
Example:
<pdf>
<page>
<divid="1"color="#cccccc"height="100px"textalign="right">
</div>
<divextends="1"color="#aaaaaa"height="150px">
<stylesheet>
<attributename="height"value="200px"/>
</stylesheet>
</div>
</page>
</pdf>
Thesecond"div"willnowhavethefollowingattributes:
textalign:right
color:#aaaaaa
height:200px
Inheritance
Stylesheetstructure
Stylesheetsaredefinedinexternalfiles,stylesheetshortandlongdeclarationsofattributesaresupported.
Syntaxofthestylesheet:
Shortstyle:
<stylesheet>
<!styleattributesareembededasxmlattributes,classattributehasthesamemeaningasinHTML/CSS>
<divclass="class"fontsize="12px"color="gray"background.color="yellow">
<!nestedelement,equivalentCSSselectorsyntax:"div.classp">
<pmargin="10px15px">
</p>
</div>
<!equivalentCSSselectorsyntax:".anotherclass","any"tagiswildcard(meananytag)>
<anyclass="anotherclass"textalign="right">
</any>
<h2class="header">
<spanfontsize="9px">
</span>
<divfontstyle="bold">
</div>
</h2>
</stylesheet>
Longstyle:
<stylesheet>
<divclass="class">
<!simpleandcomplexattributesarenestedin"div.class"selectorpath>
<attributename="fontsize"value="12px"/>
<attributename="color"value="grey"/>
<!equivalentofbackground.colorattribute>
<complexattributename="background"color="yellow"/>
<!anothernestedelement,equivalentCSSselectorsyntax:"div.classp">
<p>
<attributename="margin"value="10px15px"/>
</p>
</div>
<!equivalentCSSselectorsyntax:".anotherclass","any"tagiswildcard(meananytag)>
<anyclass="anotherclass">
<attributename="textalign"value="right"/>
</any>
<h2class="header">
<span>
<attributename="fontsize"value="9px"/>
</span>
<div>
<attributename="fontstyle"value="bold"/>
</div>
</h2>
</stylesheet>
PHPPdfsupportscolorpalettes,mappingoflogicalnamestorealcolors.
Colorpalettesgivesyoutheopportunitytocreateoroverwritedefaultnamedcolors.Bydefault,PHPPdfsupportsnamedcolors
fromtheW3Cstandard(forexample"black"="#000000").
YoucanuseapalettefortheDRYprinciple,becauseinformationaboutusedcolorswillbekeptinoneplace.Andyoucanalso
generateonedocumentwithdifferentpalettes.
Paletteofcolors
Example:
<!colors.xmlfile>
<colors>
<colorname="headercolor"hex="#333333"/>
<colorname="linecolor"hex="#eeeeee"/>
</colors>
<!stylesheet.xmlfile>
<h2color="headercolor"/>
<hrbackgroundcolor="linecolor"/>
<table>
<tdbordercolor="linecolor"/>
</table>
<!document.xmlfile>
<pdf>
<page>
<h2>Header</h2>
<hr/>
<table>
<tr>
<td>Data</td>
<td>Data</td>
</tr>
</table>
</page>
</pdf>
//phpcode
usePHPPdf\DataSource\DataSource
$facade=...
$content=$facade>render(DataSource::fromFile(__DIR__.'/document.xml'),DataSource::fromFile(__DIR__.'/stylesheet.xml'
ThelibrarysupportsprimaryHTMLtags:div,p,table,tr,td,b,strong,span,a,h1,h2,h3,h4,h5,img,br,ul,li
Inadditiontherearealsonotstandardtags:
dynamicpageautobreakablepage
pagesinglepagewithfixedsize
elasticpagesinglepagethataccommodatesitsheighttoitschildrenassameasanothertags(forexample"div").Header,
footer,watermark,templatedocumentattributedonotworkwiththistag.Usefulespeciallyingraphicfilesgeneration(image
engine).
pagebreak,columnbreak,breakbreakspageorcolumn,thistagmustbedirectchildof"dynamicpage"or"columnlayout"!
columnlayoutseparateworkspaceoncolumns,additionalattributes:numberofcolumns,marginbetweencolumns,equals
columns
barcodemoreinformationinbarcodechapter
circleelementthatborderandbackgroudareincircleshape.Additionalattributes:radius(itoverwriteswidthandheight
attributes)
piechartelementthatcanbeusedtodrawsimplepiechart(moreinformationinchartschapter.
Therearetagsthatareonlybagsforattributes,asetoftagsetc:
stylesheetstylesheetforparent
attributesimpleattributedeclaration,directchildof"stylesheet"tag.Requiredattributesofthiselement:nameattributename,
valueattributevalue
complexattributecomplexattributedeclaration,directchildof"stylesheet"tag.Requiredattributesofthiselement:name
complexattributename
placeholdersdefinesplaceholdersforparenttag.Childrentagsofplaceholderarespecyficforeveryparenttag.
metadatadefinesmetadataofpdfdocument,directchildofdocumentroot
Standardtags
behavioursdefinesbehavioursforaparenttag.Supportedbehaviours:href,ref,bookmark,note(actionassameasfor
attributeswithassameasname)
widthandheight:rigidlysetsheightandwidth,supportedunitsaredescribedinseparatesection.Relativevaluesinpercentare
supported.
maxwidth,maxheight:setsmaxsizesofelements
margin(margintop,marginbottom,marginleft,marginright):marginsimilartomarginfromHTML/CSS.Marginsofsimblings
arepooled.Forsidemarginspossibleis"auto"value,itworkssimilarasinHTML/CSS.
padding(paddingtop,paddingbottom,paddingleft,paddingright):workssimiliarasinHTML/CSS
fonttypefontnamemustoccursinfonts.xmlconfigfile,otherwiseexceptionwillbethrown
fontsizefilesizeinpoints,therearenoanyunit
fontstyleallowedvalues:normal,bold,italic,bolditalic
colortextcolor.HTML/CSSstylevaluesaresupported
breakableiftrue,elementisabletobebrokeninseveralpages.Defaultvalueformosttagsistrue..
floatworkssimilarbutnotthesameasinHTML/CSS.Allowedvalues:left|none|right,defaultnone
lineheightworkssimilarasinHTML/CSS.Defaultvalue:1.2*fontsize
textalignworksassameasinHTML/CSS.Allowedvalues:left|center|right|justify,defaultleft.
textdecorationallowedvalues:none,underline,overline,linethrough
breakbreakspageorcolumnintheendoftheownerofthisattribute.Ownerofthisattributemustbydirectlychildofdynamic
pageorcolumnlayouttag!
colspan,rowspanworkssimilarasinHTML(TODO:rowspanisn'timplementedyet)
hrefexternalurlwhereelementshouldlinking
refidofelementwhereownershouldlinking
bookmarkcreatebookmarkwithgiventitleassociatedwiththetag
notecreatestickynoteassociatedwithtag
dumpallowedvalues:trueorfalse.Createstickynotewithdebuginformations(attributes,positionetc.)
rotateangleofelementrotation.Thisattributeisn'tfullyimplemented,workscorectlyforwatermarks(see"Watermarks"
section).Possiblevalues:XXdeg(indegrees),XX(inradians),diagonally,diagonally.
alphapossiblevalues:from0to1.Transparencyforelementandhischildren.
linebreaklinebreak(trueorfalse),bydefaultsetontrueonlyfor"br"tag
styleassameasinhtml,thisattributecanbeusedtosetanotherattributes,forexample:style="width:100pxheight:200px
margin:20px0".Everyattributemustbefinishedby""char,eventhelast.
ignoreerror(onlyforimgtag)ignorefileloadingerrororthrowexception?Falsebydefault,thatmeansexceptionwillbe
thrown.
keepratio(onlyforimgtag)keepsratiobycuttingfragmentofimageevenifratioofsetteddimensionisnotthesameasratio
oforiginalsourceimage.Falsebydefault.
positionthesameasinhtml.Allowedvalues:static(default),relative,absolute
leftandrightthesameasinhtml,workswithpositionrelativeorabsolute.Rightandbottomisnotsupported.
Complexattributescanbesetbynotation"attributeName.attributeProperty"or"attributeNameattributeProperty"
Forexample:border.color="black"orbordercolor="black"
border:
color:bordercolor
style:posiblevalues:solid(solidline),dotted(predefineddottedline)oranydefinitionintheformofintegersseparatedby
space
type:whichedgeswillbeshowndefault"top+bottom+left+right"(alledges)."none"valueispossible(itdisableborder)
size:bordersize
radius:cornerroundinginunitsoflength(attention:ifthisparameterisset,typeparametewillbeignored,roundedborder
alwayswillbefullthiswillbefixedinfuture)
position:bordertranslationrelativetooriginalposition.Positivevaluesextendsborder,negativevaluesdecrasesborder.
Attributes
Complexattributes
Owingtomanipulationofthisparameter,youcanobtaincomplexpatternasborderifyouaddanotherborderswithdifferent
stylesandpositions.
background:
color:backgroundcolor
image:backgroundimage
repeat:wayofimagerepeating(none|x|y|all)
radius:roundingbackgroundcornersinunitsoflength(fornowonlyworkswithcolorbackground)
userealdimension:attributeonlyusedbypage(ordynamicpage).Trueforfillingalsomargins,falseinotherwise.
imagewidth:customwidthofbackgroundimage,percentagevaluesareallowed
imageheight:customheightofbackgroundimage,percentagevaluesareallowed
positionx:horizontalpositionforimageofbackground,allowedvalues:left,center,rightornumericvalue(default:left)
positiony:verticalpositionforimageofbackground,allowedvalues:top,center,bottomornumericvalue(default:top)
Itispossibletoaddseveralcomplexattributesinthesametype(forinstance3differentborders).
Youcanachievethatbyusingthe"stylesheet"taginsteadoftheshortnotation.
<pdf>
<dynamicpage>
<div>
<stylesheet>
<!Topandbootomedgesarered,sideedgesareyellowgray>
<complexattributename="border"color="red"type="top+bottom"/>
<complexattributeid="borderLeftAndRight"name="border"color="yellow"type="left+right"size="4px"
<complexattributeid="outerBorderLeftAndRight"name="border"color="gray"type="left+right"size="2px"
</stylesheet>
</div>
</dynamicpage>
</pdf>
Inthisexample,thesecondborderhasa"borderLeftAndRight"indentifie,ifthisborderhadnoid,theattributesfromsecondborder
wouldbemergedwiththeattributesfromfirstborder.
Remeberthedefaultidentifier"id"isassameasthe"name"attribute.The"id"attributesforcomplexattributeshasnothingtodowith
the"id"attributeoftags(usedininheritance).
Itispossibletocreatecomplexbordersthesameasinthepreviousexample(outerBorderLeftAndRight).
Supportedunitsfornumericalattributes:
in(inches)
cm(centimeters)
mm(milimeters)
pt(points)
pc(pica)*
px(pixels)
*%(percentonlyforwidthandheight).
Currentlyunsupportedunitsare:emandex
Whentheunitismissing(forexample:fontsize="10"),thenthedefaultunitispoints(pt).1pt=1/72inch
Barcodesaresupportedbythe<barcode>tag.
PHPPdfusestheZend\Barcodelibraryinordertogeneratebarcodes.
Units
Barcodes
Example:
<pdf>
<dynamicpage>
<barcodetype="code128"code="PHPPdf"/>
</dynamicpage>
</pdf>
<barcode>tagsupportsthemostofstandardattributesandhassomeotherattributes:
typetypofbarcode,supportedvalues:code128,code25,code25interleaved,code39,ean13,ean2,ean5,ean8,identcode,
itf14,leitcode,planet,postnet,royalmail,upca,upce
drawcodeequivalentofdrawCodeoptionfromZend\Barcode
barheightequivalentofbarHeightoptionfromZend\Barcode
withchecksumequivalentofwithChecksumoptionfromZend\Barcode
withchecksumintextequivalentofwithChecksumInTextoptionfromZend\Barcode
barthinwidthequivalentofbarThinWidthoptionfromZend\Barcode
barthickwidthequivalentofbarThickWidthoptionfromZend\Barcode
rotateequivalentoforientationoptionfromZend\Barcode
YoucanfindthedescriptionoftheseoptionsandtheredefaultvaluesintheZend\Barcodedocumentation.
Inordertorendertextualbarcodes,youcan'tusetofollowingembededpdffonts:courier,timesromanandhelvetica.Thiswillsoon
befixed.
PHPPdfsupportsdrawingsimplecharts.
Fornowthereisonlysupportforssimplepiechart.
Example:
<pdf>
<dynamicpage>
<piechartradius="200px"chartvalues="10|20|30|40"chartcolors="black|red|green|blue"></piechart>
</dynamicpage>
</pdf>
The<piechart>taghasthreeextraattributes:
radiusradiusofthechart
chartvaluesvaluesofthechart,togethertheymustbesummingto100.Eachvaluemustbeseparatedby"|".
chartcolorscolorsofeachvalue.Eachcolormustbeseparatedby"|".
Thelibrarysupportsexternalandinternalhyperlinks.
Externalhyperlinkslinktourl's,whileinternallinkslinktoothertagsinsidethepdfdocument.
Example:
<pdf>
<dynamicpage>
<ahref="http://google.com">gotogoogle.com</a>
<br/>
<aref="someid">gotoanothertag</a>
<ahref="#someid">gotoanothertag</a><!anchorstyleref>
<pagebreak/>
<pid="someid">Yep,thisisanothertag!)</p>
Charts
Hyperlinks
</dynamicpage>
</pdf>
Everyelementhasa"href"and"ref"attribute,evendiv.Youcan'tnestelementsinsidean"a"tag.
Ifyouwanttouseimgelementsasalink,youshouldusethehref(externallink)orref(internallink)attributedirectlyinimgtag.
Thepreferredwayofcreatingbookmarksisbyusingthe"behaviours"tag.
Thisdoesn'trestrictthestructureofthedocument,theownerofaparentbookmarkdoesn'thavetobeaparentofachild's
bookmarkowner.
Example:
<pdf>
<dynamicpage>
<div>
<behaviours>
<bookmarkid="1">parentbookmark</bookmark>
</behaviours>
Somecontent
</div>
<div>
<behaviours>
<bookmarkparentId="1">childrenbookmark</bookmark>
</behaviours>
Someanothercontent
</div>
<div>
<behaviours>
<bookmarkparentId="1">anotherchildrenbookmark</bookmark>
</behaviours>
Someanothercontent
</div>
<div>
<behaviours>
<bookmark>anotherparentbookmark</bookmark>
</behaviours>
Somecontent
</div>
</dynamicpage>
</pdf>
Ashortcutforthe"bookmark"behaviouristhe"bookmark"attribute,ifyouassignsomevaluetothisattribute,bookmarksthatrefers
tothistagwillbeautomaticallycreated.
Thebookmarkofaparenttagisalsotheparentofachildren'sbookmarks.
Example:
<pdf>
<dynamicpage>
<divbookmark="parentbookmark">
Somecontent
<divbookmark="childrenbookmark">
Someanothercontent
</div>
<divbookmark="anotherchildrenbookmark">
Someanothercontent
</div>
</div>
<divbookmark="anotherparentbookmark">
Somecontent
</div>
</dynamicpage>
</pdf>
Bookmarks
Theabovestructures(bothexamples)willcreatethisbookmarksstructure:
parentbookmark
childrenbookmark
anotherchildrenbookmark
anotherparentbookmark
Stickynotescanbecreatedbyusingthe"note"attribute.
Example:
<pdf>
<dynamicpage>
<divnote="notetext"></div>
</dynamicpage>
</pdf>
TheXMLparsernormalizesvaluesofattributes,wichresultsignoringnewlinecharacters.
Ifyouwanttoaddanotewithnewlinecharacters,youshouldusethissyntax:
<pdf>
<dynamicpage>
<div>
<behaviours>
<note>notetext</note>
</behaviours>
</div>
</dynamicpage>
</pdf>
"placeholders"canbeusedinforaddingarepetitiveheaderor/andfooter.
Someelementshavespecial"placeholders":pagehasheaderandfooter,tablealsohasheaderandfooter(TODO:notimplemented
yet)etc.
<pdf>
<dynamicpage>
<placeholders>
<header>
<divheight="50px"width="100%">
Header
</div>
</header>
<footer>
<divheight="50px"width="100%">
Footer
</div>
</footer>
</placeholders>
</dynamicpage>
</pdf>
Headerandfooterneedtohaveaheightattributeset.Thisheightispooledwithpagetopandbottommargins.
Workspaceisthepagesizereducedbypagemarginsandplaceholders(footerandheader)height.
Stickynotes
Repetitiveheadersandfooters
Pagecanhavea"watermark"placeholder.
Thewatermarkmaybesetonblock'sandcontainerelements,forinstance:div,p,h1(nospan,plaintextorimg).
Ifyouwanttouseanimageasawatermark,youshouldwraptheimgtaginadiv.
Example:
<pdf>
<dynamicpage>
<placeholders>
<watermark>
<!rotatecanhaveabsolutevalues(45degindegrees,0.123inradians)orrelativevalues("diagonally"and"diagonally"anglebetweendiagonalandbasesideofthepage)>
<divrotate="diagonally"alpha="0.1">
<imgsrc="path/to/image.png"/>
</div>
</watermark>
</placeholders>
</dynamicpage>
</pdf>
Therearetwotagsthatcanbeusedtoshowpageinformationinafooter,headerorwatermark:pageinfoandpagenumber.
Thiselementonlyworkswithdynamicpage,notsinglepages.Pageinfoshowsthecurrentandtotalpagenumber,pagenumber
showsonlythecurrentpagenumber.
Attributesofthistags:
formatformatofoutputstringthatwillbeusedasargumentofsprintffunction.Defaultvalues:"%s."forpagenumber,"%s/
%s"forpageinfo.
offsetvaluethatwillbeaddedtocurrentpagenumberandtotalpagenumber.Usefullifyouwanttocountpagesfromadiffrent
valuethanzero.Default:0.
Example:
<pdf>
<dynamicpage>
<placeholders>
<header>
<divheight="20px">
<pageinfoformat="page%sfor%s"/>
<!whenwewouldliketonumberfrom2>
<pageinfooffset="1"format="page%sfor%s"/>
<!whenwewouldliketodisplayonlycurrentpagenumber>
<pageinfoformat="%1$s."/>
<!or>
<pagenumber/>
<!whenwewouldliketodisplayonlytotalpagesnumber>
<pageinfoformat="%2$spages"/>
</div>
</header>
</placeholders>
Sometext
</dynamicpage>
</pdf>
Watermarks
Pagenumbering
The"page"and"dynamicpage"tagscanhavea"documenttemplate"attribute,thatallowsyoutouseanexternalpdfdocumentas
atemplate.
Forthe"page"tag,thepage'stemplatewillbethefirstpageofanexternaldocument.
Forthe"dynamicpage"tag,thetemplateforeachpagewillbethecorrespondingpageofanexternaldocument.
Example:
<pdf>
<dynamicpagedocumenttemplate="path/to/file.pdf">
<div>Somecontent</div>
</dynamicpage>
</pdf>
Pagecanbeseparatedoncolumns:
<pdf>
<dynamicpage>
<columnlayout>
<divwidth="100%"height="2500px"background.color="green">
</div>
</columnlayout>
</dynamicpage>
</pdf>
TheaboveXMLdescribesseveralpagesofthepdfdocument,withgreenrectanglesseparatedontwocolumns.
The"columnlayout"taghasthreeadditionalparameters:numberofcolumns,marginbetweencolumnsandequalscolumns.
Defaultvaluesforthisattributesare2,10andfalserespectlivy.Iftheequalscolumnsattributeisset,columnswillhavemoreorless
equalsheight.
Pageandcolumnmaybymanuallybrokenusingoneofthesetags:pagebreak,columnbreak,break.
Allthesetagsarethesame.Thesetagsneedtobedirectchildrenofthebreakingelement(dynamicpageorcolumnlayout).
Ifyouwanttoavoidautomaticpageorcolumnbreakoncertaintags,youshouldsetthe"breakable"attributeofthistagto"off.
Example:
<pdf>
<dynamicpage>
<divbreakable="false">thisdivwon'tbeautomaticallybroken</div>
</dynamicpage>
</pdf>
Metadatacanbeaddedbyattributesatthedocument'sroot.
Supportedmetadatais:Creator,Keywords,Subject,Author,Title,ModDate,CreationDateandTrapped.
Usingapdfdocumentasatemplate
Separatepageoncolumns
Breakingpagesandcolumns
Metadata
**Theseattributenamesarecasesensitive.**
Example:
<pdfAuthor="PiotrSliwa"Title="Testdocument">
<!someotherelements>
</pdf>
Thelibraryhasfourprimaryconfigfilesthatallowyoutoadoptthelibraryforspecyficneedsandextending.
complexattributes.xmldeclarationsofcomplexattributesclassestologicalnamesthatidentifyattributeinwholelibrary.
nodes.xmldefinitionsofallowedtagsinxmldocumentwithdefaultattributesandformattingobjects.
fonts.xmldefinitionsoffontsandassigningthemtologicalnamesthatidentifyfontinwholelibrary.
colors.xmlpaletteofcolorsdefinitions
Inordertochangedefaulttheconfigfiles,youmustpasstoFacadeconstructorconfiguredLoaderobject:
$loader=newPHPPdf\Core\Configuration\LoaderImpl('/path/to/file/nodes.xml','/path/to/file/enhancements.xml','/path/to/file/fonts.xml'
$facade=newPHPPdf\Core\Facade($loader)
Ifyouwanttochangeonlyoneconfigfile,youshoulduseLoaderImpl::set*method:
$loader=newPHPPdf\Core\Configuration\LoaderImpl()
$loader>setFontFile('/path/to/file/fonts.xml')//therearesetFontFile,setNodeFile,setComplexAttributeFileandsetColorFilemethods
$facade=newPHPPdf\Core\Facade($loader)
FacadeBuildercanbeusettobuildandconfigureFacade.FacadeBuilderisabletoconfigurecache,renderingengineanddocument
parser.
$builder=PHPPdf\Core\FacadeBuilder::create(/*youcanpassspecyficconfigurationloaderobject*/)
>setCache('File',array('cache_dir'=>'./cache'))
>setUseCacheForStylesheetConstraint(true)//stylesheetswillbealsousecache
$facade=$builder>build()
Librarysupportsbasic(official)markdownsyntax.Toconvertmarkdowndocumenttopdf,youshouldconfigureFacadeobjectby
MarkdownDocumentParser.YoualsomighttouseFacadeBuildertodothisforyou.
Example:
$facade=PHPPdf\Core\FacadeBuilder::create()
>setDocumentParserType(PHPPdf\Core\FacadeBuilder::PARSER_MARKDOWN)
>setMarkdownStylesheetFilepath(/**optionalypathtostylesheetinxmlformat*/
>build()
Bydefault,inmarkdownpdfdocument,helveticafontisused.Ifyouwanttouseutf8charactersorcustomizeapdfdocument,you
shouldprovideyourownstylesheetbyusingtheFacadeBuilder::setMarkdownStylesheetFilepathmethod.
Thestylesheetstructurehasbeendescribedinthestylesheetchapter.Bydefaultthestylesheetisempty,ifyouwanttosetanother
fonttype,thestylesheetshouldlooklikethis:
Configuration
Markdownsupport
<stylesheet>
<anyfonttype="DejaVuSans"/>
</stylesheet>
InternallytheMarkdownDocumentParserconvertsamarkdowndocumenttohtml(viathePHPmarkdownlibrary),thenconverts
htmltoxml,andatlastxmltoapdfdocument.
Beawareofthat,ifyouinamarkdowndocumentuserawhtmlthatwillbeincompatiblewiththexmlsyntaxofPHPPdf(forexample
unexistendattributesortags),theparserwillthrowanexceptionthen.
NotalltagsusedinthemarkdownimplementationarepropertlysupportedbyPHPPdf,forexample"pre"and"code"tags.
Fornow"pre"tagisanaliasfor"div",and"code"tagisanaliasfor"span",beawareofthat.
PHPPdfisabletogenerateimage(jpgorpng)filesinstedofapdfdocument.Toachievethat,youmustconfigurethe
FacadeBuilder,example:
$facade=PHPPdf\Core\FacadeBuilder::create()
>setEngineType('image')
>build()
//rendermethodreturnsarrayofimages'sources,onepdfpageisgeneratedtosingleimagefile
$images=$facade>render(...)
BydefaulttheGDlibraryisusedtorenderanimage.
ButyoucanalsouseImagick,whichoffersabetterquality,soitisrecommendedthatifyouhavetheopportiunitytoinstallImagick
onyourserver.Toswitchthegraphiclibrary,youmustconfiguretheFacadeBuilderobjectusingthesetEngineOptionsmethod:
$builder=...
$builder>setEngineOptions(array(
'engine'=>'imagick',
'format'=>'png',//png,jpegorwbmp
'quality'=>60,//intfrom0to100
))
Supportedgraphiclibrariesare:GD(default),imagick,gmagick.PHPPdfusestheImaginelibraryasaninterfaceforgraphicsfile
generation.
Belowisalistofknownlimitationsofthecurrentversionofthelibrary:
therenowaytoinjectanimageintoatextwithfloatingwillbeintroducedinthenextreleases
partialsupportforfloatattributewithintableelement(floatsmightworkimproperlywithinatable)
verticalalignattributeworksimproperlyifinelementwiththisattributeset,aremorethanoneelement
borderdoesn'tchangedimensionsoftheelement(whileinHTMLtheydo)
pngfiles(expeciallywithoutcompression)areinefficient.pngfileswithhighcompression(compressionlevel6orhigher)orjpeg
shouldbeusedinstead
notalltagsarepropertlysupported,forexamplethe"pre"tagisanaliasto"div"andthe"code"tagisanaliasfor"span"
nestingoflineartags(text,span,code,pageinfo,pagenumber,a,b,i,em)isnotproperlysupported.Ifonelineartagcontains
another,onlytextwithinthistagsismerged,stylesaretakenfromthemostoutherlineartag.
automaticgeneratingof"tableofcontents"
Imagegenerationengine
Knownlimitations
TODOplans
improvetable,headerandfooterfortable,rowspan.Fixcalculationofcell'sminheightwhencolspanisused.
supportforsimplebarandpiecharts
Thislibraryworkswithphp5.3andup.
Technicalrequirements
Status API Training Shop Blog About 2014GitHub,Inc. Terms Privacy Security Contact
[

Vous aimerez peut-être aussi