Android Question Inline PDFBOX for android Java code

mike1967

Active Member
Licensed User
Longtime User
Hello , i have added the pdfbox for android library with #AdditionalJar:
Jar Library:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
    #AdditionalJar: pdfbox-android-2.0.27.0.aar

#End Region

i have this inline java code :
Code:
Sub Class_Globals
    Private joNative As JavaObject
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    joNative = Me
End Sub

Public Sub FirstMethod As String
    Return joNative.RunMethod("fillForm",Array As String("11/12/1967","1","1",File.Combine(File.DirInternal,"verifica_template.pdf")))
End Sub

#if JAVA

import android.content.res.AssetManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;

import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.pdmodel.PDDocumentCatalog;
import com.tom_roush.pdfbox.pdmodel.PDPage;
import com.tom_roush.pdfbox.pdmodel.PDPageContentStream;
import com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission;
import com.tom_roush.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import com.tom_roush.pdfbox.pdmodel.font.PDFont;
import com.tom_roush.pdfbox.pdmodel.font.PDType1Font;
import com.tom_roush.pdfbox.pdmodel.graphics.image.JPEGFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.LosslessFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.PDImageXObject;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDAcroForm;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDCheckBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDComboBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDField;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDListBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDRadioButton;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField;
import com.tom_roush.pdfbox.rendering.ImageType;
import com.tom_roush.pdfbox.rendering.PDFRenderer;
import com.tom_roush.pdfbox.text.PDFTextStripper;
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader;



 /**
     * Fills in a PDF form and saves the result
     */
        
    public  static String fillForm(String data,String c1,String c2,String pathtopdf ) {
        try {
            // Load the document and get the AcroForm
            final File mainFile = new File(pathtopdf);
            PDDocument document = PDDocument.load(mainFile);
            PDDocumentCatalog docCatalog = document.getDocumentCatalog();
            PDAcroForm acroForm = docCatalog.getAcroForm();

            // Fill the text field
            PDTextField field = (PDTextField) acroForm.getField("data");
            field.setValue(data);
        
            PDCheckBox check1 = (PDCheckBox) acroForm.getField("e1");
               PDCheckBox check2 = (PDCheckBox) acroForm.getField("e2");
          
              if (c1 == "1")
                      { ((PDCheckBox) check1).check();}
                else
                        { ((PDCheckBox) check1).unCheck();}

            
              if (c2 == "1")
                      { ((PDCheckBox) check2).check();}
                else
                        { ((PDCheckBox) check2).unCheck();}


            document.save(mainFile);
            document.close();
            
            
        } catch (IOException e) {
            
        }
        return "ok";
    }
#end if

invoked with :
code:
Dim nativemethod As clsJavaInline
    nativemethod.Initialize
    Dim resp As String = nativemethod.FirstMethod

the compilation return no error but when invoke the method "fillForm" i have this error:

error:
Logger connesso a:  Xiaomi M2003J15SC
--------- beginning of system
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
*** mainpage: B4XPage_Created
*** mainpage: B4XPage_Appear
** Activity (main) Resume **
*** nuova verifica: B4XPage_Created [mainpage]
*** mainpage: B4XPage_Disappear [mainpage]
*** nuova verifica: B4XPage_Appear [mainpage]
(MyMap) {data=1692136800000, sede=t, addetto=r, e1=false, e2=false, i1=false, i2=false, v1=false, v2=false, v3=false, p1=false, p2=false, p3=false, l1=false, l2=false, a1=false, r1=false, o1=false, o2=false, d1=false, d2=false, b1=false, b2=false, b3=false}
Error occurred on line: 11 (clsJavaInline)
java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:132)
    at b4a.example.clsjavainline._firstmethod(clsjavainline.java:97)
    at b4a.example.nuova_verifica$ResumableSub_B4XPage_Appear.resume(nuova_verifica.java:488)
    at anywheresoftware.b4a.shell.DebugResumableSub$DelegatableResumableSub.resumeAsUserSub(DebugResumableSub.java:48)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:732)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:351)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:157)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:201)
    at anywheresoftware.b4a.shell.DebugResumableSub$DelegatableResumableSub.resume(DebugResumableSub.java:43)
    at anywheresoftware.b4a.BA.checkAndRunWaitForEvent(BA.java:275)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:150)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:201)
    at anywheresoftware.b4a.keywords.Common$15.run(Common.java:1804)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:236)
    at android.app.ActivityThread.main(ActivityThread.java:7864)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)
