Java adds, extracts, replaces, and deletes PDF pictures

Posted by wayang_mbeling on Thu, 07 Nov 2019 15:49:43 +0100

(1) Introduction

PDF is used in many operating platforms with high quality and is ideal for archiving and sharing useful information.This next article describes adding, extracting, deleting, and replacing pictures in PDF documents using Java.The article is roughly structured as follows:

  1. Add Pictures to PDF
  2. Extract pictures from PDF
  3. Replace pictures in PDF
  4. Delete pictures from PDF

Tool use:

  • Free Spire.PDF for JAVA 2.4.4 (Free Edition)
  • Intellij IDEA or Eclipse

Jar package import:

Mode 1: From Official Web Unzip after getting Free Spire.PDF for Java, add Shift+Ctrl+Alt+S in IDEA or Eclipse to import the Spire.Pdf.jar package into the project, and the jar file can be obtained in the lib folder under the unzip path.

Mode 2: Configure the guide using Maven.Can be referred to Official Help Document.

 

Primary source document screenshots:

 

 

(2) JAVA code examples

1. Add pictures to PDF

public static void main(String[] args) {
    PdfDocument doc = new PdfDocument();
    //Create a blank page
    PdfPageBase page = doc.getPages().add();
    transformText(page);
    drawImageMethod(page);
    //Preservation PDF file
    doc.saveToFile("output/drawImage.pdf");
    doc.close();
} 
//Draw Text - Transformation
private static void transformText(PdfPageBase page) {
    PdfGraphicsState state = page.getCanvas().save();
  
    //item base PDFTrueTypeFont object
    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", Font.PLAIN, 10), true);
    PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.blue));
    PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.gray));
    PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
    page.getCanvas().translateTransform(page.getCanvas().getClientSize().getWidth()/2, 20);
    page.getCanvas().drawString("SALES REPORT CHAERT", font, brush1, 0, 0, format);
    page.getCanvas().scaleTransform(1f, -0.9f);
    page.getCanvas().drawString("SALES REPORT CHART", font, brush2, 0, -2 * 18 * 1.5f, format);
    page.getCanvas().restore(state);
}
//Draw pictures
private static void drawImageMethod(PdfPageBase page) {
    PdfImage image = PdfImage.fromFile("data/SalesChart.jpg");
    float width = image.getWidth() * 0.75f;
    float height = image.getHeight() * 0.75f;
    double x = (page.getCanvas().getClientSize().getWidth() - width) / 2;
    page.getCanvas().drawImage(image, (int)x,80, width, height);
}

Result:

2. Extract pictures from PDF

import com.spire.pdf.*;
public class extraction {
    public static void main(String[] args) throws Exception {
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("data/ Who_Moved_My_Cheese.pdf.pdf");
    //Set up index Get the first page of the document
        int index = 0;
        for (PdfPageBase page : (Iterable<PdfPageBase>) doc.getPages()) {
            //Use extractImages Method to get pictures on a specified page
            for (BufferedImage image : page.extractImages()) {
                //Specify Output File Path and Name
                File output = new File("output/" + String.format("Image_%d.png", index++));
                //Save Picture As PNG Format File
                ImageIO.write(image, "PNG", output);
            }
        }
    }
}

Result:

3. Replace pictures in PDF

import com.spire.pdf.*;
public class ReplaceImage {
    public static void main(String[] args) throws IOException {
        //Load PDF File
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("data/Who_Moved_My_Cheese.pdf");
        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);
        //Load a picture
        PdfImage image = PdfImage.fromFile("data/1.png");
        //Replace the first picture on the first page with the loaded picture
        page.replaceImage(0, image);
        //Save Document
        pdf.saveToFile("Replace Picture.pdf");
    }
}

Result:

4. Delete pictures from PDF

 

import com.spire.pdf.*;
 public class deleteImage {
    public static void main(String[] args) {
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("data/Who_Moved_My_Cheese.pdf");
        //Get the first page of the document
        PdfPageBase page = doc.getPages().get(0);
        //Delete the first image on the first page
        page.deleteImage(0);
        doc.saveToFile("output/Delete Picture.pdf");
        doc.close();
    }
}

 

Result:

P.S. There are also operations on pictures in PDF: PDF Add Picture Watermark.

Topics: Java Eclipse IntelliJ IDEA Maven