繁体   English   中英

如何使用 itext 在 PDF 文档上设置边框、边距和内边距 7

[英]How to set border, margin and padding on a PDF document using itext 7

我正在尝试为 PDF 文档设置边框、边距和填充,是否可以使用 itext7 来实现

通过设置以下代码,保证金工作正常

document.setLeftMargin(180);

但是边框不起作用,下面的代码用于设置边框

float width = 1.5f;
Color color = ColorConstants.BLUE;
Border border = new DottedBorder(color,width);
Document document = new Document(pdfDocument);
document.setBorder(border);

不幸的是,仅仅通过设置Document的一些属性是不可能指定文档的背景和边框的。 好消息是 iText7 为我们提供了重写DocumentRenderer的机会(渲染器是负责渲染对应的 model 对象的类,例如ParagraphRenderer渲染Paragraph等)。

在下面的自定义DocumentRenderer中, updateCurrentArea被覆盖以解决以下两个问题:

  • 缩小DocumentRenderer用于布局Document子级的区域

  • 添加背景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)); }

    }

最后一个问题是如何将其应用于您的文档。 可以这样做:

    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
    Document doc = new Document(pdfDoc);
    doc.setRenderer(new CustomDocumentRenderer(doc));

结果 PDF: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM