[英]How to set border, margin and padding on a PDF document using itext 7
I am trying to set border, margin, and padding to a PDF document, is it possible to achieve using itext7我正在尝试为 PDF 文档设置边框、边距和填充,是否可以使用 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);
Unfortunately it's not possible to specify the document's background and borders just by setting some of the Document
's properties.不幸的是,仅仅通过设置Document
的一些属性是不可能指定文档的背景和边框的。 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).好消息是 iText7 为我们提供了重写DocumentRenderer
的机会(渲染器是负责渲染对应的 model 对象的类,例如ParagraphRenderer
渲染Paragraph
等)。
In the custom DocumentRenderer
below updateCurrentArea
was overridden to tackle the following two issues:在下面的自定义DocumentRenderer
中, updateCurrentArea
被覆盖以解决以下两个问题:
shrinking the area which will be used by DocumentRenderer
to layout the Document
's children缩小DocumentRenderer
用于布局Document
子级的区域
adding a background Div
, whic will be resposible for border rendering (I've also shown how one could set background, if needed)添加背景Div
,它将负责边框渲染(如果需要,我还展示了如何设置背景)
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.