Images
Inthissection,you’llfindthequestionsrelatedtorasterimages,suchasJPG,PNG,GIF,andsoon.
Whyaren’timagesaddedsequentially?
Iamworkingonapdfreportthatcontainstopicsandimages(charts).Thedocumentis
formattedthisway:
NR.TOPICTITLEFORTOPIC1
CHARTIMAGEfortopic1(frombytearray)
NR.TOPICTITLEFORTOPIC2
CHARTIMAGEfortopic2…
Let’sassumethatIaddthisinformationinaloop,andthattheloopruns10times.Iexpect
10topictitlesalldirectlyfollowedbytheimage.
However,ifthepageendisreachedandanewimageshouldbeadded,Inoticethatthe
imageismovedtothenextpageandthenexttopictitleisprintedonthepreviouspage.
Soonpaperwehave:
page 1: : topic c 1
image topic c 1
topic 2
image topic c 2
topic 3
topic 4
page 2: : image e topic c 3
image topic c 4
topic 5
image topic c 5
Sotheorderoftheelementsonpaper,isNOTthesameastheorderthatIusedtoputthe
elementinthedocumentviathe‘document.add()method.Thisisreallystrange.Anyone
hasanyidea?
PostedonStackOverflowonMar26,2014²⁹bywimboone³⁰
²⁹
http://stackoverflow.com/questions/22664126/image-not-sequentialy-added-in-pdf-document-itextsharp-wrong-order-of-elements
³⁰
http://stackoverflow.com/users/3149519/wim-boone
Pdf edit text size - Compress reduce PDF size in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
C# Code & .NET API to Compress & Decompress PDF Document
best pdf compressor online; adjust pdf size
Pdf edit text size - 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
adjust size of pdf in preview; can a pdf be compressed
Images
16
Ifyouhavea
PdfWriter
instance(forinstance
writer
),youneedtoforceiTexttousestrictimage
sequencelikethis:
writer.setStrictImageSequence(true);
Otherwise,iTextwillpostponeaddingimagesuntilthere’ssufficientspaceonthepagetoaddthe
image.
HowtogettheimageDPIinPDF?
I’mtryingtogetinformationaboutscannedimagesthataresavedintoPDFfilesthrough
iText(usingJava).Icangetwidthandheight(eitherthroughMatrix,orthroughBuffered-
Image).TheideawastousetheanswerheretocalculatetheDPI,butIamabitlost.Are
thesevalues(widthandheight)inpixelsorpoints?Isthereanyotherwaytoachievethis?
TherearealotofanswersonhowtoscaleandsaveanimagetoaPDFfile,butIdidn’tfind
anyonhowtoreadthewidth/height/scaleofanimageandbeconfidentabouttheresult.
PostedonStackOverflowonAug28,2014³¹byFinik³²
Let’ssplitthisproblemintotwoseparateproblems.TocalculatetheDPI,youneedtwosetsofvalues:
anumberofpixelsandadistanceininch.
1. Numberofpixels:youobtaintheimageandtheimageconsistsofpixels.Youcanretrievethe
widthandheightoftheimageinpixelsfromtheimage.Let’ssaythesevaluesare
wPx
and
wPx
.
2. Distanceininch:youobtainthematrixwhichgivesyouvaluesexpressedinpoints.As72
pointsequal1inch,youneedtodividethesevaluesby72.Let’ssaythesevaluesare
wInch
and
hInch
.
NowyoucancalculatetheDPIinthexdirectionlikethis:
wPx/ wInch
andtheDPIintheydirection
likethis:
hPx / hInch
.
³¹
http://stackoverflow.com/questions/25550000/getting-image-dpi-in-pdf-files-using-itext
³²
http://stackoverflow.com/users/1300529/finik
C# PDF insert text Library: insert text into PDF content in C#.net
Powerful .NET PDF edit control allows modify existing scanned PDF text. Ability to change text font, color, size and location and output a new PDF document.
change font size in pdf form; pdf text box font size
VB.NET PDF File Split Library: Split, seperate PDF into multiple
Divide PDF file into multiple files by outputting PDF file size. Split Split PDF File by Output File Size Demo Code in VB.NET. This
change font size pdf fillable form; pdf page size limit
Images
17
HowtopreservehighresolutionimagesinPDF?
I’mtryingtoputhighqualityimagesintoPDF(oneperpage).ButifIsetpagesizetoa4,I
havetoresizemypictures,becausethey’retoolarge.Thentheyloosetheirquality.Isthere
anywaytoputbigimagetoa4pagewithoutloosingquality?
I’musingiTextSharplibrary,firstlyI’mcreatingthedocument
document = new Document(PageSize.A4, 0000);
FileStream output t = new FileStream(pdfPath + "document.pdf", FileMode.Create);
PdfWriter writer = = PdfWriter.GetInstance(document, output);
document.Open();
thenI’maddingeachpicture
document.Add(iTextSharp.text.Image.GetInstance(toSaveImage, System.Drawing.Imagi\
ng.ImageFormat.Tiff));
andclosingthedocument
document.Close();
PostedonStackOverflowonjun6,2013³³byComPiler³⁴
Firstletmeclearacoupleofmisunderstandings:
• aPDFdocumentassuchdoesn’thavearesolution.ThereisnosuchthingasDPIinPDF.The
resolutiononlycomesintoplaywhenaPDFisrendered(tothescreen,topaper,…)andthat’s
whytheremaybeaDPIinaPDFviewer(butthat’ssomethingcompletelydifferent).
• whenyouscalean
Image
objectiniTextSharp,youdon’tloseanyinformation:thenumber
ofpixelsremainsthesame.WhereasPDFdoesn’thavearesolution,theimagesinsideaPDF
do.Whenyoutheimagescaledown(thatis:youputthesamenumberofpixelsonasmaller
canvas),theresolutionincreases;whenyouscaleup,theresolutiondecreases.
Nowforyourquestion:you’renotobligedtocreateA4pages:
³³
http://stackoverflow.com/questions/16970106/c-sharp-high-resolution-images-in-pdf
³⁴
http://stackoverflow.com/users/2411220/com-piler
C# PDF Convert to Tiff SDK: Convert PDF to tiff images in C#.net
zoomValue, The magnification of the original PDF page size. 0.1f
pdf optimized format; reader compress pdf
C# PDF Convert to Word SDK: Convert PDF to Word library in C#.net
of original PDF file and maintains the original text style (including font, size, color, links you often need to use and edit PDF document content
change font size in pdf comment box; reader pdf reduce file size
Images
18
Image img g =
iTextSharp.text.Image.GetInstance(toSaveImage,
System.Drawing.Imaging.ImageFormat.Tiff);
Rectangle pagesize = new Rectangle(img.ScaledWidth, , img.ScaledHeight);
Document document = new Document(pagesize);
img.SetAbsolutePosition(00);
document.Add(img);
Icreatedthe
Document
basedonthescaleddimensionsoftheImage.Don’tletthemethodnames
mislead you:
ScaledWidth
and
ScaledHeight
are the safest methods to use whengetting the
dimensionsofan
Image
.Notonlydotheyincludeanyscalingoperations,youmayhavedoneon
theimage,thealsotakeintoaccountthespaceneededfortheimageafterrotatingit.
ObservethatI’vesettheabsolutepositiontothelower-leftcorner.That’ssaferthansettingthepage
marginsto0.
Ifyoudon’twanttochangethepagesize,thenyouhavetousethe
ScaleToFit()
method:
Image img g =
iTextSharp.text.Image.GetInstance(toSaveImage,
System.Drawing.Imaging.ImageFormat.Tiff);
img.ScaleToFit(PageSize.A4);
Scaletofitwillkeeptheaspectratiooftheimage.Iftheaspectratiooftheimageisdifferentfrom
theaspectratioofthepage,thepagewillhaveamargin.
C# PDF File Split Library: Split, seperate PDF into multiple files
Divide PDF file into multiple files by outputting PDF file size. Split PDF document by PDF bookmark and outlines. Split PDF file by output file size.
pdf change page size; pdf page size dimensions
C# PDF Annotate Library: Draw, edit PDF annotation, markups in C#.
Provide users with examples for adding text box to PDF and edit font size and color in text box field in C#.NET program. C#.NET: Draw Markups on PDF File.
best way to compress pdf files; change font size in fillable pdf form
Absolutepositioningoftext
Inthissection,we’lldiscussproblemsthatcanoccurwhenaddingtextatabsolutepositions.
HowtowriteaZapfdingbatscharacterataspecific
locationonapage?
IwanttoputacheckmarkusingZapfdingbatsonaspecificlocationinmyPDFdocument.
WhatIachievedsofaristhis:Icanshowthecheckmarkbutit’sonthesideofthedocument
andnotonthespecificX,YcoordinatethatIwantittobe.
PostedonStackOverflowonMay4,2013³⁵byδοῦλοςἸησοῦςΧριστός³⁶
Let’sstartwitha
Font
objectthatknowshowtodrawaZapfdingbatscharacter:
Font font = new Font(Font.FontFamily.ZAPFDINGBATS, 12);
Onceyouhavea
Font
object,youcancreatea
Phrase
:
Phrase phrase = new Phrase(zapfstring, font);
Where
zapfstring
isa
string
containinganyZapfdingbatscharacteryouwant.
To add this Phrase at t anabsolute e position, you u canuse e the
ShowTextAligned()
method and
PdfWriter
’sdirectcontent:
PdfContentByte canvas = writer.DirectContent;
ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, phrase, 2005000);
Where
200
and
500
areanXandYcoordinateand
0
isanangleexpressedindegrees.Insteadof
ALIGN_CENTER
,youcanalsochoose
ALIGN_RIGHT
or
ALIGN_LEFT
.
³⁵
http://stackoverflow.com/questions/16370428/how-to-write-in-a-specific-location-the-zapfdingbatslist-in-a-pdf-document-using
³⁶
http://stackoverflow.com/users/2170392/
C# PDF Convert to Jpeg SDK: Convert PDF to JPEG images in C#.net
Using this C#.NET PDF to JPEG conversion library component toolkit, C# developers can easily and quickly convert a large-size multi-page PDF document to a
change font size in pdf text box; pdf compression settings
C# Convert: PDF to Word: How to Convert Adobe PDF to Microsoft
Support fast Word and PDF conversion with original document page size remained. Microsoft Office Word 2003 (.doc) and 2007 (.docx) versions are available.
change font size pdf text box; pdf change font size
Absolutepositioningoftext
20
Howtoreduceredundantcodewhenaddingcontent
atabsolutepositions?
Thisispartofavb.netappthatusestheitextsharplibrary:
Dim cb As s PdfContentByte writer.DirectContent
cb.BeginText()
cb.SetFontAndSize(Californian, 36)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
"CERTIFICATE OF F COMPLETION"396397.910)
cb.SetFontAndSize(Bold_Times, 22)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, name, 396322.350)
cb.SetFontAndSize(Bold_Times, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
_hours " Hours"297.05285.440)
cb.SetFontAndSize(Bold_Times, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
_dates, 494.95285.440)
cb.SetFontAndSize(Bold_Times, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, _class1, 396250.340)
If Not String.IsNullOrWhiteSpace(_class2) ) Then
cb.SetFontAndSize(Bold_Times, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, _class2, 396235.340)
End If
cb.SetFontAndSize(Copper, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
_conf_num _prefix " Annual Conference e " _dates, 396193.890)
cb.SetFontAndSize(Bold_Times, 13)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Some Name"396175.690)
cb.SetFontAndSize(Bold_Times, 10)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
"Some Company Manager"396162.640)
cb.EndText()
Plentyoflinesinthissnippetlookawfullyredundantandinmyopinion,thiscan’tbethe
cleanestwaytodothings.Unfortunately,Ican’tfigureouthowtocreateaseparatefunction
towhichIcansimplypasssomeparameters,suchas
string
,
x_Cord
,
y_Cord
,
tilt
.Sucha
functionwouldthenperformthenecessaryoperationsonthe
PdfContentByte
.
PostedonStackOverflowonNov23,2012³⁷bySkindeep2366³⁸
³⁷
http://stackoverflow.com/questions/13523099/separating-redundant-code-from-pdf-generator-function
³⁸
http://stackoverflow.com/users/969487/skindeep2366
Absolutepositioningoftext
21
You’readdingcontent“thehardway”.IfIwereyou,I’dwriteaseparateclass/factory/methodthat
createseithera
Phrase
ora
Paragraph
withthecontent.Forinstance:
protected Font f1 new Font(Californian, 36);
protected Font f2 new Font(Bold_times, 16);
public Phrase getCustomPhrase(String nameint hours, ...) {
Phrase p new Phrase();
p.add(new Chunk("..."f1));
p.add(new Chunk(namef2);
...
return p;
}
ThenIwoulduseColumnTexttoaddthe
Phrase
or
Paragraph
atthecorrectposition.Inthecase
ofa
Phrase
,I’dusethe
ColumnText.showTextAligned()
method.Inthecaseof
Paragraph
,I’duse
thisconstruction:
ColumnText ct new ColumnText(writer.DirectContent);
ct.setSimpleColumn(rectangle);
ct.addElement(getCustomParagraph(namehours, ...));
ct.go();
Theformer(usinga
Phrase
)isbestifyouonlyneedtowriteonelinethatdoesn’tneedtobewrapped,
orientedinanydirectionyouwant.
Thelatter(usinga
Paragraph
incompositemode)isbestifyouwanttoaddtextinsideaspecific
rectangle(definedbythecoordinatesofthelower-leftcornerandtheupper-rightcorner).
Theapproachyou’vetakenworks,but…itinvolveswritingPDFsyntaxalmost“manually”.That’s
moredifficultandthereforemoreerror-prone.Youalreadydiscoveredthat,otherwiseyouwouldn’t
askthequestion;-)
Absolutepositioningoftext
22
Whydoes
ColumnText
ignorethehorizontal
alignment?
I’mtryingtogetsomerowsoftextontheleftsideandsomeontherightside.Forsome
reasoniTextseemstoignorethealignmententirely.Forexample:
// create e 200x100 column
ct = new ColumnText(writer.DirectContent);
ct.SetSimpleColumn(00200100);
ct.AddElement(new Paragraph("entry1"));
ct.AddElement(new Paragraph("entry2"));
ct.AddElement(new Paragraph("entry3"));
ret = = ct.Go();
ct.SetSimpleColumn(00200100);
ct.Alignment = = Element.ALIGN_RIGHT;
ct.AddElement(new Paragraph("entry4"));
ct.AddElement(new Paragraph("entry5"));
ct.AddElement(new Paragraph("entry6"));
ret = = ct.Go();
I’vesetthealignmentofthe2ndcolumnto
Element.ALIGN_RIGHT
butthetextappears
printedontopofcolumnone,renderingunreadabletext.Likethealignmentwasstillset
toleft
PostedonStackOverflowonAug9,2013³⁹byChuck⁴⁰
Tounderstandwhathappens,you shouldlearnabouttheconcepts“textmode” and“composite
mode”.
Ifyouworkintextmode,youcandefinethealignmentatthelevelofthe
ColumnText
object.In
otherwords
ct.Alignment = Element.ALIGN_RIGHT;
willworkintextmode.
Ifyouworkincompositemode,thealignmentatthecolumnlevelwillbeignoredinfavorofthe
alignmentoftheelementsaddedtothecolumn.Inyourcase,iTextwillignorethe
ALIGN_RIGHT
in
favorofthealignmentofthe
Paragraph
objectsaddedtothecolumn.Lookingatyourcode,Isee
thatyoudidn’tdefineanalignmentfortheparagraphs,sothedefaultalignment
ALIGN_LEFT
isused.
Howdoyouknowifyou’reworkingintextmodeorincompositemode?
Bydefault,
ColumnText
usestextmodebutitswitchestocompositemode(removingallpreviously
addedtext)themomentyouinvokethe
AddElement()
method.
³⁹
http://stackoverflow.com/questions/18142623/itext-columntext-ignores-alignment
⁴⁰
http://stackoverflow.com/users/1280511/chuck
Absolutepositioningoftext
23
Theconceptstextmodeandcompositemodealsoappliesto
PdfPCell
.
Tables
The
PdfPTable
classisoneofthemostpopularclassesinthecontextofdocumentcreation.Let’s
takealookatsomequestionsandanswersregardingtables,rowsandcells.
Howtoright-aligntextina
PdfPCell
?
IhaveaC#applicationthatgeneratesaPDFinvoice.Inthisinvoiceisatableofitemsand
prices.Thisisgeneratedusinga
PdfPTable
and
PdfPCell
s.
Iwanttobeabletoright-alignthepricecolumnbutIcannotseemtobeableto-thetext
alwayscomesoutleft-alignedinthecell.
Hereismycodeforcreatingthetable:
PdfPTable table e = new PdfPTable(2);
table.TotalWidth = = invoice.PageSize.Width;
float[] widths = = { { invoice.PageSize.Width h - 70f70f };
table.SetWidths(widths);
table.AddCell(new Phrase("Item Name", tableHeadFont));
table.AddCell(new Phrase("Price", tableHeadFont));
SqlCommand cmdItems = new SqlCommand("SELECT...", con);
using (SqlDataReader rdrItems = = cmdItems.ExecuteReader())
{
while (rdrItems.Read())
{
table.AddCell(new Phrase(rdrItems["itemName"].ToString(), tableFont));
double price = = Convert.ToDouble(rdrItems["price"]);
PdfPCell pcell l = new PdfPCell();
pcell.HorizontalAlignment = = PdfPCell.ALIGN_RIGHT;
pcell.AddElement(new Phrase(price.ToString("0.00"), tableFont));
table.AddCell(pcell);
}
}
Cananyonehelp?
PostedonStackOverflowonNov28,2012⁴¹bycolincameron⁴²
⁴¹
http://stackoverflow.com/questions/13607970/right-aligning-text-in-pdfpcell
⁴²
http://stackoverflow.com/users/970789/colincameron
Documents you may be interested
Documents you may be interested