Caused by: java.lang.ExceptionInInitializerError
    at com.tom_roush.pdfbox.pdmodel.font.PDFontFactory.createFont(PDFontFactory.java:74)
    at com.tom_roush.pdfbox.pdmodel.PDResources.getFont(PDResources.java:145)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.PDDefaultAppearanceString.processSetFont(PDDefaultAppearanceString.java:169)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.PDDefaultAppearanceString.processOperator(PDDefaultAppearanceString.java:128)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.PDDefaultAppearanceString.processAppearanceStringOperators(PDDefaultAppearanceString.java:104)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.PDDefaultAppearanceString.<init>(PDDefaultAppearanceString.java:86)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.PDVariableText.getDefaultAppearanceString(PDVariableText.java:104)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.AppearanceGeneratorHelper.<init>(AppearanceGeneratorHelper.java:116)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField.constructAppearances(PDTextField.java:263)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.PDTerminalField.applyChange(PDTerminalField.java:228)
    at com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField.setValue(PDTextField.java:219)
    at b4a.example.clsjavainline.fillForm(clsjavainline.java:133)
    ... 24 more
Caused by: java.lang.IllegalArgumentException: java.io.IOException: resource 'com/tom_roush/pdfbox/resources/afm/Times-Roman.afm' not found
    at com.tom_roush.pdfbox.pdmodel.font.Standard14Fonts.getAFM(Standard14Fonts.java:198)
    at com.tom_roush.pdfbox.pdmodel.font.PDFont.<init>(PDFont.java:90)
    at com.tom_roush.pdfbox.pdmodel.font.PDSimpleFont.<init>(PDSimpleFont.java:62)
    at com.tom_roush.pdfbox.pdmodel.font.PDType1Font.<init>(PDType1Font.java:120)
    at com.tom_roush.pdfbox.pdmodel.font.PDType1Font.<clinit>(PDType1Font.java:77)
    ... 36 more
Caused by: java.io.IOException: resource 'com/tom_roush/pdfbox/resources/afm/Times-Roman.afm' not found
    at com.tom_roush.pdfbox.pdmodel.font.Standard14Fonts.loadMetrics(Standard14Fonts.java:129)
    at com.tom_roush.pdfbox.pdmodel.font.Standard14Fonts.getAFM(Standard14Fonts.java:194)
    ... 40 more

can someone help me?
Thanks in advanced
 

DonManfred

Expert
Licensed User
Longtime User
See the first thread below in Similar Threads.

pdfbox can not find the Fonts added to the aar.
Solution is to change/rewrite the pdfbox-source and compile it again. You then can add them as resource in your app.
 
Upvote 0

mike1967

Active Member
Licensed User
Longtime User
See the first thread below in Similar Threads.

pdfbox can not find the Fonts added to the aar.
Solution is to change/rewrite the pdfbox-source and compile it again. You then can add them as resource in your app.
Jar:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
    #AdditionalJar: itextg-5.5.10.jar
   

#End Region

Java:
Sub Class_Globals
    Private joNative As JavaObject
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    joNative = Me
End Sub

Public Sub FirstMethod As String
    Return joNative.RunMethod("FillForm",Array As String("11/12/1967","1","1","1",File.Combine(File.DirInternal,"verifica_template.pdf"),File.Combine(File.DirInternal,"test.pdf")))
End Sub

#if JAVA

/*
 * Example written by Bruno Lowagie in answer to
 * http://stackoverflow.com/questions/36523371
 */

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Bruno Lowagie (iText Software)
 */
public static String FillForm(String data,String c1,String c2,String c3,String pathtopdfsrc,String pathtopdfdest) throws IOException, DocumentException {
   
    File file = new File(pathtopdfdest);
    file.getParentFile().mkdirs();
   
    PdfReader reader = new PdfReader(pathtopdfsrc);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pathtopdfdest));
   
   
    AcroFields form = stamper.getAcroFields();
        if (c1=="1")
        {form.setField("e1", "On");}
        else
        {form.setField("e1", "Off");}
        if (c2=="1")
        {form.setField("e2", "On");}
        else
        {form.setField("e2", "Off");}
        if (c3=="1")
        {form.setField("i1", "On");}
        else
        {form.setField("i2", "Off");}
       
        form.setField("data", data);
       
        stamper.setFormFlattening(true);
        stamper.close();
   
       
        return "ok";
}

