gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:15:26 27 4
gpt4 key购买 nike

我正在尝试使用 iText 缩放图像(在新的 PDF 文档上)以使其填充页面宽度而不拉伸(stretch),这样它可能需要几页。

我找到了很多解决方案,但它们都非常复杂,而且我真的不喜欢那样编码。到目前为止,我发现的最佳解决方案(来自关于 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();

有什么建议吗?

最佳答案

好吧,我最终决定走我不想走的路,因为这似乎是唯一的方法:将相同的图像添加到每个页面并为每个页面设置适当的垂直偏移。偏移量计算为剩余要绘制的页数 + 保持空白的间隙。对于每一步,我都会减少页数,直到没有东西可画为止。

// 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 是如何工作的。

关于itext - 缩放图像以使用 iText 填充多个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34392675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com