B4J Question How to Insert an image to a pdf file.

warayTek

Member
Licensed User
Hi, I have an existing PDF file and would like to insert an image to a specific location. What I found so far are examples that start on a new page. I appreciate any help.
 

jkhazraji

Active Member
Licensed User
Longtime User
-Create a b4j server project.
-Add the index.html file to your www subfolder(Name it e.g., InsertImage):
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Insert Image in PDF</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
    <script src="https://unpkg.com/pdf-lib/dist/pdf-lib.js"></script> <!-- Include the pdf-lib library -->
    <script src="/b4j_ws.js"></script>
</head>
<body>
    <button id="insertButton">Insert Image</button>
 
    <script>
        $(document).ready(function() {
        b4j_connect("/insertImage/ws");            
    });
    </script>
</body>
</html>
-Insert a Server Websocket class ( let it be 'WSInsertImage' for example).
-Here it is:
B4X:
'WebSocket class
Sub Class_Globals
    Private ws As WebSocket
End Sub

Public Sub Initialize
   
End Sub

Private Sub WebSocket_Connected (WebSocket1 As WebSocket)
    ws = WebSocket1
    Log("Connected")
    InsertImage
End Sub
Private Sub InsertImage()
    Dim script As String =$"
     const insertButton = document.getElementById('insertButton');

        insertButton.addEventListener('click', async () => {
        const existingPdfUrl = 'test.pdf'; // Replace with your PDF file
        const imageUrl = 'SampleJPG.jpg'; // Replace with your image URL
       
        // Load the existing PDF
        const existingPdfBytes = await fetch(existingPdfUrl).then(res => res.arrayBuffer());
        const pdfDoc = await PDFLib.PDFDocument.load(existingPdfBytes);

        // Load the image to be inserted
        const imageBytes = await fetch(imageUrl).then(res => res.arrayBuffer());
        const image = await pdfDoc.embedJpg(imageBytes);

        // Get the first page of the PDF (change the index if needed)
        const page = pdfDoc.getPages()[0];

        // Insert the image at the specified coordinates
        page.drawImage(image, {
            x: 100, // X-coordinate of the top-left corner
            y: 400, // Y-coordinate of the top-left corner
            width: 200,
            height: 100,
        });

        // Generate a new PDF with the inserted image
        const modifiedPdfBytes = await pdfDoc.save();

        // Create a blob from the PDF bytes and create a download link
        const blob = new Blob([modifiedPdfBytes], { type: 'application/pdf' });
        const url = URL.createObjectURL(blob);
        alert(url);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'modified-pdf.pdf';
        a.click();
        });
    "$
      ws.Eval(script,Null)
      ws.Flush
End Sub
Private Sub WebSocket_Disconnected

End Sub

-Add the the following line to your main:
B4X:
srvr.AddWebSocket("/insertImage/ws", "WSInsertImage")
-Change the name of the PDF and Image file in the code into yours.
-Change the PDF page and image position in the code.
-open browser and navigate to: http://127.0.0.1:XXXXX/insertImage.
-Click Insert Image and you will get your image inserted into the PDF file where you liked.
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
...
Click Insert Image and you will get your image inserted into the PDF file where you liked.

If all that works - and it looks like it could ? - then it brings to mind the phrase:

Any sufficiently advanced technology is indistinguishable from magic

and that perhaps the forum needs a new user category "Magician".
 
Upvote 0

jkhazraji

Active Member
Licensed User
Longtime User
If all that works - and it looks like it could ? - then it brings to mind the phrase:

Any sufficiently advanced technology is indistinguishable from magic

and that perhaps the forum needs a new user category "Magician".
It really worked.. See the result here as a downloadable gif file
 
Last edited:
Upvote 0

jkhazraji

Active Member
Licensed User
Longtime User
Inserting an Image file to a PDF file can also be done with the following code:
Insert Image in PDF file:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 600
#End Region
#AdditionalJar:pdfbox-app-2.0.16.jar
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI
    Private Button1 As B4XView
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
   
    Dim jo As JavaObject = Me
    Dim inPDFPath As String= File.Combine(File.DirApp,"test.pdf")
 
    Dim outPDFPath As String= File.Combine(File.DirApp,"modified.pdf")
   
    Dim imgPath As String= File.Combine(File.DirApp,"SampleJPG.jpg")
    Dim pageNo As Int = 0
    jo.RunMethod("InsertingImageInPdf",Array(inPDFPath,outPDFPath,imgPath, pageNo))
   
