<!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>
'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
srvr.AddWebSocket("/insertImage/ws", "WSInsertImage")
...
Click Insert Image and you will get your image inserted into the PDF file where you liked.
It really worked.. See the result here as a downloadable gif fileIf 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".
#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
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?Inserting an Image file to a PDF file can also be done with the following code:
Notice: the file : pdfbox-app-2.0.16.jar should be in the Additional Libraries folderInsert 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
The PDF and Image files have to be in the Object folder of the b4j app
Hello.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
#if java
PDPageContentStream contents = new PDPageContentStream(doc, page);
#end if
#if java
PDPageContentStream contents = new PDPageContentStream(doc, page, true, true);
#end if