Reputation: 21
I am trying to set border, margin, and padding to a PDF document, is it possible to achieve using itext7
Margin works fine by setting below code
document.setLeftMargin(180);
But the border is not working, below code used to set the border
float width = 1.5f;
Color color = ColorConstants.BLUE;
Border border = new DottedBorder(color,width);
Document document = new Document(pdfDocument);
document.setBorder(border);
Upvotes: 0
Views: 4165
Reputation: 2458
Unfortunately it's not possible to specify the document's background and borders just by setting some of the Document
's properties. The good news is that iText7 provides us with an opportunity to override DocumentRenderer
(renderers are classes responsible to render corresponding model objects, for example, ParagraphRenderer
renders Paragraph
and so on).
In the custom DocumentRenderer
below updateCurrentArea
was overridden to tackle the following two issues:
shrinking the area which will be used by DocumentRenderer
to layout the Document
's children
adding a background Div
, whic will be resposible for border rendering (I've also shown how one could set background, if needed)
class CustomDocumentRenderer extends DocumentRenderer {
public CustomDocumentRenderer(Document document) {
super(document);
}
@Override
protected LayoutArea updateCurrentArea(LayoutResult overflowResult) {
LayoutArea area = super.updateCurrentArea(overflowResult); // margins are applied on this level
Rectangle newBBox = area.getBBox().clone();
// apply border
float[] borderWidths = {10, 10, 10, 10};
newBBox.applyMargins(borderWidths[0], borderWidths[1], borderWidths[2], borderWidths[3], false);
// this div will be added as a background
Div div = new Div()
.setWidth(newBBox.getWidth())
.setHeight(newBBox.getHeight())
.setBorder(new SolidBorder(10))
.setBackgroundColor(ColorConstants.GREEN);
addChild(new DivRenderer(div));
// apply padding
float[] paddingWidths = {20, 20, 20, 20};
newBBox.applyMargins(paddingWidths[0], paddingWidths[1], paddingWidths[2], paddingWidths[3], false);
return (currentArea = new RootLayoutArea(area.getPageNumber(), newBBox));
}
}
The last quetions is how to apply it on your document. It could be done as follows:
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
Document doc = new Document(pdfDoc);
doc.setRenderer(new CustomDocumentRenderer(doc));
Upvotes: 1