如何在java中的itext pdf库中为段落添加边框?

时间:2015-05-05 12:58:08

标签: java itext

我在java中使用itext pdf库创建了一个段落。我必须为段落添加边框,而不是整个文档。怎么做?

2 个答案:

答案 0 :(得分:2)

请查看BorderForParagraph示例。它显示了如何为这样的段落添加边框:

enter image description here

没有方法允许您为Paragraph创建边框,但您可以创建PdfPageEvent实现,允许您根据{的开始和结束位置绘制矩形{1}}:

Paragraph

如您所见,我介绍了一个名为class ParagraphBorder extends PdfPageEventHelper { public boolean active = false; public void setActive(boolean active) { this.active = active; } public float offset = 5; public float startPosition; @Override public void onParagraph(PdfWriter writer, Document document, float paragraphPosition) { this.startPosition = paragraphPosition; } @Override public void onParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) { if (active) { PdfContentByte cb = writer.getDirectContentUnder(); cb.rectangle(document.left(), paragraphPosition - offset, document.right() - document.left(), startPosition - paragraphPosition); cb.stroke(); } } } 的{​​{1}}参数。默认情况下,我将此参数设置为boolean。我还创建了active(更改此值以微调结果)和false参数。

每次iText开始呈现offset对象时,startPosition值都会更新。每次iText结束呈现Paragraph时,如果startPositionParagraph,则会绘制一个矩形(否则没有任何反应)。

我们使用这样的事件:

active

如您所见,我们使用true方法向public void createPdf(String dest) throws IOException, DocumentException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest)); ParagraphBorder border = new ParagraphBorder(); writer.setPageEvent(border); document.open(); document.add(new Paragraph("Hello,")); document.add(new Paragraph("In this document, we'll add several paragraphs that will trigger page events. As long as the event isn't activated, nothing special happens, but let's make the event active and see what happens:")); border.setActive(true); document.add(new Paragraph("This paragraph now has a border. Isn't that fantastic? By changing the event, we can even provide a background color, change the line width of the border and many other things. Now let's deactivate the event.")); border.setActive(false); document.add(new Paragraph("This paragraph no longer has a border.")); document.close(); } 声明了该事件。我们激活这样的事件:

PdfWriter

我们将其停用:

setPageEvent()

这是唯一的概念验证!如果您希望此方法适用于跨越多个页面的段落,则需要实施border.setActive(true); border.setActive(false); 方法。这显示在BorderForParagraph2

enter image description here

onStartPage()onEndPage()实施很简单:

onStartPage()

答案 1 :(得分:0)

试试这个:

public static void main(String[] args) {
     Document document = new Document();
    // step 2
    PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream("somepath"));
    document.setPageSize(PageSize.LETTER);
    document.setMargins(36, 72, 108, 180);
    document.setMarginMirroring(false);
    // step 3
    document.open();
    // step 4
    Rectangle rect= new Rectangle(36,108);
    rect.enableBorderSide(1);
    rect.enableBorderSide(2);
    rect.enableBorderSide(4);
    rect.enableBorderSide(8);
    rect.setBorder(2);
    rect.setBorderColor(BaseColor.BLACK);
    document.add(rect);
}