asp.net open pdf in new window code behind : Reader shrink pdf software control cloud windows web page azure class itext_so-sample1-part663

QuestionsaboutPDFingeneral
5
• AdobeLCisasuiteofmodules,someofwhichcanonlybeprovidedbyAdobe.Forinstance:
nothirdpartycan“Readerenable”PDFdocumentsbecauseReaderenablingrequiresaprivate
keythatisproprietarytoAdobe.However:iTextcompeteswithAdobeLCinsomeareas,for
instancedigitalsigning(readthewhitepaperfromtheOfficeofLegislativeCounselondigital
signatures¹⁰)andformfilling(iTexthasanadd-oncalledXFAWorker¹¹thatcanconvertyour
dynamicXFAformsintostaticPDF,e.g.PDF/A)
DoesaPDFfilehavestyles,headersandfooters?
DoesaPDFfilehavestyles,headersandfootersinformationasisthecasewithdocxfiles
thathaveseparatexmlfileswithextrainformation?
PostedonStackOverflowonJan21,2014¹²byPrakhar¹³
RegularPDFsdon’thavestyles,butdifferentfonts(forinstanceHelveticaisonefont,Helvetica-Bold
isanotherfontofthesamefamily).Theydon’thaveheadersandfooters,justliketheydon’thave
paragraphs,sectiontitles,tablerowsortablecells.EverythingyouseeinaPDFpage,isjustabunch
ofglyphs,pathsandshapesdrawnonacanvas.
However: if your PDF is a Tagged PDF, the e PDF F contains something that t is s known as the
StructTreeRoot
.Thismeansthat,apartfromthepresentationofthecontent,youalsohaveatree
structurethatstoresthesemanticsofthecontent.Thisstructurecontainsreferencestothecontent
onthedifferentpages,allowingyou(forinstance)tofindoutwhichlinesbelongtogetherina
paragraph,whichpartsofthepageare“artifacts”(suchasarepeatingpageheaderorafooterwith
apagenumber),whichcontentisorganizedasatable,etc…
TaggedPDFisarequirementforPDF/ALevelAandPDF/UAdocuments.AmajorityofthePDF
filesyoucanfindinthewildaren’ttagged(oraren’ttaggedproperly).
¹⁰
http://www.mnhs.org/preserve/records/legislativerecords/docs_pdfs/CA_Authentication_WhitePaper_Dec2011.pdf
¹¹
http://itextpdf.com/product/xfa_worker
¹²
http://stackoverflow.com/questions/21259333/does-pdf-has-styles-headers-and-footers-information-as-docx
¹³
http://stackoverflow.com/users/1881995/prakhar
Reader shrink pdf - Compress reduce PDF size in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
C# Code & .NET API to Compress & Decompress PDF Document
change font size fillable pdf; best way to compress pdf files
Reader shrink pdf - VB.NET PDF File Compress Library: Compress reduce PDF size in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
VB.NET PDF Document Compression and Decompression Control SDK
pdf files optimized; change page size pdf acrobat
Gettingstarted
ThemostpopulariTextexampleisthe“HelloWorld”example,explainingthefivestepstocreatea
PDFfromscratchusingiText:
// step 1
Document document new Document();
// step 2
PdfWriter.getInstance(documentnew FileOutputStream(filename));
// step 3
document.open();
// step 4
document.add(new Paragraph("Hello World!"));
// step 5
document.close();
Obviously,iTextiscapableofdoingmuchmorethancreatingaPDFthatshowsthewords“Hello
World”,butlet’stakealookatsomebasicquestionstogetstarted.
HowtogenerateanddesignPDFswithiTextor
iTextSharp?
I’mwonderingwhatisthebest/easiestwaytodesignaPDFdocument?Isitremotely
legittoactuallydesignawholePDFdocumentwithiTextSharpwithcode(i.enotloading
externalfiles)?Iwantthefinalresulttolooksimilartoawebpagewithvariouscolors,
borders,imagesandeverything.
Ordoyouhavetorelyonotherdocumentslike.doc,.htmlfilestoachieveagooddesign?
OriginallyIthoughtthatIwoulduseHTMLmarkuptogenerateaPDF,butwhyevenuse
aHTMLmarkuporatemplatefiletocreatethePDFdesignwhenIcouldjustdoitright
withinthePDFwithouthavingtorelyononvariousfilesthatservesnorealpurpose.
IsitpossibletogenerateanddesignbigPDFdocumentsusingcodeandarethereanymore
properguidesorsimilarwithallthevariouscommandstogeneratetexts,images,borders
andeverythingsinceIhavenorealclueaboutgeneratingPDFwithcode.
PostedonStackOverflowonOct6,2014¹⁴byHenrikP¹⁵
¹⁴
http://stackoverflow.com/questions/26218444/generate-and-design-pdf-with-itextsharp-or-similar
¹⁵
http://stackoverflow.com/users/2914876/henrikp
VB.NET Image: Image Scaling SDK to Scale Picture / Photo
licenses; Allow VB.NET programmers to enlarge & shrink source image file while maintain original image width to height ratio; Scaled
change font size in fillable pdf form; acrobat compress pdf
VB.NET TIFF: How to Convert TIFF to GIF Using VB.NET TIFF to GIF
VB.NET, please change the function code "ImageFormat.Gif" to "ImageFormat.Jpeg/Pdf". Welch - a simple form of file compressing) compression to shrink file size
pdf reduce file size; pdf page size
Gettingstarted
7
Thequestionisverybroad,soIcanonlygiveyouaverybroadanswer.
Option1:youcreateyourlayoutbyusingiText’shigh-levelobjects.Therearecountlessapplications
outtherethatareusing
PdfPTable
togeneratecomplexreports.Forinstance:thetimetablesfora
GermanRailwaycompanyarecreatedfromscratchthroughcode;theinvoicesforaBelgianTelco
companyarecreatedthisway,…Theadvantageofthisapproachisthatyoucanreallyfine-tunethe
layout.Thedisadvantageisthatyouneedtochangesourcecodeassoonasyouwanttochangethe
layout.
Option2:youcreateyourlayoutbycreatinganAcroFormtemplate.Everyfieldinthistemplate
hasanameandisvisualizedatexactpositions(definedbyitscoordinates)onspecificpages.The
codetofilloutsuchaformconsistsofonlyahandfuloflines.Wheneveryouneedtochangethe
layout,youaltertheAcroFormtemplate.Youdonotneedtochangeyourcode.Thedisadvantageis
thatAcroFormsareverystatic.Compareittoapaperform:youcan’tinsertarowinapaperform
either.
Option3:youcreateyourdata inXHTMLformatandyourstylesinCSS.ABelgianprinting
companyresponsibleforcreatinginvoicesforitscustomersisstreamingdataintoverysimpleHTML
filesinvolvingasequenceoftablesthatneverspanmorethanahandfulofpages.Thesefilesare
thenfedtoiText’sXMLworkeralongwithaCSSthatisdifferentforeachofitscustomers.The
advantageofthisapproachisthatnoextraprogrammingisneededwhenanewcustomerjoins.It’s
justamatterofcreatinganewCSS.ThedisadvantageisthatyouarelimitedbytheHTMLformat.
Elementarylogicalsotellsyouthatyoushouldn’texpectURL2PDF:haveyouevertriedprinting
awebsite?Well,thebadqualityofthatprintshouldgiveyouanindicationoftheproblemsyou’ll
encounterwhentryingtoconvertHTMLtoPDF.Ifyouanticipatethem,youcangetgoodresults.
Ifyoudon’t:it’sapoorcraftsmanwhoblameshistools…
Option4:defineyourtemplateusingtheXMLFormsArchitecture(XFA).Suchtemplatesareusually
createdusingAdobeLiveCycleDesigner.AnXSDisfedintoLCDesignerandtheresultisanempty
formwherethePDFformatactsasacontainerforanXMLstream.YoucanthenuseiTexttoinject
yourcustomXMLcontainingdatathatconformswiththeXSDintothePDFandyoucanuseXFA
Workertoflattensuchaform.XFAWorkerisonlyavailableasaclosedsourceproduct(giversneed
tosetlimitsbecausetakersrarelydo).
Option5:rightnowXMLWorkerisusedtoconvertXHTML+CSSandXFAtoPDF(ordinaryPDF,
PDF/A,PDF/UA).YoucouldusethegenericXMLWorkerenginetosupportyourownXMLformat.
Theadvantagewouldbeaverypowerfulenginethatyoucantunetomeetyourexactneeds.The
disadvantageisthatthisinvolvesaseriousup-frontdevelopmentinvestment.
Option6:useathirdpartytooltodefinethetemplateandathirdpartyserverthatusesiTextunder
thehoodtocreatePDFsbasedonthetemplate.AnexampleofsuchathirdpartytoolisScriptura
developedbyInventiveDesigners.Thereareothertools,butInventiveDesignersisacustomerof
iTextandweknowthattheyareusingiTextcorrectlywhereaswedon’thavethisguaranteefrom
othervendors.
VB.NET Image: Image Resizer Control SDK to Resize Picture & Photo
image resizing method is extremely easy and developers can shrink or reduce dedicated to provide powerful & profession imaging controls, PDF document, image to
pdf text box font size; change font size in pdf text box
VB.NET PowerPoint: Convert PowerPoint to BMP Image with VB PPT
If you convert PowerPoint to BMP image, it can help you shrink the file size files just like our other document converters, such as VB.NET PDF Converter, Excel
pdf compress; pdf compression
Gettingstarted
8
HowtocreateacomplexPDFdocument?
IhaveanJava/JavaEEbasedapplication whereinIhavearequirementtocreatePDF
certificatesforvariousservicesthatwillbeprovidedtotheusers.Iamlookingforaway
tocreatePDF(noneedfordigitalcertificatesfornow).Whatistheeasiestandconvenient
wayofdoingthat?Ihavetried
1. XSLtoPDFconversion
2. HTMLtoPDFconversionusingitext.
3. thecrudeJavaway(using
PdfWriter
,
PdfPTable
,etc.)
Whatisthebestwayoutofthese,oristhereanyotherwaywhichiseasierandconvenient?
PostedonStackOverflowonJan4,2013¹⁶byAnkit¹⁷
WhenyoutalkaboutCertificates,Ithinkofstandardsheetsthatlookidenticalforeveryreceiverof
thecertificate,exceptfor:
• thenameofthereceiver,
• thecoursethatwasfollowedbythereceiver,
• adate.
Ifthis isthecase,Iwould useany tool thatallowsyou tocreateafancy certificate(Acrobat,
OpenOffice,AdobeInDesign,…)andcreateastaticform(sometimesreferredtoasanAcroForm)
containingthreefields:
name
,
course
,
date
.
IwouldthenuseiTexttofillinthefieldslikethis:
PdfReader reader new PdfReader(pathToCertificateTemplate);
PdfStamper stamper =
new PdfStamper(readernew FileOutputStream(pathToCertificate));
AcroFields form stamper.getAcroFields();
form.setField("name"name);
form.setField("course"course);
form.setField("date"date);
stamper.setFormFlattening(true);
stamper.close();
reader.close();
¹⁶
http://stackoverflow.com/questions/14151335/creating-complex-pdf-using-java
¹⁷
http://stackoverflow.com/users/810176/ankit
Gettingstarted
9
Creatingsuchacertificatefromcodeis“thehardway”;creatingsuchacertificatefromXMLis“a
pain”(becauseXMLisn’twell-suitedfordefiningalayout),creatingacertificatefrom(HTML+
CSS)ispossiblewithiText’sXMLWorker,butallofthesesolutionshavethedisadvantagethatit’s
hardworktopositioneveryitemcorrectly,tomakesureeverythingfitsonthesamepage,etc…
It’smucheasiertomaintainatemplatewithfixedfields.Thisway,youonlyhavetocodeonce.If
forsomereasonyouwanttomovethefieldstoanotherplace,youonlyhavetochangethetemplate,
youdon’thavetoworryaboutmessingaroundincode,XML,HTMLorCSS.
Pleasegotothesectionaboutinteractiveformstolearnmoreaboutthistechnology.
HowtosetthepagesizetoEnvelopesizewith
Landscapeorientation?
IcreateaPDFdocumentusingiTextSharpandthiscode:
Document pdfDoc c = new Document(PageSize.A4.Rotate(), 10f10f100f0f);
IgoogledbutIcouldn’tfindtheEnvelopesize.HowdoIsetthepagesizeasEnvelopewith
Landscapeorientation?
PostedonStackOverflowonSep17,2014¹⁸byKing_Fisher¹⁹
YouarecreatinganA4documentinlandscapeformatwiththisline:
Document pdfDoc c = new Document(PageSize.A4.Rotate(), 10f10f100f0f);
Ifyouwanttocreateadocumentinenvelopeformat,youshouldn’tcreateanA4page,insteadyou
shoulddothis:
Document pdfDoc c = new Document(envelope, 10f10f100f0f);
Inthisline,
envelope
isanobjectoftype
Rectangle
.
Thereisnosuchthingastheenvelopesize.Therearedifferentenvelopesizestochoosefrom.Take
alookattheenvelopesizechart²⁰.
Forinstance,ifyouwanttocreateapagewiththesizeofa6-1/4CommercialEnvelope²¹,thenyou
needtocreatearectanglethatmeasures6by3.5inch.ThemeasurementsysteminPDFdoesn’tuse
inches,butuserunits.Bydefault,1userunit=1point,and1inch=72points.
Henceyou’ddefinethe
envelope
variablelikethis:
¹⁸
http://stackoverflow.com/questions/25886909/how-do-i-set-page-size-as-envelope-landscape-in-itextsharp
¹⁹
http://stackoverflow.com/users/3141617/king-fisher
²⁰
http://www.paper-papers.com/envelope-size-chart.html
²¹
http://www.paper-papers.com/6-14-Commercial-Envelopes-24lb-WHITE-WOVE-35-x-6.html
Gettingstarted
10
Rectangle envelope = new Rectangle(432252);
Because:
6 inch x 72 points = = 432 2 points (the width)
3.5 inch x x 252 2 points = 252 points (the height)
Ifyouwantadifferentenvelopetype,youhavetodotheMathwiththedimensionsofthatenvelope
format.
Fonts
Simplefonts,compositefonts,embeddedfonts,encoding,ttffiles,specialcharacters,righttoleft
writingsystems,…Thischapteriswhereallyourquestionsaboutfontsbelong.
HowtousethefontVerdanain
PdfStamper
?
IwanttouseVerdanaasafontwhilestampingaPDFfilewithiTextPDF.Theoriginalfile
usesVerdana,whichisn’tanoptionintheclassBasefont.
Hereisthefunctiontocreatemyfontrightnow:
def standardStampFont() {
return BaseFont.createFont(BaseFont.HELVETICABaseFont.WINANSIfalse)
}
I’d like to change e that to the e Verdana a Font, , but t simply exchanging g the e Part
BaseFont.HELVETICA
with
"Verdana"
doesn’twork.
PostedonStackOverflowonOct16,2014²²byAlainSarti²³
iTextcansupporttheStandardType1fonts,becauseiTextshipswithAFMfile(AdobeFontMetrics
files).iTexthasnoideaaboutthefontmetricsofotherfonts(Verdanaisn’taStandardType1font).
YouneedtoprovidethepathtotheVerdanafontfile.
BaseFont.createFont("c:/windows/fonts/verdana.ttf"BaseFont.WINANSIBaseFont.E\
MBEDDED)
NotethatIchange
false
to
BaseFont.EMBEDDED
becausethesameproblemyouhaveonyourside,
willalsooccuronthesideofthepersonwholooksatyourfile:hisPDFviewercanrenderStandard
Type1fonts,butmaynotbeabletorenderotherfontssuchasVerdana.
Caveat:Thehardcodedpath
"c:/windows/fonts/verdana.ttf"
worksformeonmylocalmachine
becausethefontfilecanbefoundusingthatpathonmylocalmachine.Thiscodewon’tworkon
theserverwhereIhosttheiTextsite,though(whichisaLinuxserverthatdoesn’tevenhavea
c:/windows/fonts
directory).Iamusingthishardcodedpathbywayofexample.Youshouldmake
surethatthefontispresentandavailablewhenyoudeployyourapplication.
²²
http://stackoverflow.com/questions/26404418/how-to-use-verdana-font-in-stamper-itext-pdf
²³
http://stackoverflow.com/users/1817618/alain-sarti
Fonts
12
Whydoesn’tFontFactory.GetFont()workforallfonts?
IfIsay:
var georgia FontFactory.GetFont("Georgia Regular", 10f);
itdoesn’twork.WhenIcheckthestateofthevariablegeorgia,ithasits
Family
property
settothevalue
UNDEFINED
andits
FamilyName
propertysetto
Unknown
.
ItonlyworksifIactuallyloadandregisterthefontfileandthengetitlikeso:
FontFactory.Register("C:\\Windows\\Fonts\\georgia.ttf""Georgia");
var georgia FontFactory.GetFont("Georgia", 20f);
Whyisthat?
PostedonStackOverflowonJun3,2014²⁴byWaterCoolerv2²⁵
iTextiswritteninJava,whichmeansit’splatform-independent.Itshipswith14AFMfilescontaining
themetricsofthe14StandardType1fonts(4flavorsofHelvetica,4flavorsofTimesRoman,4flavors
ofCourier,SymbolandZapfDingbats).
Assoonasyouneedotherfonts,youneedtoregisterthefontfilesbypassingthepathtothe
fontdirectoryorthepathtoanactualfont.ThefontdirectoryonLinuxis differentfromthe
fontdirectory onWindows(there isno“C:/Windows/fonts” onLinux).There’salsoa method
registerDirectories()
thatlooksattheoperatingsystemyou’recurrentlyusingandthatregisters
allthe‘usualsuspects’(iTextguessesthefontpathbasedontheOS).Thismethodisexpensive:it
registersallfontsitfindsandthiscoststimeandmemory.
Oncefontsareregistered,youcanaskthe
FontFactory
fortheregisterednames.Thisisshownin
theFontFactoryExample²⁶.You’llnoticethedifferencebetweenthe
getRegisteredFonts()
method
andthe
getRegisteredFamilies()
method.
Additionalnote:theoriginalquestionisaboutiTextSharp,writteninC#.iTextSharpisportedfrom
JavaandtriestostayascloseaspossibletotheoriginalversionwritteninJava.Nevertheless,the
samerationaleapplies:startingupanapplicationwouldbemuchslowerifiTextSharpwouldhave
toscanthefontsdirectory.Inmostapplications,youonlyneedahandfuloffonts;registeringall
fontsavailableintheWindowsfontsdirectorywouldbeoverkill.
²⁴
http://stackoverflow.com/questions/24007492/why-doesnt-fontfactory-getfontknown-font-name-floatsize-work
²⁵
http://stackoverflow.com/users/303685/water-cooler-v2
²⁶
http://itextpdf.com/examples/iia.php?id=212
Fonts
13
Whyaren’tmyfontsgettingregistered?
IhaveaprogramusingiTextSharpthatincludesthecode
FontFactory.RegisterDirectories();
foreach (string fontname in FontFactory.RegisteredFonts) {
Log.Info("**** Found d registered font: : " + fontname);
}
WhenIrunit(usingMonoonaCentOSbox),thelogshowsonlythecorePostScriptfonts:
• zapfdingbats
• times-roman
• times-italic
• helvetica-boldoblique
• courier-boldoblique
• helvetica-bold
• helvetica
• courier-oblique
• helvetica-oblique
• courier-bold
• times-bolditalic
• courier
• times-bold
• symbol
ButIhave156TTFfilesundermy
/usr/share/fonts
directorytree(whichisoneofthe
directoriesmentionedinthecodeforthe
RegisterDirectories
function).Whyaren’tthese
beingregistered?
PostedonStackOverflowonNov29,2013²⁷bydan04²⁸
TherearesubtledifferencesbetweeniTextandiTextSharp.
IniText,
registerDirectories()
lookslikethis:
²⁷
http://stackoverflow.com/questions/13635212/why-arent-my-fonts-getting-registered
²⁸
http://stackoverflow.com/users/287586/dan04
Fonts
14
public int registerDirectories() {
int count = 0;
String windir System.getenv("windir");
String fileseparator System.getProperty("file.separator");
if (windir != null && fileseparator != null) {
count += registerDirectory(windir fileseparator "fonts");
}
count += registerDirectory("/usr/share/X11/fonts"true);
count += registerDirectory("/usr/X/lib/X11/fonts"true);
count += registerDirectory("/usr/openwin/lib/X11/fonts"true);
count += registerDirectory("/usr/share/fonts"true);
count += registerDirectory("/usr/X11R6/lib/X11/fonts"true);
count += registerDirectory("/Library/Fonts");
count += registerDirectory("/System/Library/Fonts");
return count;
}
IniTextSharphowever,themethodlookslikethis:
public virtual int RegisterDirectories() {
string dir = Path.Combine(
Path.GetDirectoryName(Environment.GetFolderPath(
Environment.SpecialFolder.System)), "Fonts");
return RegisterDirectory(dir);
}
Javaisplatformindependent,sowehavetolookforthe‘usualsuspects’.C#isWindowsspecific,
sowecandependontheenvironmenttotelluswheretofindfonts.YourquestiontellsusthatMono
doesn’tsupportthis,soyou’llhavetouse
FontFactory.RegisterDirectory("/usr/share/fonts");
Documents you may be interested
Documents you may be interested