Показать обложку в формате pdf в Listview - PullRequest
0 голосов
/ 12 мая 2018

У меня есть читатель PDF с списком с иконкой PDF и как сделать так, чтобы обложка pdf показывалась в виде списка вот так?

Example 1

или

Example 2

исходный код: https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/

Как изменить значок PDF для отображения PDF в списке?

спасибо

Основная активность.java

ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;

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


}

private void init() {
    lv_pdf = (ListView) findViewById(R.id.lv_pdf);
    dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Pdf");
    fn_permission();
    lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int i, long l) {

            Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
            intent.putExtra("position", i);
            startActivity(intent);
            Log.e("Position", i + "Pdf");
        }
    });
}

public static ArrayList<File> getfile(File dir) {
    File listFile[] = dir.listFiles();
    if (listFile != null && listFile.length > 0) {
        for (int i = 0; i < listFile.length; i++) {
            if (listFile[i].isDirectory()) {
                getfile(listFile[i]);
            } else {
                boolean booleanpdf = false;
                if (listFile[i].getName().endsWith(".pdf")) {
                    for (int j = 0; j < fileList.size(); j++) {
                        if (fileList.get(j).getName().equals(listFile[i].getName())) {
                            booleanpdf = true;
                        } else {

                        }
                    }
                    if (booleanpdf) {
                        booleanpdf = false;
                    } else {
                        fileList.add(listFile[i]);
                    }
                }

            }
        }

    }
    return fileList;
}

private void fn_permission() {
    if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

        if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {


        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSIONS);

        }
    } else {
        boolean_permission = true;

        getfile(dir);

        obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
        lv_pdf.setAdapter(obj_adapter);

    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSIONS) {

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            boolean_permission = true;
            getfile(dir);

            obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
            lv_pdf.setAdapter(obj_adapter);

        } else {

            Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();

        }
    }
}

PdfActivity

 public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG = "PdfActivity";
int position = -1;

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

private void init() {
    pdfView = (PDFView) findViewById(R.id.pdfView);

    //position = Environment.getExternalStorageDirectory()+"/sdcard/Pdf"
    position = getIntent().getIntExtra("position", -1);
    displayFromSdcard();
    //String position = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Pdf/";
}

private void displayFromSdcard() {
    pdfFileName = MainActivity.fileList.get(position).getName();

    pdfView.fromFile(MainActivity.fileList.get(position))
            .defaultPage(pageNumber)
            .enableSwipe(true)
            .password("123456")
            .swipeHorizontal(false)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(new DefaultScrollHandle(this))
            .load();
}


@Override
public void onPageChanged(int page, int pageCount) {
    pageNumber = page;
    setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}


@Override
public void loadComplete(int nbPages) {
    PdfDocument.Meta meta = pdfView.getDocumentMeta();
    printBookmarksTree(pdfView.getTableOfContents(), "-");

}

public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
    for (PdfDocument.Bookmark b : tree) {

        Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

        if (b.hasChildren()) {
            printBookmarksTree(b.getChildren(), sep + "-");
        }
    }
}

PdfAdapter

 Context context;
ViewHolder viewHolder;
ArrayList<File> al_pdf;

public PDFAdapter(Context context, ArrayList<File> al_pdf) {
    super(context, R.layout.adapter_pdf, al_pdf);
    this.context = context;
    this.al_pdf = al_pdf;

}


@Override
public int getItemViewType(int position) {
    return position;
}

@Override
public int getViewTypeCount() {
    if (al_pdf.size() > 0) {
        return al_pdf.size();
    } else {
        return 1;
    }
}

@Override
public View getView(final int position, View view, ViewGroup parent) {


    if (view == null) {
        view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_pdf, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.tv_filename = (TextView) view.findViewById(R.id.tv_name);

        view.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) view.getTag();

    }

    viewHolder.tv_filename.setText(al_pdf.get(position).getName());
    return view;

}

public class ViewHolder {

    TextView tv_filename;


}

1 Ответ

0 голосов
/ 13 мая 2018

Вы можете создать изображение, создав растровое изображение первой страницы PDF.Затем сохраните изображение в каталоге вашего приложения для последующего использования.Вы можете использовать PdfiumCore (который является зависимостью от barteks PdfView) для генерации изображения.

Вы можете использовать следующее:

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

class PDFUtils {

  static String generateAndSaveFirstPageImage(Context context, Uri uri, long bookId) {
    try {
      ParcelFileDescriptor fd = context.getContentResolver().openFileDescriptor(uri, "r");
      int pageNum = 0;
      PdfiumCore pdfiumCore = new PdfiumCore(context);
      try {
        PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
        pdfiumCore.openPage(pdfDocument, 0); // open first page for cover.

        int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNum);
        int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNum);

        // do a fit center to 1920x1080
        //double scaleBy = Math.min(1080 / (double) width, //
        //    1920 / (double) height);
        //width = (int) (width * scaleBy);
        //height = (int) (height * scaleBy);

        // ARGB_8888 - best quality, high memory usage, higher possibility of OutOfMemoryError
        // RGB_565 - little worse quality, twice less memory usage
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        pdfiumCore.renderPageBitmap(pdfDocument, bitmap, pageNum, 0, 0, width, height);
        //if you need to render annotations and form fields, you can use
        //the same method above adding 'true' as last param

        String fileName = bookId + ".jpg";
        // save the file
        File outputFile = new File(context.getFilesDir(), fileName);
        FileOutputStream outputStream = new FileOutputStream(outputFile);

        // a bit long running
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

        outputStream.close();
        fd.close();
        pdfiumCore.closeDocument(pdfDocument); // important!

        return fileName;
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
}

Затем вам нужно использовать класс с помощью следующего:

long bookId = 2345; // your book identifier
Url yourPdfUrl; // url of pdf in your device
PdfUtils.generateAndSaveFirstPageImage(context, yourPdfUrl, bookId);

После того, как вы сохранили изображение, вы можете снова использовать изображение с чем-то вроде этого:

String imagePath = getFilesDir() + "/" + yourBookId + ".jpg";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...