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
Converting pdf to tiff file - software SDK project:C# PDF Convert to Tiff SDK: Convert PDF to tiff images in C#.net, ASP.NET MVC, Ajax, WinForms, WPF
Online C# Tutorial for How to Convert PDF File to Tiff Image File
www.rasteredge.com
Converting pdf to tiff file - software SDK project:VB.NET PDF Convert to Tiff SDK: Convert PDF to tiff images in vb.net, ASP.NET MVC, Ajax, WinForms, WPF
Free VB.NET Guide to Render and Convert PDF Document to TIFF
www.rasteredge.com
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
software SDK project:Online Convert PDF file to Tiff. Best free online PDF Tif
XDoc.PDF) is a multifunctional PDF document converting tool, which can control, C# developers can render and convert PDF document to TIFF image file
www.rasteredge.com
software SDK project:C# TIFF: C#.NET Code to Convert TIFF Image File
controls. Visual C#.NET demo code for converting PDF document to Tiff image file is offered. How to Convert Jpeg Images to Tiff.
www.rasteredge.com
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
software SDK project:Online Convert Excel to PDF file. Best free online export xlsx
Your Excel file is converted to look just the same as it does in your office software. Creating a PDF from xlsx/xls has never been so easy! Easy converting!
www.rasteredge.com
software SDK project:C# PDF Convert to Word SDK: Convert PDF to Word library in C#.net
is a C# programming example for converting PDF to Word inputFilePath = Program.RootPath + "\\" 1.pdf"; PDFDocument doc DocumentType.DOCX DocumentType.TIFF.
www.rasteredge.com
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.
software SDK project:C# PDF Converter Library SDK to convert PDF to other file formats
This PDF document converting library component offers reliable C# image or document, or from PDF document to other file formats, like multi-page TIFF file.
www.rasteredge.com
software SDK project:VB.NET PDF Converter Library SDK to convert PDF to other file
a series of demo code directly for converting MicroSoft Office Word, Excel and PowerPoint document to PDF file in VB.NET application. Conversion of TIFF to PDF.
www.rasteredge.com
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/
software SDK project:VB.NET TIFF: TIFF Converter Control SDK; Convert TIFF to Image &
to PDF conversion without using external PDF document processing VB.NE TIFF to JPEG Converting Plugin, VB.NE conversion SDK is able to convert TIFF file to JPEG
www.rasteredge.com
software SDK project:C# PDF Convert to HTML SDK: Convert PDF to html files in C#.net
Besides, this PDF converting library also makes PDF document visible and searchable on the Internet by converting PDF document file into HTML webpage.
www.rasteredge.com
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