问题描述
我正在尝试使用 iText7 创建一个 PDF,其中包含存储在图像和相应数字中的问题。数字和图像必须放在同一页上,所以我使用了一个表格对象将它们放在一起;但是,图像会超出页面边缘。
Table table = new Table(UnitValue.CreatePercentArray(8)).UseAllAvailableWidth();
Cell cellQuestionNumber = new Cell().Add(questionNum).SetBorder(Border.NO_BORDER);
Cell cellImage = new Cell().Add(img).SetBorder(Border.NO_BORDER);
table.AddCell(cellQuestionNumber);
table.AddCell(cellImage);
document.Add(table);
我看到有些人在图像上使用 .SetAutoScaleWidth(true)
,但是当我这样做时,图像只会缩小到难以置信的难以阅读的大小。
有什么建议吗?
解决方法
此处无需使用表格 - 您可以将要保留在一页中的元素添加到 Div
中,然后使用 setKeepTogether(true)
属性防止将 Div
拆分为两页。
为确保图像不超过页面宽度,您可以将其最大宽度属性设置为 100%。
这是一个代码示例:
Image image = new Image(ImageDataFactory.create("C:\\Users\\Alexey\\Desktop\\Capture.PNG"));
Div div = new Div();
div.add(new Paragraph("#1.)"));
div.add(image.setMaxWidth(UnitValue.createPercentValue(100)));
div.setKeepTogether(true);
document.add(div);