You are on the right track when you want to involve PdfTemplate
elements. PdfTemplate
is an iText object that corresponds with the concept of Form XObjects in the PDF specification. We chose another name because the word Form is somewhat misleading (people confuse it with form fields, interactive forms, etc).
The content stream of a page in PDF is a sequence of PDF syntax, consisting of operands and operators. An XObject is an object that is external to this content stream. The content of an XObject is stored inside the PDF document only once, but it can be reused many times on the same page, on different pages.
There are different types of XObjects, but Image XObjects and Form XObjects are the most important ones.
- Image XObjects are used when we work with raster images. You are absolutely right when you write: *"I don't want to draw my boxes and lines into an image and drop the image into the Section, that won't look as good as if I have actual PDF boxes and lines."
- Form XObjects are used when we want to reuse PDF syntax. This is what you need: you want to define
moveTo()
, lineTo()
, curveTo()
, stroke()
, fill()
,... operations, and you want these lines and shapes to be stored as vector data.
The solution to your problem is to draw lines and shapes to a PdfTemplate
object and to wrap the PdfTemplate
object inside an Image
object. When you add that Image
object to a Section
or a Chapter
, it will be added as a Form XObject. You don't have to feat that it will be degraded into a raster image.
You can find some examples of this technique on the official web site. For instance in the answer to the question
How to generate 2D barcode as vector image?
Here we create a PdfTemplate
with a bar code and we return it as an Image
object. The screen shot that shows you the internals of the resulting PDF proves that the bar code is added as a vector image.
public Image createBarcode(PdfContentByte cb, String text,
float mh, float mw) throws BadElementException {
BarcodePDF417 pf = new BarcodePDF417();
pf.setText("BarcodePDF417 barcode");
Rectangle size = pf.getBarcodeSize();
PdfTemplate template = cb.createTemplate(
mw * size.getWidth(), mh * size.getHeight());
pf.placeBarcode(template, BaseColor.BLACK, mh, mw);
return Image.getInstance(template);
}
To create a PdfTemplate
object, you need a PdfContentByte
instance (e.g. using writer.getDirectContent()
) and use the createTemplate()
method passing a width and a height as parameters. Then you draw content to the PdfTemplate
and turn it into an Image
object using Image.getInstance()
.
You'll find more info on drawing lines and shapes in the chapter on Absolute positioning of lines and shapes and in the example section of Chapter 3 and Chapter 14 of my book.