Java实现图片保存到pdf的某个位置2
1、依赖–maven
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency>
2、上代码
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;import javax.imageio.ImageIO;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;public class PdfBoxInsertImageExample {public static void main(String[] args) {try {File originalPdf = new File("path/to/original.pdf"); File tempPdf = new File("path/to/temp.pdf"); insertImageIntoPdf(originalPdf, tempPdf, 0, new Point2D.Float(100, 100), "path/to/image.jpg", null, null);} catch (IOException e) {e.printStackTrace(); }}public static void insertImageIntoPdf(File sourcePdf, File targetPdf, int pageIndex,Point2D.Float position, String imagePath,Float desiredWidth, Float desiredHeight) throws IOException {try (PDDocument document = PDDocument.load(sourcePdf)) { PDPage page = document.getPage(pageIndex);PDImageXObject image = LosslessFactory.createFromImage(document, ImageIO.read(new File(imagePath)));float originalWidth = image.getWidth();float originalHeight = image.getHeight();float scaleX = (desiredWidth != null) ? desiredWidth / originalWidth : 1f;float scaleY = (desiredHeight != null) ? desiredHeight / originalHeight : 1f;if (desiredWidth == null && desiredHeight != null) {scaleX = scaleY;} else if (desiredWidth != null && desiredHeight == null) {scaleY = scaleX;}float newWidth = originalWidth * scaleX;float newHeight = originalHeight * scaleY;try (PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true)) {contentStream.drawImage(image, position.x, position.y, newWidth, newHeight);}document.save(targetPdf);}}
}