End Sub



#if Java
import java.io.File;
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 static void InsertingImageInPdf(String inpPDFFile, String outpPDFFile, String imgFile, int pageNumber) throws Exception {
     
      //Loading an existing document
      File file = new File(inpPDFFile);
      PDDocument doc = PDDocument.load(file);

      //Retrieving the page
      PDPage page = doc.getPage(pageNumber);

      //Creating PDImageXObject object
      PDImageXObject pdImage = PDImageXObject.createFromFile(imgFile, doc);

      //creating the PDPageContentStream object
      PDPageContentStream contents = new PDPageContentStream(doc, page);

      //Drawing the image in the PDF document. The numbers are the coordinates, width and height of the image
      contents.drawImage(pdImage, 10, 650,100,100);    
      System.out.println("Image inserted");

      //Closing the PDPageContentStream object
      contents.close();      

      //Saving the document
      doc.save(outpPDFFile);
     
      //Closing the document
      doc.close();
   }
 


#End If
Notice: the file : pdfbox-app-2.0.16.jar should be in the Additional Libraries folder
The PDF and Image files have to be in the Object folder of the b4j app
 
Last edited:
Upvote 0

warayTek

Member
Licensed User
Inserting an Image file to a PDF file can also be done with the following code:
Insert Image in PDF file:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 600
#End Region
#AdditionalJar:pdfbox-app-2.0.16.jar
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI
    Private Button1 As B4XView
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
  
    Dim jo As JavaObject = Me
    Dim inPDFPath As String= File.Combine(File.DirApp,"test.pdf")
 
    Dim outPDFPath As String= File.Combine(File.DirApp,"modified.pdf")
  
    Dim imgPath As String= File.Combine(File.DirApp,"SampleJPG.jpg")
    Dim pageNo As Int = 0
    jo.RunMethod("InsertingImageInPdf",Array(inPDFPath,outPDFPath,imgPath, pageNo))
  
End Sub



#if Java
import java.io.File;
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 static void InsertingImageInPdf(String inpPDFFile, String outpPDFFile, String imgFile, int pageNumber) throws Exception {
    
      //Loading an existing document
      File file = new File(inpPDFFile);
      PDDocument doc = PDDocument.load(file);

      //Retrieving the page
      PDPage page = doc.getPage(pageNumber);

      //Creating PDImageXObject object
      PDImageXObject pdImage = PDImageXObject.createFromFile(imgFile, doc);

      //creating the PDPageContentStream object
      PDPageContentStream contents = new PDPageContentStream(doc, page);

      //Drawing the image in the PDF document. The numbers are the coordinates, width and height of the image
      contents.drawImage(pdImage, 10, 650,100,100);   
      System.out.println("Image inserted");

      //Closing the PDPageContentStream object
      contents.close();     

      //Saving the document
      doc.save(outpPDFFile);
    
      //Closing the document
      doc.close();
   }
 


#End If
Notice: the file : pdfbox-app-2.0.16.jar should be in the Additional Libraries folder
The PDF and Image files have to be in the Object folder of the b4j app
Sorry for the late reply. I've been busy and totally forgot to make a response. Thanks for the code, works well. But I have a question, How can I insert an image to a specific page without clearing the content?

This an example file where I want to insert my image.
lpo.png

when trying to add the image this is the output
lpo2.png
 
Upvote 1

jkhazraji

Active Member
Licensed User
Longtime User
Sorry for the late reply. I've been busy and totally forgot to make a response. Thanks for the code, works well. But I have a question, How can I insert an image to a specific page without clearing the content?

This an example file where I want to insert my image.
View attachment 145851
when trying to add the image this is the output
View attachment 145850
Hello.
-Use a transparent png image for signature.
-Detect the coordinates (x,y) in the pdf file where to place it ( Note that the coordinate system in a pdf page starts from the lower left corner (0,0))
- Change the following inline Java code:
B4X:
#if java
    PDPageContentStream contents = new PDPageContentStream(doc, page);
#end if
into:
B4X:
#if java
    PDPageContentStream contents = new PDPageContentStream(doc, page, true, true);
#end if
Which is the append mode that will not overwrite the page contents.
The final result in your case:
1694681763514.png
 
Upvote 0
Top