An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
Insert Images in PDF in Java
Image is an important part of PDF documents, and inserting images at appropriate positions on a PDF page can make the document more attractive. This article will share how to insert an image into an existing PDF document using Free Spire.PDF for Java.
Import Jar Dependency (2 Methods)
Method 1: Download the free library and unzip it. Then add the Spire.Pdf.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository></repositories><dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf.free</artifactId> <version>5.1.0</version> </dependency></dependencies>
Sample Code
Free Spire.PDF for Java provides the PdfPageBase.getCanvas().drawImage() method to add images to the PDFs when creating as well as insert images into existing PDFs. The following code shows how to insert an image into an exixting PDF document, and to avoid covering the text content, I set the transparency to the inserted image.
import com.spire.pdf.*;import com.spire.pdf.graphics.PdfImage;public class InsertImage { public static void main(String[] args) { //Create PDF document PdfDocument pdf = new PdfDocument(); //Load the PDF document from disk pdf.loadFromFile("D:\\Files\\input.pdf"); //Get a specified page PdfPageBase page = pdf.getPages().get(0); //Load an image PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\Olympics.jpg"); //Set the width and height of image float width = image.getWidth() * 0.75f; float height = image.getHeight() * 0.75f; //Define a position to draw image double x = (page.getCanvas().getClientSize().getWidth()-width) /2; float y = 300f; //Set image transparency page.getCanvas().setTransparency(0.5f); //Draw image on page canvas page.getCanvas().drawImage(image, x, y, width, height); //Save the document pdf.saveToFile("insertImage.pdf", FileFormat.PDF); pdf.close(); }}
Original Link: https://dev.to/carlwils/insert-image-in-pdf-in-java-1pdb
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To