Java如何使用iText缩放PDF文档中的图像?
com.itextpdf.text.Image该类中的一些方法可用于缩放图像。这些方法包括:scaleAbsolute(),scaleAbsoluteWidth(),scaleAbsoluteHeight(),scalePercent()和scaleToFit()。
package org.nhooo.example.itextpdf; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileOutputStream; import java.io.IOException; public class ImageScalingDemo { public static void main(String[] args) { Document doc = new Document(); try { PdfWriter.getInstance(doc, new FileOutputStream("ImageScaling.pdf")); doc.open(); //将图像缩放到绝对宽度和绝对 //高度 String filename = "other-sample/src/main/resources/java.gif"; Image image = Image.getInstance(filename); image.scaleAbsolute(200f, 200f); doc.add(image); //下一行可以防止“服务器退回"Server returned //HTTP响应代码:403“错误。" error. System.setProperty("http.agent", "Chrome"); //将图像缩放到一定比例 String url = "https://nhooo.org/wp-content/uploads/2017/01/nhooo.png"; image = Image.getInstance(url); image.scalePercent(200f); doc.add(image); //缩放图像,使其适合特定的宽度并 //高度 image = Image.getInstance(url); image.scaleToFit(100f, 200f); doc.add(image); } catch (DocumentException | IOException e) { e.printStackTrace(); } finally { doc.close(); } } }
Maven依赖
<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency>