Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

java - iText Image Resize

I have a watermark that I would like to put into my pdf. The watermark is a .bmp image, and is 2290 x 3026. I am having a lot of trouble trying to resize this picture to fit the page, does anyone have any suggestions?

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();

Here is the output for the getScaled() methods.

826.0 - Width
1091.4742 - Height

I would share the picture of the pdf with you guys but unfortunately I can't.

Should I try using a .jpg instead? I don't really know how well iText handles different image extensions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I do it like that:

//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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...