我是 iText 新手,面临着一个关于向段落添加外部图像的真正有趣的案例。事情是这样的:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("out2.pdf"));
document.open();
Paragraph p = new Paragraph();
Image img = Image.getInstance("blablabla.jpg");
img.setAlignment(Image.LEFT| Image.TEXTWRAP);
// Notice the image added to the Paragraph through a Chunk
p.add(new Chunk(img2, 0, 0, true));
document.add(p);
Paragraph p2 = new Paragraph("Hello Worlddd!");
document.add(p2);
给我图片和“Hello Worlddd!”下面的字符串。然而,
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("out2.pdf"));
document.open();
Paragraph p = new Paragraph();
Image img = Image.getInstance("blablabla.jpg");
img.setAlignment(Image.LEFT| Image.TEXTWRAP);
// Notice the image added directly to the Paragraph
p.add(img);
document.add(p);
Paragraph p2 = new Paragraph("Hello Worlddd!");
document.add(p2);
给我图片和字符串“Hello worlddd!”位于图片的右侧,其上方一行。
这种差异背后的逻辑是什么?
最佳答案
您描述的行为是因为在第二个代码片段中,段落不调整其行距,而是调整其宽度。如果在第二个片段中添加行
p.add("Hello world 1")
就在之前
p.add(img)
您会在左侧看到字符串“Hello world 1”,位于字符串“Hello Worlddd!”上方。如果输出 p 的行距 (System.out.println(p.getLeading()),您可以看到它是一个较低的数字(通常为 16),而不是图像的高度。
在第一个示例中,您使用带有 4 个参数的 block 构造函数
new Chunk(img, 0, 0, true)
最后一个(正确的)说要调整行距,因此它会按您的预期打印。
关于image - iText - 使用 Chunk 添加外部图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11118224/