Summary
This article introduces how to add pictures to PDF documents through java program, and how to replace and delete the existing pictures in PDF. In addition, for the operation of pictures, please refer to the settings PDF picture background , set up PDF image watermark,Read pictures in PDF , will PDF save as picture And so on.
Tools: free flame.pdf for Java (free version)
Jar access and import: Download official website And unzip the jar file under the lib folder into the java program, or through the maven warehouse download and import.
jar import effect:
Java code example
[example 1] add picture to PDF
import com.spire.pdf.*; import com.spire.pdf.graphics.*; public class AddImage { public static void main(String[] args) { //create documents PdfDocument pdf = new PdfDocument(); //Add a page PdfPageBase page = pdf.getPages().add(); //Load the picture and get the height and width of the picture PdfImage image = PdfImage.fromFile("fj.png"); int width = image.getWidth()/2; int height = image.getHeight()/2; //Draw picture to PDF page.getCanvas().drawImage(image,50,50,width, height); //Save document pdf.saveToFile("AddImage.pdf"); pdf.dispose(); } }
Picture adding effect:
[example 2] replace the picture in PDF
import com.spire.pdf.*; import com.spire.pdf.graphics.PdfImage; public class ReplaceImage { public static void main(String[] args) { //Load PDF File PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("AddImage.pdf"); //Get the first page PdfPageBase page = pdf.getPages().get(0); //Load a picture PdfImage image = PdfImage.fromFile("lh.png"); //Replace the first picture on the first page with the loaded picture page.replaceImage(0, image); //Save document pdf.saveToFile("ReplaceImage.pdf"); pdf.dispose(); } }
Picture replacement effect:
[example 3] delete the picture in PDF
import com.spire.pdf.*; public class DeleteImage { public static void main(String[] args) { //Establish PdfDocument object PdfDocument pdf = new PdfDocument(); //Load PDF File pdf.loadFromFile("AddImage.pdf"); //Get the specified page PdfPageBase page = pdf.getPages().get(0); //Delete the specified picture on the page page.deleteImage(0); //Save document pdf.saveToFile("DeleteSpecificImage.pdf", FileFormat.PDF); pdf.dispose(); } }
Picture deletion effect:
(end of this paper)