I’m developing an Android application where I need to merge multiple PDF files that are downloaded and stored in the device’s Downloads directory. After merging, I need to delete all the original files except the newly merged one. I would like to do this using Java in Android Studio.
The downloaded files are not corrupted, as I can open them manually without any issues. However, I still keep encountering the Pdf startxref not found error. It seems to be related to improper handling during the merge process, even though the PDFs open fine on their own.
Can anyone help me understand the cause of this error and how to resolve it? Additionally, any suggestions on how to delete the original files after the merge would be greatly appreciated!
Here’s the code I am using to merge the PDFs:
List<String> filePath2 = new ArrayList<>(); // To store downloaded file
private void mergePdfs(String filePath1) {
if (!hasStoragePermissions()) {
requestPermission();
} else {
String newFilePath = null;
PdfCopy copy = null;
Document document = null;
try {
String newFileName = patientData.getFullname() + new SimpleDateFormat("yyyyMMddHHmmSS").format(new Date()) + ".pdf".replace(" ", "");
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), newFileName);
file.createNewFile();
newFilePath = file.getAbsolutePath();
document = new Document();
copy = new PdfCopy(document, new FileOutputStream(newFilePath));
document.open();
if(new File(filePath1).exists()) {
PdfReader reader1 = null;
try {
reader1 = new PdfReader(filePath1);
if (reader1.isOpenedWithFullPermissions()) {
copy.addDocument(reader1);
}
} finally {
if (reader1 != null) {
reader1.close();
}
new File(filePath1).delete();
}
}
for (String path : filePath2) {
if(new File(path).exists()) {
PdfReader reader = null;
try {
reader = new PdfReader(path);
if (reader.isOpenedWithFullPermissions()) {
copy.addDocument(reader);
}
} finally {
if (reader != null) {
reader.close();
}
}
new File(path).delete();
}
}
document.close();
copy.close();
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "PDF file generated successfully.", Snackbar.LENGTH_LONG).
setTextColor(Color.WHITE).setActionTextColor(Color.WHITE).setBackgroundTint(getResources().getColor(R.color.greensnack));
View snackbarView = snackbar.getView();
TextView textView = (TextView) snackbarView.findViewById(com.google.android.material.R.id.snackbar_action);
textView.setText("");
textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.snackbar_close, 0);
textView.setGravity(Gravity.RIGHT);
snackbar.show();
} catch (Exception e) {
if (newFilePath != null) {
new File(newFilePath).delete();
}
if(new File(filePath1).exists()) {
new File(filePath1).delete();
}
for (String path : filePath2) {
if(new File(path).exists()){
new File(path).delete();
}
}
showSnackbar("Something went wrong while generating PDF.");
System.out.println("Merge error" + e);
}
}
}
}
1