ITextSharp and putting rich text in a specific pos

2019-07-24 21:04发布

I have created a pdf document using Adobe LiveCycle. The problem I am facing is that I need to add some formatted text in a specific position on the document.

How can I do that?

    overContent.BeginText();
    overContent.SetTextMatrix(10, 400);
    overContent.ShowText("test");

This will only add basic text in the position specified and I really need to a linebreak, bullets, etc.. in the document.

标签: itextsharp
1条回答
神经病院院长
2楼-- · 2019-07-24 21:32

I am using iText in Java and also ran into a similar situation. I was just trying to insert a simple line break with NON-formatted text. The newline character (\n) doesnt fly. The solution I came up with (and it aint pretty) was:

// read in the sourcefile
reader = new PdfReader(path + sourcefile);

// create a stamper instance with the result file for output
stamper = new PdfStamper(reader, new FileOutputStream(path + resultfile));

// get under content (page)
cb = stamper.getUnderContent(page);
BaseFont bf = BaseFont.createFont();

// createTemplate returns a PdfTemplate (subclass of PdfContentByte)
// (width, height)
template = cb.createTemplate(500, 350);

Stack linelist = new Stack();
linelist.push("line 1 r");
linelist.push("line 2 r");
linelist.push("line 3 r");
int lineheight = 15;
int top = linelist.size() * lineheight;

for (int i = 0; i < linelist.size(); i++) {
    String line = (String) linelist.get(i);
    template.beginText();
    template.setFontAndSize(bf, 12);
    template.setTextMatrix(0, top - (lineheight * i));
    template.showText(line);
    template.endText();
}

cb.addTemplate(template, posx, (posy-top));
stamper.close();
  1. I break my lines into an array/stack/list whatever
  2. I loop trhu that list and setText one line at a time

There HAS to be a better way, but this worked for my situation (for the time being).

查看更多
登录 后发表回答