This article will show you how to add, remove, and replace images in PDF documents in Java.
--Free Spire.PDF for JAVA 2.4.4 (free version)
** Method 1: ** First, after getting Free Spire.PDF for JAVA from Official Site Decompress. Here are three easy ways to open Project Structure in IDEA.
After that, follow the procedure below. (1) Select "Modules"-"Dependencies" and add the external jar package. (2) Enter the "Attach File or Directores" screen, select the path of the jar file, and click "OK". As shown in the following figure:
** Method 2: ** Place the jar package using Maven. You can refer to Installation Method. I will.
Test documentation:
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
public class drawImage {
public static void main(String[] args) {
//create the PDF
PdfDocument doc = new PdfDocument();
//Load the PDF sample file
doc.loadFromFile("data/Sample.pdf");
//Get the first page
PdfPageBase page = doc.getPages().get(0);
drawImageMethod(page);
//Save the file
doc.saveToFile("output/drawImage.pdf");
doc.close();
}
private static void drawImageMethod(PdfPageBase page) {
//Add the image
PdfImage image = PdfImage.fromFile("data/1.png ");
float width = image.getWidth() * 0.3f;
float height = image.getHeight() * 0.3f;
//Get the location of image
page.getCanvas().drawImage(image, 420,100, width, height);
}
}
Add result:
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;
import java.io.IOException;
public class ReplaceImage {
public static void main(String[] args) throws IOException {
//Create the PDF
PdfDocument pdf = new PdfDocument();
//Load the PDF sample file
pdf.loadFromFile("data/Sample.pdf");
//Get the first page
PdfPageBase page = pdf.getPages().get(0);
//Load the image
PdfImage image = PdfImage.fromFile("data/1.png ");
//Replace the first image of the first page
page.replaceImage(0, image);
//Save the file
pdf.saveToFile("ImageReplace.pdf");
}
}
Replacement result:
import com.spire.pdf.*;
public class deleteImage {
public static void main(String[] args) {
//Create the PDF
PdfDocument doc = new PdfDocument();
//Load the PDF sample file
doc.loadFromFile("data/Sample.pdf");
//Get the first page
PdfPageBase page = doc.getPages().get(0);
//Delete the first page of the first page
page.deleteImage(0);
doc.saveToFile("output/ImageDelete.pdf");
doc.close();
}
}
Delete result: (End of text)
Recommended Posts