The Best Itext Questions On StackOverflow
The Best Itext Questions On StackOverflow
iText Software
This book is for sale at http://leanpub.com/itext_so
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Why StackOverflow? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
How to use this book? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
How to generate and design PDFs with iText or iTextSharp? . . . . . . . . . . . . . . . . 6
How to create a complex PDF document? . . . . . . . . . . . . . . . . . . . . . . . . . . 8
How to set the page size to Envelope size with Landscape orientation? . . . . . . . . . . 9
Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
How to use the font Verdana in PdfStamper? . . . . . . . . . . . . . . . . . . . . . . . . 11
Why doesnt FontFactory.GetFont() work for all fonts? . . . . . . . . . . . . . . . . . . . 12
Why arent my fonts getting registered? . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Why arent images added sequentially? . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
How to get the image DPI in PDF? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
How to preserve high resolution images in PDF? . . . . . . . . . . . . . . . . . . . . . . 17
Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
How to right-align text in a PdfPCell? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
How to use multiple fonts in a single cell? . . . . . . . . . . . . . . . . . . . . . . . . . . 25
How to introduce a rowspan? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
How to change width of single column of table? . . . . . . . . . . . . . . . . . . . . . . . 28
What is the PdfPTable.DefaultCell property used for? . . . . . . . . . . . . . . . . . . 29
CONTENTS
Table events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
How to use a dotted line as a cell border? . . . . . . . . . . . . . . . . . . . . . . . . . . 32
How to create a table with rounded corners? . . . . . . . . . . . . . . . . . . . . . . . . . 33
Page events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
How to add a rectangle to every page of a document? . . . . . . . . . . . . . . . . . . . . 35
How can I add an image to all pages of my PDF? . . . . . . . . . . . . . . . . . . . . . . 36
How to set a fixed background image for all my pages? . . . . . . . . . . . . . . . . . . . 38
Interactive forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
How to fill out a pdf file programmatically? (AcroForm technology) . . . . . . . . . . . . 54
How to fill out a pdf file programmatically? (Dynamic XFA) . . . . . . . . . . . . . . . . 55
How to fill XFA form using iText without breaking usage rights? . . . . . . . . . . . . . 57
Legal questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
What is the difference between Lowagie and iText? . . . . . . . . . . . . . . . . . . . . . 70
Can iText 2.1.7 or earlier be used commercially? . . . . . . . . . . . . . . . . . . . . . . . 71
To be continued . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
introduction
A couple of years ago, I decided to self-publish new books about iText, as opposed to working with
a publisher as I did before for the iText in Action books. This led to a book about digital signatures
that is available for download on the iText site, and a book called The ABC of PDF published on
LeanPub. The goal of The ABC of PDF was to start with a book that looks at PDF at the lowest
level, examining the syntax of a PDF file and a PDF page, and then to continue writing a series of
books that explain how to use iText on a higher level, answering questions such as:
However, in spite of the fact that more than 15,000 people downloaded The ABC of PDF, it turned
out that people really wanted me to write a different kind of book. Ive received many comments
through LeanPub from people who were disappointed that the ABC-book didnt explain how to
use iText. They expected a book with more practical examples, instead of examples that helps them
understand the PDF specification. Some people even used the feedback form to ask me technical
questions. Unfortunately, I was unable to answer these questions, because the people posting them
didnt realize that I received these questions anonymously. Even if I knew the answers, I didnt know
who or where to send them to.
All of this faced me with a dilemma: do I stop writing The ABC of PDF and start writing one of
the other books that were planned? If so, which part of iText is most important to iText users? The
plan for the ABC was to write a book of about 150 pages, but much to my surprise, I was only half
way when I finished writing page 150. Didnt I have other writing priorities?
Then suddenly I had an idea: why not write a book with questions and answers? Why not create a
book entitled The Best iText Questions on StackOverflow?
Why StackOverflow?
I joined StackOverflow on August 24, 2012. Up until then, I had been answering many questions
on the iText mailing-list. This mailing-list hosted on SourceForge used to be an important source
http://itextpdf.com/book/digitalsignatures
https://leanpub.com/itext_pdfabc/
introduction 2
of inspiration. I composed two iText in Action books for Manning Publications, simply by
reorganizing the many answers and examples written in answer to question into a real book.
However, at some point I got tired of the mailing-list. When I referred to an example in one of my
books, people would accuse me for trying to trick them into buying my book. The mailing-list was
also used by people spreading false allegations, such as iText is no longer open source. One could
explain that these people were wrong, for instance by providing a link to the source code, but there
was no way to award people for providing good answers and to discourage people from posting bad
answers. It felt as if the ungrateful were winning the debate.
Then I discovered StackOverflow where people build a reputation getting reputation points when
they ask good questions and provide good answers, losing points when they post bad questions or
bad answers. I took me 2 years and almost 2 months to become a Trusted User, a status that requires
20,000 reputation points. Since I registered on StackOverflow, I have posted answers to more than
1,000 questions. Looking back at some of the more elaborate answers, I thought it would be a good
idea to bundle those questions and answers that are of book quality.
Acknowledgments
I have selected nothing but questions I have answered myself, but it goes without saying that I
cant answer every single question about iText personally. For instance: when I am travelling, I am
off-line for many hours. As unanswered questions about iText give me stress, I am always happy to
see that other people jump in when Im away from my keyboard.
I want to thank Alexis Pigeon for editing many iText questions in order to clarify what is asked. I
rely on Chris Haas for answering questions that require the C# skills that I am missing. I notice that
I skip questions about digital signatures, because I know that Michael Klinks answer will be much
more accurate than mine.
I also want to thank the many people who accepted one of my answers, because thats how one
builds a reputation on StackOverflow. I know that some people down-vote me because my style can
be harsh at times. Somebody once tweeted: Spent a lot of time today on StackOverflow and realized
that Bruno Lowagie is kind of a dick. Ah well, I hope that the balance is positive.
Please understand that it is hard for me when people talk about Lowagie as if its a thing, not a
person. Sometimes people start by saying that they are using Lowagie software and then they start
cursing at me if I give them an answer they dont like, for instance: please use a more recent version
instead of a version that has been declared End of Life more than five years ago. So it goes Not
every developer realizes that Im on their side and that their job is much easier if only their boss
would purchase a commercial iText license so that they can use the most recent version.
https://github.com/itext/itextpdf
http://stackoverflow.com
http://stackoverflow.com/users/1622493/bruno-lowagie
introduction 3
this is a question
At times, I throw in a question of myself to clarify things. These questions are marked with an
information icon:
Sometimes, it was important to add a comment that was made on StackOverflow. I have marked
comments like this:
This is a comment
I hope you enjoy this book, and that it helps you solving all your iText problems. If not, please post
a question on StackOverflow and, who knows, maybe your question will be added to this book.
http://stackoverflow.com
Questions about PDF in general
When posting a question on StackOverflow, people can tag their posts as iText or iTextSharp
questions. This allows me to quickly find those questions by performing a simple query for posts
tagged as itext* questions. This includes the tags itext, itextsharp, itextpdf and itextg.
However, not all questions tagged this way are iText-related. Sometimes, people using iText have
questions that are about PDF in general.
Actually I want to know the difference or comparison between different PDF creation /
generation techniques. For Example: iText, Adobe LC, Jasper Reports, etc.
I would like to know the exact advantage / disadvantage of using each of them.
Currently I am using Adobe LC ES2 and would like to also know the advantage of using
Adobe software over other techniques.
Posted on StackOverflow on Mar 19, 2013 by user2185226
Thats a very broad question and I see that it already has a vote to close the question for this reason.
Let me give the nutshell version of the answer. I could easily write a book on this topic (and maybe
one day I will).
iText is a library that can be used by developers to enhance their web and other applications
with PDF functionality: create PDF, fill out PDF forms, examine and manipulate existing
PDFs.
JasperReports is a Business Intelligence / Reporting tool that uses an old iText version to create
reports. It is distributed by JasperSoft / TIBCO. JasperReports only uses a limited part of the
complete iText functionality. Creating PDF is just one of many features of JasperReports, and
JasperSoft uses iText to implement that feature.
http://stackoverflow.com/questions/tagged/itext*
http://stackoverflow.com/questions/15492738/difference-between-itext-and-adobe-lc
http://stackoverflow.com/users/2185226/user2185226
Questions about PDF in general 5
Adobe LC is a suite of modules, some of which can only be provided by Adobe. For instance:
no third party can Reader enable PDF documents because Reader enabling requires a private
key that is proprietary to Adobe. However: iText competes with Adobe LC in some areas, for
instance digital signing (read the white paper from the Office of Legislative Counsel on digital
signatures) and form filling (iText has an add-on called XFA Worker that can convert your
dynamic XFA forms into static PDF, e.g. PDF/A)
Does a PDF file have styles, headers and footers information as is the case with docx files
that have separate xml files with extra information?
Posted on StackOverflow on Jan 21, 2014 by Prakhar
Regular PDFs dont have styles, but different fonts (for instance Helvetica is one font, Helvetica-Bold
is another font of the same family). They dont have headers and footers, just like they dont have
paragraphs, section titles, table rows or table cells. Everything you see in a PDF page, is just a bunch
of glyphs, paths and shapes drawn on a canvas.
However: if your PDF is a Tagged PDF, the PDF contains something that is known as the
StructTreeRoot. This means that, apart from the presentation of the content, you also have a tree
structure that stores the semantics of the content. This structure contains references to the content
on the different pages, allowing you (for instance) to find out which lines belong together in a
paragraph, which parts of the page are artifacts (such as a repeating page header or a footer with
a page number), which content is organized as a table, etc
Tagged PDF is a requirement for PDF/A Level A and PDF/UA documents. A majority of the PDF
files you can find in the wild arent tagged (or arent tagged properly).
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
Getting started
The most popular iText example is the Hello World example, explaining the five steps to create a
PDF from scratch using iText:
// step 1
Document document = new Document();
// step 2
PdfWriter.getInstance(document, new FileOutputStream(filename));
// step 3
document.open();
// step 4
document.add(new Paragraph("Hello World!"));
// step 5
document.close();
Obviously, iText is capable of doing much more than creating a PDF that shows the words Hello
World, but lets take a look at some basic questions to get started.
The question is very broad, so I can only give you a very broad answer.
Option 1: you create your layout by using iTexts high-level objects. There are countless applications
out there that are using PdfPTable to generate complex reports. For instance: the time tables for a
German Railway company are created from scratch through code; the invoices for a Belgian Telco
company are created this way, The advantage of this approach is that you can really fine-tune the
layout. The disadvantage is that you need to change source code as soon as you want to change the
layout.
Option 2: you create your layout by creating an AcroForm template. Every field in this template
has a name and is visualized at exact positions (defined by its coordinates) on specific pages. The
code to fill out such a form consists of only a handful of lines. Whenever you need to change the
layout, you alter the AcroForm template. You do not need to change your code. The disadvantage is
that AcroForms are very static. Compare it to a paper form: you cant insert a row in a paper form
either.
Option 3: you create your data in XHTML format and your styles in CSS. A Belgian printing
company responsible for creating invoices for its customers is streaming data into very simple HTML
files involving a sequence of tables that never span more than a handful of pages. These files are
then fed to iTexts XML worker along with a CSS that is different for each of its customers. The
advantage of this approach is that no extra programming is needed when a new customer joins. Its
just a matter of creating a new CSS. The disadvantage is that you are limited by the HTML format.
Elementary logic also tells you that you shouldnt expect URL2PDF: have you ever tried printing
a website? Well, the bad quality of that print should give you an indication of the problems youll
encounter when trying to convert HTML to PDF. If you anticipate them, you can get good results.
If you dont: its a poor craftsman who blames his tools
Option 4: define your template using the XML Forms Architecture (XFA). Such templates are usually
created using Adobe LiveCycle Designer. An XSD is fed into LC Designer and the result is an empty
form where the PDF format acts as a container for an XML stream. You can then use iText to inject
your custom XML containing data that conforms with the XSD into the PDF and you can use XFA
Worker to flatten such a form. XFA Worker is only available as a closed source product (givers need
to set limits because takers rarely do).
Option 5: right now XML Worker is used to convert XHTML+CSS and XFA to PDF (ordinary PDF,
PDF/A, PDF/UA). You could use the generic XML Worker engine to support your own XML format.
The advantage would be a very powerful engine that you can tune to meet your exact needs. The
disadvantage is that this involves a serious up-front development investment.
Option 6: use a third party tool to define the template and a third party server that uses iText under
the hood to create PDFs based on the template. An example of such a third party tool is Scriptura
developed by Inventive Designers. There are other tools, but Inventive Designers is a customer of
iText and we know that they are using iText correctly whereas we dont have this guarantee from
other vendors.
Getting started 8
What is the best way out of these, or is there any other way which is easier and convenient?
Posted on StackOverflow on Jan 4, 2013 by Ankit
When you talk about Certificates, I think of standard sheets that look identical for every receiver of
the certificate, except for:
If this is the case, I would use any tool that allows you to create a fancy certificate (Acrobat,
Open Office, Adobe InDesign,) and create a static form (sometimes referred to as an AcroForm)
containing three fields: name, course, date.
I would then use iText to fill in the fields like this:
http://stackoverflow.com/questions/14151335/creating-complex-pdf-using-java
http://stackoverflow.com/users/810176/ankit
Getting started 9
Creating such a certificate from code is the hard way; creating such a certificate from XML is a
pain (because XML isnt well-suited for defining a layout), creating a certificate from (HTML +
CSS) is possible with iTexts XML Worker, but all of these solutions have the disadvantage that its
hard work to position every item correctly, to make sure everything fits on the same page, etc
Its much easier to maintain a template with fixed fields. This way, you only have to code once. If
for some reason you want to move the fields to another place, you only have to change the template,
you dont have to worry about messing around in code, XML, HTML or CSS.
Please go to the section about interactive forms to learn more about this technology.
I googled but I couldnt find the Envelope size. How do I set the page size as Envelope with
Landscape orientation?
Posted on StackOverflow on Sep 17, 2014 by King_Fisher
If you want to create a document in envelope format, you shouldnt create an A4 page, instead you
should do this:
Because:
If you want a different envelope type, you have to do the Math with the dimensions of that envelope
format.
Fonts
Simple fonts, composite fonts, embedded fonts, encoding, ttf files, special characters, right to left
writing systems, This chapter is where all your questions about fonts belong.
I want to use Verdana as a font while stamping a PDF file with iText PDF. The original file
uses Verdana, which isnt an option in the class Basefont.
Here is the function to create my font right now:
def standardStampFont() {
return BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false)
}
Id like to change that to the Verdana Font, but simply exchanging the Part
BaseFont.HELVETICA with "Verdana" doesnt work.
iText can support the Standard Type 1 fonts, because iText ships with AFM file (Adobe Font Metrics
files). iText has no idea about the font metrics of other fonts (Verdana isnt a Standard Type 1 font).
You need to provide the path to the Verdana font file.
Note that I change false to BaseFont.EMBEDDED because the same problem you have on your side,
will also occur on the side of the person who looks at your file: his PDF viewer can render Standard
Type 1 fonts, but may not be able to render other fonts such as Verdana.
Caveat: The hard coded path "c:/windows/fonts/verdana.ttf" works for me on my local machine
because the font file can be found using that path on my local machine. This code wont work on
the server where I host the iText site, though (which is a Linux server that doesnt even have a
c:/windows/fonts directory). I am using this hard coded path by way of example. You should make
sure that the font is present and available when you deploy your application.
http://stackoverflow.com/questions/26404418/how-to-use-verdana-font-in-stamper-itext-pdf
http://stackoverflow.com/users/1817618/alain-sarti
Fonts 12
If I say:
it doesnt work. When I check the state of the variable georgia, it has its Family property
set to the value UNDEFINED and its FamilyName property set to Unknown.
It only works if I actually load and register the font file and then get it like so:
FontFactory.Register("C:\\Windows\\Fonts\\georgia.ttf", "Georgia");
var georgia = FontFactory.GetFont("Georgia", 20f);
Why is that?
Posted on StackOverflow on Jun 3, 2014 by Water Cooler v2
iText is written in Java, which means its platform-independent. It ships with 14 AFM files containing
the metrics of the 14 Standard Type 1 fonts (4 flavors of Helvetica, 4 flavors of Times Roman, 4 flavors
of Courier, Symbol and ZapfDingbats).
As soon as you need other fonts, you need to register the font files by passing the path to the
font directory or the path to an actual font. The font directory on Linux is different from the
font directory on Windows (there is no C:/Windows/fonts on Linux). Theres also a method
registerDirectories() that looks at the operating system youre currently using and that registers
all the usual suspects (iText guesses the font path based on the OS). This method is expensive: it
registers all fonts it finds and this costs time and memory.
Once fonts are registered, you can ask the FontFactory for the registered names. This is shown in
the FontFactoryExample. Youll notice the difference between the getRegisteredFonts() method
and the getRegisteredFamilies() method.
Additional note: the original question is about iTextSharp, written in C#. iTextSharp is ported from
Java and tries to stay as close as possible to the original version written in Java. Nevertheless, the
same rationale applies: starting up an application would be much slower if iTextSharp would have
to scan the fonts directory. In most applications, you only need a handful of fonts; registering all
fonts available in the Windows fonts directory would be overkill.
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
FontFactory.RegisterDirectories();
foreach (string fontname in FontFactory.RegisteredFonts) {
Log.Info("**** Found registered font: " + fontname);
}
When I run it (using Mono on a CentOS box), the log shows only the core PostScript fonts:
zapfdingbats
times-roman
times-italic
helvetica-boldoblique
courier-boldoblique
helvetica-bold
helvetica
courier-oblique
helvetica-oblique
courier-bold
times-bolditalic
courier
times-bold
symbol
But I have 156 TTF files under my /usr/share/fonts directory tree (which is one of the
directories mentioned in the code for the RegisterDirectories function). Why arent these
being registered?
Posted on StackOverflow on Nov 29, 2013 by dan04
http://stackoverflow.com/questions/13635212/why-arent-my-fonts-getting-registered
http://stackoverflow.com/users/287586/dan04
Fonts 14
Java is platform independent, so we have to look for the usual suspects. C# is Windows specific,
so we can depend on the environment to tell us where to find fonts. Your question tells us that Mono
doesnt support this, so youll have to use FontFactory.RegisterDirectory("/usr/share/fonts");
Images
In this section, youll find the questions related to raster images, such as JPG, PNG, GIF, and so on.
I am working on a pdf report that contains topics and images (charts). The document is
formatted this way:
NR. TOPIC TITLE FOR TOPIC 1
CHART IMAGE for topic 1 (from bytearray)
NR. TOPIC TITLE FOR TOPIC 2
CHART IMAGE for topic 2
Lets assume that I add this information in a loop, and that the loop runs 10 times. I expect
10 topic titles all directly followed by the image.
However, if the page end is reached and a new image should be added, I notice that the
image is moved to the next page and the next topic title is printed on the previous page.
So on paper we have:
page 1: topic 1
image topic 1
topic 2
image topic 2
topic 3
topic 4
page 2: image topic 3
image topic 4
topic 5
image topic 5
So the order of the elements on paper, is NOT the same as the order that I used to put the
element in the document via the document.add() method. This is really strange. Anyone
has any idea?
Posted on StackOverflow on Mar 26, 2014 by wim boone
http://stackoverflow.com/questions/22664126/image-not-sequentialy-added-in-pdf-document-itextsharp-wrong-order-of-elements
http://stackoverflow.com/users/3149519/wim-boone
Images 16
If you have a PdfWriter instance (for instance writer), you need to force iText to use strict image
sequence like this:
writer.setStrictImageSequence(true);
Otherwise, iText will postpone adding images until theres sufficient space on the page to add the
image.
Im trying to get information about scanned images that are saved into PDF files through
iText (using Java). I can get width and height (either through Matrix, or through Buffered-
Image). The idea was to use the answer here to calculate the DPI, but I am a bit lost. Are
these values (width and height) in pixels or points? Is there any other way to achieve this?
There are a lot of answers on how to scale and save an image to a PDF file, but I didnt find
any on how to read the width/height/scale of an image and be confident about the result.
Posted on StackOverflow on Aug 28, 2014 by Finik
Lets split this problem into two separate problems. To calculate the DPI, you need two sets of values:
a number of pixels and a distance in inch.
1. Number of pixels: you obtain the image and the image consists of pixels. You can retrieve the
width and height of the image in pixels from the image. Lets say these values are wPx and
wPx.
2. Distance in inch: you obtain the matrix which gives you values expressed in points. As 72
points equal 1 inch, you need to divide these values by 72. Lets say these values are wInch
and hInch.
Now you can calculate the DPI in the x direction like this: wPx / wInch and the DPI in the y direction
like this: hPx / hInch.
http://stackoverflow.com/questions/25550000/getting-image-dpi-in-pdf-files-using-itext
http://stackoverflow.com/users/1300529/finik
Images 17
Im trying to put high quality images into PDF (one per page). But if I set page size to a4, I
have to resize my pictures, because theyre too large. Then they loose their quality. Is there
any way to put big image to a4 page without loosing quality?
Im using iTextSharp library, firstly Im creating the document
document.Add(iTextSharp.text.Image.GetInstance(toSaveImage, System.Drawing.Imagi\
ng.ImageFormat.Tiff));
document.Close();
a PDF document as such doesnt have a resolution. There is no such thing as DPI in PDF. The
resolution only comes into play when a PDF is rendered (to the screen, to paper,) and thats
why there may be a DPI in a PDF viewer (but thats something completely different).
when you scale an Image object in iTextSharp, you dont lose any information: the number
of pixels remains the same. Whereas PDF doesnt have a resolution, the images inside a PDF
do. When you the image scale down (that is: you put the same number of pixels on a smaller
canvas), the resolution increases; when you scale up, the resolution decreases.
http://stackoverflow.com/questions/16970106/c-sharp-high-resolution-images-in-pdf
http://stackoverflow.com/users/2411220/com-piler
Images 18
Image img =
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(0, 0);
document.Add(img);
I created the Document based on the scaled dimensions of the Image. Dont let the method names
mislead you: ScaledWidth and ScaledHeight are the safest methods to use when getting the
dimensions of an Image. Not only do they include any scaling operations, you may have done on
the image, the also take into account the space needed for the image after rotating it.
Observe that Ive set the absolute position to the lower-left corner. Thats safer than setting the page
margins to 0.
If you dont want to change the page size, then you have to use the ScaleToFit() method:
Image img =
iTextSharp.text.Image.GetInstance(toSaveImage,
System.Drawing.Imaging.ImageFormat.Tiff);
img.ScaleToFit(PageSize.A4);
Scale to fit will keep the aspect ratio of the image. If the aspect ratio of the image is different from
the aspect ratio of the page, the page will have a margin.
Absolute positioning of text
In this section, well discuss problems that can occur when adding text at absolute positions.
I want to put a check mark using Zapfdingbats on a specific location in my PDF document.
What I achieved so far is this: I can show the check mark but its on the side of the document
and not on the specific X, Y coordinate that I want it to be.
Posted on StackOverflow on May 4, 2013 by
Lets start with a Font object that knows how to draw a Zapfdingbats character:
Where 200 and 500 are an X and Y coordinate and 0 is an angle expressed in degrees. Instead of
ALIGN_CENTER, you can also choose 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/
Absolute positioning of text 20
Plenty of lines in this snippet look awfully redundant and in my opinion, this cant be the
cleanest way to do things. Unfortunately, I cant figure out how to create a separate function
to which I can simply pass some parameters, such as string, x_Cord, y_Cord, tilt. Such a
function would then perform the necessary operations on the PdfContentByte.
Posted on StackOverflow on Nov 23, 2012 by Skindeep2366
http://stackoverflow.com/questions/13523099/separating-redundant-code-from-pdf-generator-function
http://stackoverflow.com/users/969487/skindeep2366
Absolute positioning of text 21
Youre adding content the hard way. If I were you, Id write a separate class/factory/method that
creates either a Phrase or a Paragraph with the content. For instance:
Then I would use ColumnText to add the Phrase or Paragraph at the correct position. In the case
of a Phrase, Id use the ColumnText.showTextAligned() method. In the case of Paragraph, Id use
this construction:
The former (using a Phrase) is best if you only need to write one line that doesnt need to be wrapped,
oriented in any direction you want.
The latter (using a Paragraph in composite mode) is best if you want to add text inside a specific
rectangle (defined by the coordinates of the lower-left corner and the upper-right corner).
The approach youve taken works, but it involves writing PDF syntax almost manually. Thats
more difficult and therefore more error-prone. You already discovered that, otherwise you wouldnt
ask the question ;-)
Absolute positioning of text 22
Im trying to get some rows of text on the left side and some on the right side. For some
reason iText seems to ignore the alignment entirely. For example:
Ive set the alignment of the 2nd column to Element.ALIGN_RIGHT but the text appears
printed on top of column one, rendering unreadable text. Like the alignment was still set
to left
Posted on StackOverflow on Aug 9, 2013 by Chuck
To understand what happens, you should learn about the concepts text mode and composite
mode.
If you work in text mode, you can define the alignment at the level of the ColumnText object. In
other words ct.Alignment = Element.ALIGN_RIGHT; will work in text mode.
If you work in composite mode, the alignment at the column level will be ignored in favor of the
alignment of the elements added to the column. In your case, iText will ignore the ALIGN_RIGHT in
favor of the alignment of the Paragraph objects added to the column. Looking at your code, I see
that you didnt define an alignment for the paragraphs, so the default alignment ALIGN_LEFT is used.
How do you know if youre working in text mode or in composite mode?
By default, ColumnText uses text mode but it switches to composite mode (removing all previously
added text) the moment you invoke the AddElement() method.
http://stackoverflow.com/questions/18142623/itext-columntext-ignores-alignment
http://stackoverflow.com/users/1280511/chuck
Absolute positioning of text 23
The concepts text mode and composite mode also applies to PdfPCell.
Tables
The PdfPTable class is one of the most popular classes in the context of document creation. Lets
take a look at some questions and answers regarding tables, rows and cells.
I have a C# application that generates a PDF invoice. In this invoice is a table of items and
prices. This is generated using a PdfPTable and PdfPCells.
I want to be able to right-align the price column but I cannot seem to be able to - the text
always comes out left-aligned in the cell.
Here is my code for creating the table:
Im making a windows form for a friend that delivers packages. So I want to transfer his
current paper form, into a .pdf with the library iTextSharp.
What I need:
I want the table to have a little headline, Company name for example, the text should be
a little smaller than the text input from the windows form. Currently Im using cells and
was wondering if I can use 2 different font sizes within the same cell?
What I have:
What I want:
Youre passing a String and a Font to the AddCell() method. Thats not going to work. You need
the AddCell() method that takes a Phrase object or a PdfPCell object as parameter.
A Phrase is an object that consists of different Chunks, and the different Chunks can have different
font sizes. For instance:
A PdfPCell is an object to which you can add different objects, such as Phrases, Paragraphs,
Images,
I am adding a table to a PDF file. I have 3 rows and 3 columns. I want the first column
to appear only once as a single cell for all the rows. The result should be like where
it says Deloitte in the column of company as shown in the image:
The MyFirstTable example from my book does exactly what you need. Ported to C#, it looks like
this:
You can look at the resulting PDF here. In your case youd need
cell.Rowspan = 6;
hello I have created table in a PDF file using iText. The heading of my table columns are
Medicine Name, Doses, and time: This is what my columns look like:
|Medicin|Doses|time|
| e name| | |
As you can see the word Medicine is split into Medicin and e. I want to avoid this by
changing the width of the first column, but I dont know how to do that.
Posted on StackOverflow on Jun 10, 2014 by DCoder
The ColumnWidths example demonstrates different ways of changing the width of a column. This
is one specific way:
Now the width of the first column is double the size of the second and third column.
http://examples.itextpdf.com/results/part1/chapter04/first_table.pdf
http://stackoverflow.com/questions/24141791/how-to-change-width-of-single-coloumn-of-table-itext-android
http://stackoverflow.com/users/2843856/dcoder
http://itextpdf.com/examples/iia.php?id=76
Tables 29
What is the DefaultCell property used for? The Java documentation for
PdfPTable.getDefaultCell() reads:
Gets the default PdfPCell that will be used as reference for all the addCell
methods except addCell(PdfPCell).
It appears as though the PDfPCell class does have a border property on it but not the
PdfPTable class.
Is there some property on the PdfPTable class to set the borders of all its contained cells in
one statement?
Posted on StackOverflow on Jun 3, 2014 by Water Cooler v2
Borders are defined at the level of the cell, not at the level of the table. Hence: if you want to remove
the borders of the table, you need to remove the borders of each cell.
http://stackoverflow.com/questions/24006618/what-is-the-pdfptable-defaultcell-property-used-for
http://stackoverflow.com/users/303685/water-cooler-v2
http://stackoverflow.com/questions/24006547/draw-a-borderless-table-in-itextsharp
http://stackoverflow.com/users/303685/water-cooler-v2
Tables 30
By default, each cell has a border. You can change this default behavior by changing the border of
each cell. For instance: if you create PdfPCell objects, you use:
cell.setBorder(Rectangle.NO_BORDER);
In case the cells are created internally, you need to change that property at the level of the default
cell.
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
For special borders, for instance borders with rounded corners or a single border for the whole table,
or double borders, you can use either cell events or table events, or a combination of both.
Im new with iText and Im trying to build a table. For some reason
table.getDefaultCell().setBorder(PdfPCell.NO_BORDER) has no effect: my table
has still borders.
Here is my code:
In this case, you define every aspect, every property of the cell on the cell itself.
Concept 2: you allow iText to create the PdfPCell implicitly, for instance:
table.addCell("Adding a String");
table.addCell(new Phrase("Adding a phrase"));
In this case, you can define properties at the level of the default cell. These properties will be used
internally when iText creates a PdfPCell in your place.
Conclusion: either you define the border for all the PdfPCell instances separately, or you let iText
create the PdfPCell instances in which case you can define the border at the level of the default cell.
If you choose the second option, you can adapt your code like this:
This decision was made by design, based on experience: it offers the most flexible to work with cells
and properties.
Table events
We continue with some questions about tables of which the answer involves table or cell events.
I am trying to create a table with cells that have a dotted line for a border. How can I do
this?
Posted on StackOverflow on Nov 21, 2013 with user1913695
Ive made an example that solves your problem: DottedLineCell; The resulting PDF is a document
with two tables: dotted_line_cell.pdf
For the first table, we use a table event:
http://stackoverflow.com/questions/20117321/dotted-line-for-cell-border
http://stackoverflow.com/users/1913695/user1913695
http://itextpdf.com/sandbox/tables/DottedLineCell
http://itextpdf.com/sites/default/files/dotted_line_cell.pdf
Table events 33
}
canvas.stroke();
}
}
This is the most elegant way to draw the cell borders, as it uses only one stroke() operator for all
the lines. Unfortunately, this solution isnt an option if you have tables with rowspans.
The second table uses a cell event:
With a cell event, a border is drawn around every cell. This means youll have multiple stroke()
operators and overlapping lines. However: this solution always works, also when the table has cells
with a rowspan greater than one.
http://stackoverflow.com/questions/23650957/how-to-create-a-rounded-corner-table-using-itext-itextsharp
http://stackoverflow.com/users/1833945/andreanobili
Table events 34
table.DefaultCell.Border = PdfPCell.NO_BORDER;
table.DefaultCell.CellEvent = new RoundedBorder();
You can of course fine-tune the values 1.5, 3 and 4 to get different effects.
Page events
When creating a document from scratch, iText can trigger a series of events for instance when a
new page starts or ends, when a paragraph is added, and so on
Im using iText to create a PDF document. Right now I am trying to get a rectangle on
every single page of the document but Im not sure how to do this. I tried adding this at
the end of my code:
PdfContentByte cb = writer.getDirectContent();
for (int pgCnt = 1; pgCnt <= writer.getPageNumber(); pgCnt++) {
cb.saveState();
cb.setColorStroke(new CMYKColor(1f, 0f, 0f, 0f));
cb.setColorFill(new CMYKColor(1f, 0f, 0f, 0f));
cb.rectangle(20,10,10,820);
cb.fill();
cb.restoreState();
}
but this only adds the rectangle on the last page and it kind of make sense because Im not
using the pgCnt anywhere. How can I specify that I want the rectangle on page number
pgCnt, so I can add the rectangle on every page?
Please take a look at the entries for the keyword Page events on the official iText site. You need to
extend the PdfPageEventHelper class and add your code to the onEndPage() method.
http://stackoverflow.com/questions/16638406/how-can-i-add-rectangle-on-every-page-of-a-document-using-itext
http://stackoverflow.com/users/1883606/carla-stabile
http://itextpdf.com/themes/keyword.php?id=204
http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfPageEventHelper.html
Page events 36
Create an instance of your custom page event class, and declare it to the writer before opening the
document:
writer.setPageEvent(myPageEventInstance);
Now your rectangle will be drawn on every page, on top of the existing content. If you want the
rectangle under the existing content: replace getDirectContent() with getDirectContentUnder().
I have been trying to add an image to all pages using iTextSharp. The image needs
to be OVER all content of every page. I have used the following code below all the
otherdoc.add()
The above code only inserts an image in the last page. Is there any way to insert the image
in the same way in all pages?
Posted on StackOverflow on Feb 20, 2014 by Neville Nazerane
Its normal that the image is only added once; after all: youre adding it only once.
You should create a document in 5 steps and add an event in step 2:
http://stackoverflow.com/questions/21908651/add-an-image-in-all-pages-of-pdf
http://stackoverflow.com/users/991609/neville-nazerane
Page events 37
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, stream);
MyEvent event = new MyEvent();
writer.PageEvent = event;
// step 3
document.Open();
// step 4
// Add whatever content you want to add
// step 5
document.Close();
Image image;
The OnEndPage() in class MyEvent will be triggered every time the PdfWriter has finished a page.
Hence the image will be added on every page.
Caveat: it is important to create the image object outside the OnEndPage() method, otherwise the
image bytes risk being added as many times as there are pages in your PDF (leading to a bloated
PDF).
Page events 38
On Button Click, I generate 4 pages on my PDF, i added this image to provide a background
image
It works only with 1 page, but when I generate a PDF that contains many records and have
several pages, the bg image is only at the last page. I want to apply the background image
to all of the pages.
Posted on StackOverflow on Nov 1, 2014 by dandy
It is normal that the background is added only once, because youre adding it only once.
If you want to add content to every page, you should not do that manually because you dont know
when a new page will be created by iText. Instead you should use a page event.
The idea is to create an implementation of the PdfPageEvent interface, for instance by extending
the PdfPageEventHelper class and overriding the OnEndPage() method:
http://stackoverflow.com/questions/26688288/set-a-fix-background-image-for-all-my-pages-in-pdf-itext-asp-c-sharp
http://stackoverflow.com/users/4131886/dandy
Page events 39
In this case, we add a PdfTemplate, but it is very easy to add an Image replacing the Stationery
instance with an Image instance and replacing the AddTemplate() method with the AddImage()
method.
Once you have an instance of your custom page event, you need to declare it to the PdfWriter
instance:
From that moment on, your OnEndPage() method will be executed each time a page is finalized.
Warning: as documented you shall not use the OnStartPage() method to add content in a page
event!
If we adapt the above example to your requirement, the final result would look more or less like
this:
Note that 1700 and 1000 seems quite big. Are you sure those are the dimensions of your page?
Parsing XML and XHTML
There are a lot of questions about HTMLWorker on StackOverflow. Many of these questions remain
unanswered as HTMLWorker has been abandoned in favor of XML Worker. HTMLWorker was initially
meant as a parser for a small selection of HTML tags. People started using it as if it were a full-blown
HTML to PDF converter and then complained because HTMLWorker doesnt support CSS parsing. The
HTMLWorker code grew organically up until a point where it was no longer maintainable.
We started another project, called XML Worker. It can be used to convert XHTML to PDF. Its not
an URL to PDF converter in the sense that it wont print your web site to PDF. In HTML, you can
encounter content at the end of the file that needs to be added at the start of the document. When
this happens, one would expect that the start of the document is the first page. That isnt possible
with iText as iText flushes finished pages to the OutputStream as soon as possible and there is no
way to return to a previous page to add the extra content.
XML Worker is meant to create simple reports using an easy language such as HTML (and some
CSS). It wont resolve ASP pages, nor execute JavaScript. It will only deal with finished XHTML.
Could anybody explain to me why is it so complicated to create a pdf file from xml sheet?
Acrobat can create XML File but when I want to do this other way round it suddenly gets
complicated. I would like to find some simple application which would allow me to create
a pdf file out of xml. Is it possible?
Posted on StackOverflow on Jun 13, 2013 by DDEX
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename=reports.pdf");
Document document = new Document();
document.setPageSize(PageSize.A1);
PdfWriter writer = null;
writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
ByteArrayInputStream bis
= new ByteArrayInputStream(htmlSource.toString().getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis);
document.close();
With this code, Im able to generate PDF, but I would like to add a CSS file while generating
PDF.
Posted on StackOverflow on Jul 16, 2014 by Yella Goud
Please take a look at the ParseHtmlTable1 example. In this example, we have HTML stored in a
StringBuilder object and some CSS stored in a String. In my example, I convert the sb object and
the CSS object to an InputStream. If you have files with the HTML and the CSS, you could easily
use a FileInputStream.
Once you have an InputStream for the HTML and the CSS, you can use this code:
// CSS
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(CSS.getBytes()\
));
cssResolver.addCss(cssFile);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
// Pipelines
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
http://stackoverflow.com/questions/24777549/how-to-add-external-css-while-generating-pdf
http://stackoverflow.com/users/2436481/yella-goud
http://itextpdf.com/sandbox/xmlworker/ParseHtmlTable1
Parsing XML and XHTML 42
ByteArrayInputStream bis =
new ByteArrayInputStream(htmlSource.toString().getBytes());
ByteArrayInputStream cis =
new ByteArrayInputStream(cssSource.toString().getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis, cis);
When I try converting html to pdf using iText and XML Worker, Im asked to give the
closing tag for <hr> and <br> tags. It works if I do this manually, but I dont want to add
each closing tag manually. How can I do this in an automated way?
Posted on StackOverflow on Oct 30, 2014 by Kannu Verma
You are experiencing this problem because you are feeding HTML to iTexts XML Worker. XML
Worker requires XML, so you need to convert your HTML into XHTML.
There is an example on how to do this on the official iText site: D00_XHTML
http://stackoverflow.com/questions/26652029/how-to-do-xml-to-html-conversion-to-generate-closed-tags
http://stackoverflow.com/users/4197576/kannu-verma
http://itextpdf.com/sandbox/xmlworker/D00_XHTML
Parsing XML and XHTML 43
In this example, we get a path to an ordinary HTML file (similar to what you have). We then use
the Jsoup library to parse the HTML into an XHTML byte array. In this example, we use that byte
array to write an XHTML file to disk. You can use the byte array directly as input for XML Worker.
http://jsoup.org/
Inspect a PDF with iText
iText can tell you more about a PDF. What is the size of a page? Which measurement unit is used.
All of these questions can be answered with a simple example using PdfReader.
I have some code that reads pdf files. The code fails at the line :
iTextSharp.text.pdf.PRTokeniser.CheckPdfHeader() at
iTextSharp.text.pdf.PdfReader.ReadPdf()
I know from other entries that this issue is coming from some invalid formatting in the
PDF. However Im not in a position to tell my users to redo their PDFs. Is there some other
way around this issue, that can allow reading of the pdf despite this problem?
Posted on StackOverflow on Sep 10, 2012 by David Choi
If a file doesnt start with %PDF- then theres nothing to fix: the file isnt a PDF file.
However, there may be another problem: maybe youre trying to access a file that has zero length due
to some problem while creating the InputStream. Another context in which Ive seen this happen,
is a PDF loaded from a server, where the server returned a 404 message in HTML instead of a PDF
file ;-)
Whenever that exception happens, you should store the bytes somewhere, and examine them.
Without those bytes, nobody will be able to give you useful advice.
http://stackoverflow.com/questions/12357126/invalidpdfexception-pdf-header-signature-not-found
http://stackoverflow.com/users/1426199/david-choi
Inspect a PDF with iText 45
I have a PDF, and I want to get the width and height of each page using iTextSharp. This
is what I have so far:
string source=@"D:\pdf\test.pdf";
PdfReader reader = new PdfReader(source);
These are some methods that will give you information about the dimensions of a page. Most of
them return an object of type Rectangle that has methods such as getWidth() and getHeight() to
get the width and the height of the page. Other useful methods are getLeft() and getRight() as
well as getTop() and getBottom(). These four methods return the x and y coordinates that define
the boundaries of your page.
http://stackoverflow.com/questions/18202660/how-to-get-pdf-page-width-and-height
http://stackoverflow.com/users/2677532/mohamed-kamal
Manipulating existing PDFs
In this chapter, were going to solve some problems when working with existing PDFs that need to be
split into different files, merged or stamped. Usually, we are going to use a combination of PdfReader
to read the document and PdfStamper, PdfCopy or PdfSmartCopy to create a new PDF. Note that well
skip filling out interactive forms for now. Well deal with AcroForm and XFA technology in the next
chapter.
I need to change the value of a field in an existing PDF file. I am using PdfReader,
PdfStamper and AcroFields and thats working fine. But, in doing so, it is required to
create a new PDF and I would like the change to be reflected in the existing PDF itself.
If I am setting the destination filename to be the same as the original filename, then my
application fails.
Posted on StackOverflow on Apr 18, 2013 by tk2013
You cant read a file and write to it simultaneously. Think of how Microsoft Word works: you cant
open a Word document and write directly to it. Word always creates a temporary file, writes the
changes to it, then replaces the original file with it, and then throws away the temporary file.
You can do that too:
Or:
The latter option is more dangerous, as youll lose the original file if you do something that causes
an exception in PdfStamper. If I were you, Id create a temporary file.
http://stackoverflow.com/questions/16081831/using-itextsharp-stamper-required-to-update-in-the-same-pdf
http://stackoverflow.com/users/2239456/tk2013
Manipulating existing PDFs 47
It works fine, but my problem is that in some PDF files no watermark is added although
the file size increased, any idea?
Posted on StackOverflow on Jul 8, 2013 by Abady
The fact that the file size increases is a good indication that the watermark is added. The main
problem is that youre adding the watermark outside the visible area of the page. See my answer to
the question How to position text relative to page using iText?
You need something like this:
That is: if you want to add the image in the lower-left corner of the page. You can add an offset, but
make sure the offset in the x direction doesnt exceed the width of the page, and the offset in the y
direction doesnt exceed the height of the page.
http://stackoverflow.com/questions/17522965/how-to-add-a-watermark-to-a-pdf-file
http://stackoverflow.com/users/1450667/abady
Manipulating existing PDFs 48
This usually works great! But once and a while, its rotating some of the pages by 90
degrees? Anyone ever have this happen?
Posted on StackOverflow on Apr 14, 2014 by Nicholas DiPiazza
There are errors once in a while because you are using the wrong method to concatenate documents.
You should not use PdfWriter to concatenate (or merge) PDF documents. That is wrong because:
You completely ignore the page size of the pages in the original document (you assume they
are all of size A4),
You ignore page boundaries such as the crop box (if present),
You ignore the rotation value stored in the page dictionary,
You throw away all interactivity that is present in the original document, and so on.
http://stackoverflow.com/questions/23062345/function-that-can-use-itext-to-concatenate-merge-pdfs-together-causing-some
http://stackoverflow.com/users/1174024/nicholas-dipiazza
Manipulating existing PDFs 49
If you are merging documents that contain fields, you need to add the following line:
copy.SetMergeFields();
Manipulating existing PDFs 50
I would like to add a link to an existing pdf that jumps to a coordinate on another page.
I have the following problem when printing the PDF file after merge, the PDF documents
get cut off. Sometimes this happens because the documents arent 8.5 x 11 whereas the page
size might be 11 x 17.
Is there some way to detect the page size and then use that same page size for those
documents? Or, if not, is it possible to have it fit to page? This is my code:
Screen shot
Posted on StackOverflow on Feb 12, 2014 by Sumit Vaidya
Using PdfWriter to merge documents is a bad idea. This has been explained on StackOverflow many
times!
Merging documents is done using PdfCopy (or PdfSmartCopy).
If you need an example, see for instance the FillFlattenMerge2 example:
http://stackoverflow.com/questions/21731439/pdf-page-cutting-through-itext-api
http://stackoverflow.com/users/2853641/sumit-vaidya
http://itextpdf.com/sandbox/acroforms/reporting/FillFlattenMerge2
Manipulating existing PDFs 52
reader.close();
// end loop
document.close();
In your case, you also need to add page numbers, you can do this in a second go, as is done in the
StampPageXofY example:
Or you can add them while merging, as is done in the MergeWithToc example.
http://itextpdf.com/sandbox/stamper/StampPageXofY
http://itextpdf.com/sandbox/merge/MergeWithToc
Manipulating existing PDFs 53
I strongly advise against using PdfWriter to merge documents! As documented, you are throwing
away all annotations by adding PdfImportedPage instances to a document using addTemplate().
This is typically not what you want. Youre only making it harder on yourself if you insist on using
that class. I dont understand why so many people use the wrong approach to merge documents. I
blame the unofficial documentation for the popularity of this wrong approach.
Interactive forms
Is your form based on AcroForm technology or is it based on the XML Forms Architecture? Thats
a common counter-question youll be confronted with when asking a question about forms. In any
case, these answers should help you solving the most common problems with respect to forms.
What techniques available to fill a pdf form automatically using external data and save
them. I have to use data from a database to fill a template PDF and save a copy of it on
disk with that data. Language and platform is not issue but it would be good if it can run
on windows and Linux.
Posted on StackOverflow on Jun 24, 2010 by affan
If your form is based on AcroForm technology, you can use iText to fill it out like this:
In this snippet, src is the source of a PDF file (could be a path to a file, could be a byte[]) and dest
is the path to the resulting PDF. The key corresponds with the name of a field in your template. The
value corresponds with the value you want to fill in. If you want the form to keep its interactivity,
you need to remove the line stamper.setFormFlattening(true); otherwise all form fields will be
removed, resulting in a flat PDF.
http://stackoverflow.com/questions/3108704/how-to-fill-out-a-pdf-file-programatically
http://stackoverflow.com/users/109769/affan
Interactive forms 55
I have a dynamic XFA Form that I can fill out manually using Adobe Acrobat on my
computer. Using iTextSharp I can read what the XFA XML data is and see the structure of
the data. I am essentially trying to mimic that with iText using the following code:
This question was answered by the person who posted the question:
I found the issue. The replacement DomDocument needs to be the entire merged XML of
the new document, not just the data or datasets portion.
I upvoted this answer, because its not incorrect, but now that I think its better to use the example
from the book:
http://stackoverflow.com/questions/16502427/how-can-i-set-xfa-data-in-a-static-xfa-form-in-itextsharp-and-get-it-to-save
http://stackoverflow.com/users/511518/jon333
http://itextpdf.com/examples/iia.php?id=165
Interactive forms 56
As you can see, its not necessary to replace the whole XFA XML. If you use the FillXfaForm method,
the data is sufficient.
Interactive forms 57
This is my code:
This code throws no exception and everything seems to be OK, but if I open filled pdf,
Adobe Reader says something like this:
This document enabled extended features. This document was changed since
it was created and using extended features isnt possible anymore.
If I choose xml manually by clicking Import data from Adobe Reader, form is filled
properly, so I guess there is no error in xml.
Posted on StackOverflow on Oct 29, 2014 by paldir
In your code, you are not using PdfStamper in append mode. This means that iText will reorganize
the different objects in your PDF. Usually that isnt a problem.
However: your PDF is Reader-enabled, which means that your PDF is digitally signed using a private
key owned by Adobe. By reorganizing the objects inside the PDF, that signature is broken. This is
made clear by the message you already mentioned:
This document enabled extended features. This document was changed since it was
created and using extended features isnt possible anymore.
http://stackoverflow.com/questions/26629498/how-to-fill-xfa-form-using-itext
http://stackoverflow.com/users/4148435/paldir
Interactive forms 58
To avoid breaking the signature, you need to use PdfStamper in append mode. Instead of reorganiz-
ing the original content, iText will now keep the original file intact and append new content after
the end of the original file.
Actions and annotations
All things interactive are discussed here. Except for forms, weve already covered these.
I know how to target any text of any PDF page using code:
My question is how to target a page based on its number. For example if targeted page
number is 6, clicking on the Anchor text should take to 6th page.
Posted on StackOverflow on Feb 20, 2014 by Yogesh
Instead of an Anchor, you need a Chunk. To this Chunk you need to add a PdfAction. The action
needs to be a gotoLocalPage() action.
For instance:
I want to insert a hyperlink into an existing PDF at a position I know in advance: I already
have the coordinates of a rectangle on a given page. I want to link this rectangle to another
page of the same PDF (which I also know in advance). How do I achieve this?
Posted on StackOverflow on Nov 7, 2013 by Hans Stricker
Once you have an instance of PdfAnnotation, you can add it to a specific page using the
addAnnotation() method.
http://stackoverflow.com/questions/22194844/inserting-a-linked-rectangle-with-itext
http://stackoverflow.com/users/363429/hans-stricker
http://itextpdf.com/sandbox/annotations/AddLinkAnnotation
Actions and annotations 61
I am using java and iText to create a pdf. Is it possible to add a map with a pointer on it so
the user will know where the starting point is?
Posted on StackOverflow on Nov 6, 2014 by user2487493
What do you mean by a map with a pointer so the user knows where the starting point is? If you
have a map in your PDF, you could add an annotation that looks like an arrow. Is that what youre
looking for?
Since you didnt answer my counter-question added in comment, Im providing two examples. If
these are not what youre looking for, you really should clarify your question.
Example 1: add a custom shape as extra content on top of a map
This is demonstrated in the AddPointer example:
If we know the coordinates of the pointer, we can draw lines and curves that result in a the red
pointer shown here (see the red pin near the Cambridge Innovation Center):
http://stackoverflow.com/questions/26752663/adding-maps-at-itext-java
http://stackoverflow.com/users/2487493/user2487493
http://itextpdf.com/sandbox/objects/AddPointer
Actions and annotations 62
The result is an annotation (which isnt part of the real content, but part of an interactive layer on
top of the real content):
http://itextpdf.com/sandbox/annotations/AddPointerAnnotation
Actions and annotations 63
It is interactive in the sense that extra info is shown when the user clicks the annotation:
Many other options are possible, but once again: your question wasnt entirely clear.
Extracting text from PDFs
iText can parse PDFs to extract the content of a page. As there are many different ways to create a
PDF file, and as the text on a page usually isnt more than a bunch of characters drawn on a page,
its not trivial to extract text correctly.
I have a problem using iTextSharp when reading data from PDF File. What I want to achieve
is to read only specific part of PDF page (I want to only retrieve Address Information, which
is located at constant position). I have seen using iTextSharp for reading all pages such as
following:
http://stackoverflow.com/questions/24185066/itextsharp-read-from-specific-position
http://stackoverflow.com/users/1539189/robert-j
Extracting text from PDFs 65
Now youll get all the text snippets that intersect with the rect (so part of the text may be outside
rect, iText doesnt cut text snippets in pieces).
I have been searching for some unit tests for the program iText with no luck. Is anyone
aware of any such tests? Also, does anyone know if the developers use any automatic
testing tools on iText, such as Jenkins?
Posted on StackOverflow on Feb 21, 2014 by user3338813
1. The tests that are added when new core functionality is added. You can find these where
Maven expects them: each Maven project has a src directory with 2 sub directories: main and
test. For instance: if you look at iText core, youll find the released stuff here and the tests
here. Most of these tests are built on top of our testutils.
2. The tests that are added when we get questions on SO or when we create code samples for
the books. For these we use a generic test classes such as GenericTest and SandboxSam-
pleWrapper. The wrapper class makes creating a test a no-brainer. All you need to do to
turn a sample into a test is adding the @WrapToTest annotation. Well, actually theres more
involved: you need to follow a specific pattern when writing a sample: always use SRC and
DEST for source PDFs and resulting PDFs, always use a createPdf() or manipulatePdf()
method, and always give the cmp file the same name as the DEST file prefixed with cmp_.
In both cases, youll find PDF files of which the name starts with cmp_, see for instance the cmpfiles
folder for the examples. In both cases, youll find references to Ghostscript and a compare tool
(youll need to configure these).
http://stackoverflow.com/questions/21944424/itext-unit-testing-and-automated-testing-questions
http://stackoverflow.com/users/3338813/user3338813
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/itext/src/main/
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/itext/src/test/
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/itext/src/main/java/com/itextpdf/testutils/
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/sandbox/src/test/java/sandbox/GenericTest.java
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/sandbox/src/test/java/sandbox/SandboxSampleWrapper.java
http://sourceforge.net/p/itext/code/HEAD/tree/trunk/sandbox/cmpfiles/
General questions about iText 67
The code works fine. It is creating PDF successfully. but it gives me a runtime exception:
I have done clean and build, added jar to libs folder and make it selected on order and
export and i done lot of research for past 2 days. but nothing helped me. Based upon my
knowledge there should be these possibilities: (1) the external jar isnt loaded properly,
or (2) the class PdfGraphics2D extends java.awt.Graphics2D which is not available on
Android.
Posted on StackOverflow on Jun 14, 2013 by R9J
http://stackoverflow.com/questions/17102533/could-not-find-class-com-itextpdf-awt-pdfgraphics2d
http://stackoverflow.com/users/1912085/r9j
General questions about iText 68
Youve discovered that PdfGraphics2D extends java.awt.Graphics2D, and as you already know
Graphics2D is a forbidden class on Android.
Im using JDBC to fetch data from database and then I use iText to create a PDF file which
can be downloaded on client machine. The application is coded in HTML/JSP and runs on
Apache Tomcat.
I use the response.getOutputStream to create an output PDF file immediately. However,
I get the following error:
How can I generate a dynamic PDF file which can be downloaded by client machine?
Posted on StackOverflow on Jun 13, 2013 by Sahil Sharma
When you write JSP, you probably like white space and indentation, for instance:
http://itextpdf.com/product/itextg
http://itextpdf.com/product/itextg
http://stackoverflow.com/questions/17083318/how-to-insert-image-in-pdf-using-itext-and-download-to-client-machine
http://stackoverflow.com/users/2367475/sahil-sharma
General questions about iText 69
This will always cause the exception "getOutputStream() has already been called for this
response" regardless if youre using iText or not. The getOutputStream() method was called the
moment you introduced your first white space character in your JSP script.
To fix this, you need to remove all white space:
Not a single character is accepted outside the <% and %> markers. As explained in the better JSP
manuals, you shouldnt use JSP to create binary files. Why not? Because JSP introduces white space
characters at arbitrary places in your binary file. That results in corrupt files. Use Servlets instead!
Legal questions
Although StackOverflow is a forum where developers post technical questions and technical
questions only, we notice that some developers also want to know more about the legal aspects of
using open source, more specifically: is it legal to use iText for free? Is there a license fee involved?
What is the difference between lowagie and iText. Is this just version difference or up-
gradation to library. Which one recommended to be used.
Posted on StackOverflow on Nov 22, 2012 by Adeeb Cheulkar
I am Lowagie, the lowagie you refer to. Im the original author of iText and the author of the iText
in Action books.
As explained in the Sales FAQ, you should use the latest version of iText.
The differences between old versions of iText (iText 2.x.y dates from July 2009 or earlier) and newer
versions of iText can be found in the changelogs.
The 5.0.0 version had the following substantial changes:
Numerous bugs have been fixed since July 2009. Functionality that makes your PDFs future-proof
such as updates regarding new digital signature standards and new standards such as PDF/UA,
PDF/A-2 and PDF/A-3 is only available in the more recent iText versions.
http://stackoverflow.com/questions/13515210/difference-between-lowagie-and-itext
http://stackoverflow.com/users/1771109/adeeb-cheulkar
http://itextpdf.com/salesfaq
http://itextpdf.com/changelog
Legal questions 71
Can iText 2.1.7 (MPL/GPL) licence be used in commercial projects? I am not a legal guy but
lots of discussion threads suggest that there is no issue using the earlier version (2.1.7) of
iText in commercial projects as that version is bounded with terms & conditions governed
by MPL/GPL license.
However, if we look at iTexts official website, it says as the licence has been upgraded
to AGPL licence, one has to buy the software before commercially using it. See the topic
entitled Why shouldnt I use iText 2.x (or iTextSharp 4.x)?
LEGAL REASONS: Older versions of iText under the free model may con-
tain code fragments that infringe other peoples copyrights or intellectual
property rights. iText Software Group has done a significant investment in
identifying and eliminating all those cases as of version 5.1. which is one of
the reason why it is now a paying commercial version. We do not recommend
the use of versions prior to 5.1 for commercial projects as your company could
be liable for copyright or IP infringements.
Of course, this seems a warning only. Discouragement of not using iText with earlier
version due to Technical reasons could be understood but Legal reasons are not worth.
What about the commercial projects who have been using iText 2.1.7 before the licence
upgrade happened in iText? Would they now have to change their whole project planning
because iText has now change his mind to not to distribute it commercially? Of course
iText might has done significant investment in upgrading the version technically but what
about the investment one might have done in his commercial project using iText 2.1.7 or
earlier?
Please someone who understands legal implications of both the licences clarify this
confusion. iText can use such warning to encourage its sale but is there anything substantial
in such warning? Can one use iText with version 2.1.7 or earlier commercially? Comments
from Mr. Bruno Lowagie, the original author of iText are highly appreciated.
Posted on StackOverflow on Sep 6, 2014 by Devendra Sharma
The first iText company was founded in 2008. The purpose of this company was to put all the
Intellectual Property of the code into one legal entity. This was achieved by identifying [1.] every
third party project from which code was borrowed, as well as [2.] every individual developer who
contributed code.
https://www.mozilla.org/MPL/1.1/
http://itextpdf.com/salesfaq
http://stackoverflow.com/questions/25696851/can-itext-2-1-7-or-earlier-can-be-used-commercially
http://stackoverflow.com/users/2881228/devendra-sharma
Legal questions 72
[1.] Some code snippets were borrowed from projects with an ambiguous license. For instance: we
had a snippet that was released under Suns Example License (which allowed us to use the code), but
in the comment section of the class, it said that the code was proprietary to SUN (which prevented
us to use the code). Which of both prevailed? Being an ignorant developer at that time, I thought
the Example License was the one I could use, just like some people claim that you can use iText 2.1.7
today. Lawyers however, disagreed: they said that the most strict license was the valid one.
We solved these problems by (1) asking permission to use code with ambiguous licenses, (2)
refactoring code if we didnt get permission, (3) removing code we couldnt refactor.
We did the same with contributions from individual developers.
[2.] The IP from individual developers was transferred to iText Group NV (formerly known as 1T3XT
BVBA) by asking every developer who contributed 20 lines of code or more to sign a Contributor
License Agreement.
Two problems arose:
1. Individual developers could not be reached. For example: we dropped the RTF package
completely because we couldnt find a couple of the core developers of the RTF functionality.
2. In a couple of cases, we had to negotiate about the CLA. For example: one company didnt
like the CLA. Instead, this company released the contribution of its employees under an MIT
license, so that we could use it anyway. Another organization was really slow in agreeing with
the CLA. It took us until September 2009 before we received formal approval. Only after this
approval, we switched to the AGPL. I cant disclose the document (it was different from the
CLA), nor the name of the organization (I hope I dont break the NDA just by writing this). I
can only say that we only had full coverage of the code base after that document was signed.
Ignorant developers claim that the LGPL/MPL header protects them, but what if some proprietary
code was accidentally added to a class with such a header? Does this make that proprietary code
available under the MPL/LGPL? If it did, it would be sufficient to take proprietary code, add an
MPL/LGPL header and publish it. Doing this on purpose would be illegal. Doing this out of ignorance
can be pardoned if there is a willingness to fix the issue.
In the early years of open source, it did occur that proprietary code got mixed into an open source
project by accident. At iText, we have invested a lot of time and effort into cleaning up the code
base. Since that exercise, we are very disciplined with respect to code contributions. This is one of
the core tasks of a professional open source company.
After we fixed all the issues, we removed all copies of those old iText versions from our servers to
make sure we were in the clear. If a company decides to use some rogue version of iText 2.1.7 that is
outside of our control, this company does so willingly and knowingly, in other words: at its own
risk! There is no way such a company can claim: We didnt know there was a possible IP issue with
the code.
If you want to use iText 2.1.7, you need to do the exercise we have done between 2007-2009 at
your own expense. This will cost you more than the price of a license. For instance: the individual
Legal questions 73
developers gave permission to iText Group NV to do business with iText, but will they give that
permission to you? How will you identify those individual developers?
Moreover: iText 2.1.7 dates from July 2009, meaning that it is more than 5 years old. Many bugs have
been fixed since that date. Should you knowingly introduce those bugs into the code base of your
customer, then your customer may claim that you had an alternative: you could have used a more
recent version of iText
As for your question what about the investment one might have done in his commercial project using
iText 2.1.7 or earlier? That investment must have been done at least 3 years ago, because weve been
informing people that they should upgrade for at least that long. Upgrading to a recent version is an
investment that should be categorized as a maintenance cost. It should be an affordable cost because
whoever has been using iText 2.1.7 for that long in a commercial project has been making money
thanks to iText for that long. Claiming that iText has now changed its mind is not correct unless
now is marked as a synonym of 5 years ago in your dictionary.
To be continued
All the answers and the many code samples I have provided on StackOverflow were written in the
hope that they are helpful. I leave it up to the reader of this Best of selection to decide whether
or not Im kind of a dick as the people who down-voted some of my answers claim. I just love
answering questions, and where love is involved, theres also pain, for instance the pain if the love
isnt returned. Some people seem to make a sport out of it to beg for an answer and then to thank me
by saying: were never going to be a customer of iText Software. Somehow that doesnt compute. I
hope you understand.
Obviously, a book like this is never finished. New questions about iText are posted every day. I expect
that this book will grow over the years. Some answers may become obsolete, some new functionality
will require more clarification. This clarification may be provided in the form of an answer to a new
question, or as a topic in one of the other upcoming books:
https://leanpub.com/itext_pdfabce
https://leanpub.com/itext_pdfcreate
https://leanpub.com/itext_pdfupdate
https://leanpub.com/itext_pdfsign