#end if

RunMethod:
Dim nativemethod As clsJavaInline
    nativemethod.Initialize
    Dim resp As String = nativemethod.FirstMethod
    Log(resp)

<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="33"/>

Seems to be work fine
https://repo1.maven.org/maven2/com/itextpdf/itextg/5.5.10/

https://kb.itextpdf.com/home/it5kb/examples/filling-out-forms

Is to verify the licence
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
#AdditionalJar: itextg-5.5.10.jar
Legacy notice!


iText 5 is the previous major version of iText’s leading PDF SDK. iText 5 is EOL, and is no longer developed, although we still provide support and security fixes.

BTW: iText is not a free PDF-Creation-Library
 
Last edited:
Upvote 0

mike1967

Active Member
Licensed User
Longtime User
BTW: iText is not a free PDF-Creation-Library
jar:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
    #AdditionalJar: pdfbox-android.aar
   

#End Region

java:
Sub Class_Globals
    Private joNative As JavaObject
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    joNative = Me
End Sub

Public Sub FirstMethod As String
    If File.Exists(File.DirInternal,"test.pdf") Then
    File.Delete(File.DirInternal,"test.pdf")
    End If
    Return joNative.RunMethod("fillForm",Array As String("11/12/1967","1","1",File.Combine(File.DirInternal,"verifica_template.pdf"),File.Combine(File.DirInternal,"test.pdf")))
End Sub

#if JAVA

import android.content.res.AssetManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;

import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.pdmodel.PDDocumentCatalog;
import com.tom_roush.pdfbox.pdmodel.PDPage;
import com.tom_roush.pdfbox.pdmodel.PDPageContentStream;
import com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission;
import com.tom_roush.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import com.tom_roush.pdfbox.pdmodel.font.PDFont;
import com.tom_roush.pdfbox.pdmodel.font.PDType1Font;
import com.tom_roush.pdfbox.pdmodel.graphics.image.JPEGFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.LosslessFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.PDImageXObject;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDAcroForm;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDCheckBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDComboBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDField;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDListBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDRadioButton;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField;
import com.tom_roush.pdfbox.rendering.PDFRenderer;
import com.tom_roush.pdfbox.text.PDFTextStripper;
import com.tom_roush.pdfbox.util.PDFBoxResourceLoader;




 /**
     * Fills in a PDF form and saves the result
     */
       
    public  static String fillForm(String data,String c1,String c2,String pathtopdfsrc,String pathtopdfdest ) {
   
        try {
           
            // Load the document and get the AcroForm
            final File mainFile = new File(pathtopdfsrc);
            final File destFile= new File(pathtopdfdest);
            PDDocument document = PDDocument.load(mainFile);
            PDDocumentCatalog docCatalog = document.getDocumentCatalog();
            PDAcroForm acroForm = docCatalog.getAcroForm();

            // Fill the text field
            PDTextField field = (PDTextField) acroForm.getField("data");
            field.setValue(data);
       
            PDCheckBox check1 = (PDCheckBox) acroForm.getField("e1");
               PDCheckBox check2 = (PDCheckBox) acroForm.getField("e2");
         
              if (c1 == "1")
                      { ((PDCheckBox) check1).check();}
                else
                        { ((PDCheckBox) check1).unCheck();}

           
              if (c2 == "1")
                      { ((PDCheckBox) check2).check();}
                else
                        { ((PDCheckBox) check2).unCheck();}


            document.save(destFile);
            document.close();
           
           
        } catch (IOException e) {
           
        }
        return "ok";
    }
#end if

runmethod:
Dim nativemethod As clsJavaInline
    nativemethod.Initialize
    Dim resp As String = nativemethod.FirstMethod
    Log(resp)

with version 2.1 of pdfbox-android work fine

i download from
https://github.com/VivyTeam/pdfbox-android

i compile it with android studio

This is the AAR file:
https://www.dropbox.com/scl/fi/62q9...roid.aar?rlkey=h4fobwin7cb26cka7lqqi3h1i&dl=0

I Am not able to create a B4A wrapper , can someone help me ?
 
Last edited:
Upvote 0
Top