Foxit PDF SDK for Android

How do I insert an image into a PDF file?

There are two ways to help you insert an image into a PDF file. The first one is calling PDFPage.addImageFromFilePath interface. You can refer to the following sample code which inserts an image into the first page of a PDF file:

Note: Before calling PDFPage.addImageFromFilePath interface, you should get and parse the page that you want to add the image.

String path = "mnt/sdcard/input_files/sample.pdf";
try {

    // Initialize a PDFDoc object with the path to the PDF file.
    PDFDoc document = new PDFDoc(path);

    // Load the unencrypted document content.
    document.load(null);

    // Get the first page of the PDF file.
    PDFPage page = document.getPage(0);

    // Parse the page.
    if (!page.isParsed()) {
        Progressive parse = page.startParse(e_ParsePageNormal, null, false);
        int state = Progressive.e_ToBeContinued;
        while (state == Progressive.e_ToBeContinued) {
            state = parse.resume();
        }
    }

    // Add an image to the first page.
    page.addImageFromFilePath("mnt/sdcard/input_files/2.png", new PointF(20, 30), 60, 50, true);

    // Save the document that has added the image.
    document.saveAs("mnt/sdcard/input_files/sample_image.pdf", PDFDoc.e_SaveFlagNormal);

} catch (Exception e) {
    e.printStackTrace();
}

The second one is that use the PDFPage.addAnnot interface to add a stamp annotation to a specified page, and then convert the image to a bitmap and set the bitmap to the added stamp annotation. You can refer to the following sample code which inserts an image as a stamp annotation into the first page of a PDF file:

String path = "mnt/sdcard/input_files/sample.pdf";
try {
// Initialize a PDFDoc object with the path to the PDF file.
PDFDoc document = new PDFDoc(path);

// Load the unencrypted document content.
document.load(null);

// Get the first page of the PDF file.
PDFPage page = document.getPage(0);

// Add a stamp annotation to the first page.
Stamp stamp = (Stamp) page.addAnnot(Annot.e_annotStamp, new RectF(100, 350, 250, 150));

// Load a local image and convert it to a Bitmap.
Bitmap bitmap = BitmapFactory.decodeFile("mnt/sdcard/input_files/2.png");

// Set the bitmap to the added stamp annotation.
stamp.setBitmap(bitmap);

//Reset appearance stream.
stamp.resetAppearanceStream();

// Save the document that has added the stamp annotation.
document.saveAs("mnt/sdcard/input_files/sample_image.pdf", PDFDoc.e_saveFlagNormal);

} catch (Exception e) {
e.printStackTrace();

}

Updated on August 28, 2018

Was this article helpful?
Thanks for your feedback. If you have a comment on how to improve the article, you can write it here: