iText 图像调整大小

2022-09-01 19:37:29

我有一个水印,我想把它放到我的pdf中。水印是.bmp图像,尺寸为 2290 x 3026。我在尝试调整此图片大小以适应页面时遇到了很多麻烦,有人有任何建议吗?

Document document = new Document(); 
PdfWriter.getInstance(document, new FileOutputStream("result.pdf")); 
document.open(); 
document.add(new Paragraph("hello")); 
document.close(); 
PdfReader reader = new PdfReader("result.pdf"); 
int number_of_pages = reader.getNumberOfPages(); 
PdfStamper pdfStamper = new PdfStamper(reader, new FileOutputStream("result_watermark.pdf")); 
// Get the PdfContentByte type by pdfStamper. 
Image watermark_image = Image.getInstance("abstract(0307).bmp"); 
int i = 0; 
watermark_image.setAbsolutePosition(0, 0);
watermark_image.scaleToFit(826, 1100);
System.out.println(watermark_image.getScaledWidth());
System.out.println(watermark_image.getScaledHeight()); 
PdfContentByte add_watermark; 
while (i < number_of_pages) { 
    i++; 
    add_watermark = pdfStamper.getUnderContent(i); 
    add_watermark.addImage(watermark_image); 
} 
pdfStamper.close();

下面是这些方法的输出。getScaled()

826.0 - Width
1091.4742 - Height

我会与你们分享pdf的图片,但不幸的是我不能。

我应该尝试使用.jpg吗?我真的不知道iText处理不同图像扩展的能力如何。


答案 1

我这样做:

//if you would have a chapter indentation
int indentation = 0;
//whatever
Image image = coolPic;

float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
               - document.rightMargin() - indentation) / image.getWidth()) * 100;

image.scalePercent(scaler);

答案 2

watermark_image.scaleAbsolute(826, 1100);

而不是

watermark_image.scaleToFit(826, 1100);

推荐