我使用 iText 库来创建并操作 PDF 文档。 让我们有一个包含简单字符串的文档,例如“Hello world”。 所以在pdf文件结构中,我们必须有(Hello world)Tj。 问题是我如何通过使用java代码设置每个字符的位置(我们也可以讨论TJ运算符)。 我保证他/她帮助我并给我想法的人,我会将他/她的名字作为我的项目中的引用:)
任何答案都值得赞赏:)
最诚挚的问候,
最佳答案
The problem is how can i set position for each character by using java code
使用 iText,您可以通过使用 PdfContentByte 的文本定位和显示方法轻松定位任何文本片段(包括单个字符)。
如果您想包装该功能,可以使用辅助类,例如这个:
public class ContentWriter
{
public ContentWriter(PdfContentByte content) throws DocumentException, IOException
{
this.content = content;
BaseFont bf = BaseFont.createFont();
content.beginText();
content.setFontAndSize(bf, 12);
}
// x and y are offsets relative to the start coordinates of the most recent write call
public ContentWriter write(float x, float y, String text)
{
if (finished)
throw new IllegalStateException("ContentWritr session already finished.");
content.moveText(x, y);
content.showText(text);
return this;
}
public void finish()
{
if (!finished)
{
content.endText();
finished = true;
}
}
final PdfContentByte content;
boolean finished = false;
}
可以这样使用:
public void testShowSomePositionedContent() throws DocumentException, IOException
{
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("positionedContent.pdf"));
document.open();
PdfContentByte cb = writer.getDirectContent();
new ContentWriter(cb).
write(100, 400, "A").
write(20, 0, "B").
write(18, 2, "C").
write(10, 7, "D").
finish();
document.close();
}
此示例代码创建了以下内容:
由于您还讨论了 PDF 运算符,因此您可能对 PDF 本身的外观感兴趣:
BT
/F1 12 Tf
100 400 Td
(A)Tj
20 0 Td
(B)Tj
18 2 Td
(C)Tj
10 7 Td
(D)Tj
ET
由于 ContentWriter
帮助程序类仅需要一个 PdfContentByte
实例,因此它也可以与 PdfStamper 中某些页面的 UnderContent 或 OverContent 一起使用。
关于java - 与 TJ 运算符(operator)合作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17686744/