Laxman
Laxman

Reputation: 31

Text replace with Image in Apache PDFBOX

Can anyone help me out how to replace text with Image by using Apache PDFBOX ?

Upvotes: 3

Views: 2351

Answers (1)

L Kiran Nallam
L Kiran Nallam

Reputation: 31

import java.io.File;    
import java.io.IOException;    
import org.apache.pdfbox.pdmodel.PDDocument;           
import org.apache.pdfbox.pdmodel.PDPage;    
import org.apache.pdfbox.pdmodel.PDPageContentStream;    
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; 

public class RubberImagePaste {    
    public void createPDFFromImage( String inputFile, String imagePath, String outputFile )
            throws IOException
    {
        // the document
        PDDocument doc = null;
        try
        {
            doc = PDDocument.load( new File(inputFile) );

            PDPage page = doc.getPage(0);

            // createFromFile is the easiest way with an image file
            // if you already have the image in a BufferedImage, 
            // call LosslessFactory.createFromImage() instead
            PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

            // contentStream.drawImage(ximage, 20, 20 );
            // better method inspired by http://stackoverflow.com/a/22318681/535646
            // reduce this value if the image is too large
            float scale = 1f;
            contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth()*scale, pdImage.getHeight()*scale);

            contentStream.close();
            doc.save( outputFile );
        }
        finally
        {
            if( doc != null )
            {
                doc.close();
            }
        }
    }


    /**
     * 
     *
     * @param args The command line arguments.
     *
     * @throws IOException If there is an error parsing the document.
     */
    public static void main( String[] args ) throws IOException
    {
        String documentFile = "D:/ABC.pdf";
        String stampFile = "D:/Sign.png";
        String outFile = "D:ABCnew.pdf";

        new File("target/test-output").mkdirs();

        String[] args1 = new String[] { documentFile, outFile, stampFile };
        RubberImagePaste rubberStamp = new RubberImagePaste();
        rubberStamp.createPDFFromImage( documentFile, stampFile, outFile);
    }

    /**
     * This will print the usage for this example.
     */
    private void usage()
    {
        System.err.println( "Usage: java "+getClass().getName()+" <input-pdf> <output-pdf> <image-filename>" );
    }
}

Special Thanks to Tilman

Upvotes: 1

Related Questions