Martin Zaubi
Martin Zaubi

Reputation: 11

PDFBox on Android doesn't open and fill PDF forms

I have used PDFBox from: Tom Roush PDFBox Android and imported it into the build.gradel: dependencies {compile 'org.apache:pdfbox-android:1.8.9.0'}

But everytime I run the Activity just the Toast appears, but the filled PDF file can't be found. The PDF is located in the /assets folder. I have created this folder by myself in /app/src/main/assets. I use Android Studio.

The Activity:

public class GwmProbenActivity extends AppCompatActivity {

DatabaseHelperAllgemeineDaten myDb;
public String stOrt;
public String stProgramm;
public String stName;
public String stDatum;
File root;

AssetManager assetManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_proben);

    Intent intent = getIntent();
    stDatum = intent.getStringExtra("datum");
    myDb = new DatabaseHelperAllgemeineDaten(this);

    PDFBoxResourceLoader.init(getApplicationContext());
    root = android.os.Environment.getExternalStorageDirectory();
    assetManager = getAssets();
}


public void fillPDF() {
    try {
        // Load the document and get the AcroForm
        PDDocument document = PDDocument.load(assetManager.open("Vorlage_GWM-   Protokoll.pdf"));
        PDDocumentCatalog docCatalog = document.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();

        // Fill the text field
        PDFieldTreeNode field = acroForm.getField("ProbenahmeDatum");
        field.setValue(stDatum);

        String path = root.getAbsolutePath() + "/Download/Vorlage_GWM-Protokoll1";
        Toast.makeText(this,"Saved filled form to " +    path,Toast.LENGTH_LONG).show();
        document.save(path);
        document.close();
    }
    catch (IOException ioe)
    {
        ioe.printStackTrace();
    }
}

public void speichern (View v) {
    fillPDF();
}
}

Upvotes: 0

Views: 866

Answers (1)

Martin Zaubi
Martin Zaubi

Reputation: 11

I have added the ".pdf" and moved the Toast behind the document.close(). Now the Toast doesn't show up and I can't find the file in storage/emulated/0/Download.

Since API 23+ you need to check for permissions in the Activity. This is was the solution.

Upvotes: 1

Related Questions