使用iText将图像缩放以填充多个页面

3
我正在尝试使用iText(在新PDF文档上)缩放图像,以使其填充页面宽度而不拉伸,以便它可以占用多个页面。
我找到了很多解决方案,但它们都非常复杂,我不是很喜欢那样编码。目前为止我发现的最好的解决方案(来自SO上的另一个问题)是使用PdfTable,但它总是使用单个页面来缩放图像。
// Load image from external storage
Image image = Image.getInstance(path + "/img.png");
// Calculate ratio
float width = PageSize.A4.getWidth();
float heightRatio = image.getHeight() * width / image.getWidth();
Document document = new Document();
document.open();
PdfPTable table = new PdfPTable(1);
table.setWidthPercentage(100);
PdfPCell c = new PdfPCell(image, true);
c.setBorder(PdfPCell.NO_BORDER);
c.setPadding(0);
// Set image dimensions
c.getImage().scaleToFit(width, heightRatio);
table.addCell(c);
document.add(table);
// Write PDF file
document.close();

任何建议吗?

1
在PDF中,每个页面都有自己的画布。如果图像绘制在一个页面画布上,这只会影响该页面的外观,对其他页面没有影响。你可以做的是在多个页面上绘制相同的图像,并选择适当的图像位置。图像位置。 - mkl
谢谢@Bruno,我明白了。我现在正在尝试用这种方法解决问题。我还发现了你的这个答案http://developers.itextpdf.com/question/how-show-image-large-dimensions-across-multiple-pages(至少我认为从图片上看是你的;))。 - afe
这个评论是@mkl提供的,但你说得对,照片里的男人是我,旁边的女人是我的妻子;-) 这个例子解决了你的问题吗?它并不复杂,是吧? - Bruno Lowagie
不,@Bruno,不是这样的,我只是希望以一种更清晰的方式来完成它。在下面的答案中,基于那个解决方案。 - afe
1个回答

4

好的,我最终决定走我不想走的路线,因为这似乎是唯一的方法:将相同的图像添加到每个页面并为每个页面设置适当的垂直偏移量。偏移量的计算方式为剩余要绘制的页面数加上留白的间隙。在每个步骤中,我会减少页面数量,直到没有可绘制的页面为止。

// Open new PDF file
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(getSharedDirPath() + File.separator + "file.pdf"));

document.open();
PdfContentByte content = pdfWriter.getDirectContent();

// Load image from external folder
Image image = Image.getInstance(path + "/img.png");
image.scaleAbsolute(PageSize.A4);
image.setAbsolutePosition(0, 0);

float width = PageSize.A4.getWidth();
float heightRatio = image.getHeight() * width / image.getWidth();
int nPages = (int) (heightRatio / PageSize.A4.getHeight());
float difference = heightRatio % PageSize.A4.getHeight();

while (nPages >= 0) {
    document.newPage();
    content.addImage(image, width, 0, 0, heightRatio, 0, -((--nPages * PageSize.A4.getHeight()) + difference));
}

// Write PDF file
document.close();

说实话,我不太喜欢这个解决方案,我以为像在文本编辑器中那样自动调整尺寸是可能的,但最终并不是很困难......只是花了我三天时间弄清楚PDF的整个过程。


说实话,我不喜欢这个解决方案 - 没有理由不喜欢。 - mkl
当然不会有。 "De gustibus non disputandum est"。 - afe
1
在“没有根本上更好的方法”这个意义上,“没有理由” - mkl
我使用 scaleToFit() 方法来在保持纵横比的同时,在一个维度上缩放图像。例如,在您的情况下,我会这样做:image.scaleToFit(PageSize.A4.getWidth(), 10000); 通过在 y 方向上使用极大值,图像将在 x 方向上缩放,并相应地调整高度,从而保持纵横比。 - Bruno Lowagie
是的,我明白了。一开始我还以为有更好的方法呢。@Bruno 我会试试的。不过我觉得这样做没什么用,因为我还是需要在addImage调用中手动设置宽度和高度,对吧? - afe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接