Как прочитать PDF-файл в Android-студии - PullRequest
0 голосов
/ 20 сентября 2019

Я новичок в разработке для Android, я хочу сделать приложение для Android, которое может читать PDF-файлы.у меня есть pdf-файлы с большими конкурсами (каждый pdf-файл размером около 60 МБ), так как я искал, мне нужно хранить файлы на сервере, например на веб-сайте или что-то еще (я не знаю точно, это то, что мне нужно), если ябудет хранить файлы на сервере. Как я могу заставить пользователей читать файлы PDF, не загружая их на свои телефоны?,Я обнаружил, что мне нужно использовать веб-просмотр, но я не уверен, что это правильный путь.и если то, что я думаю, является неправильным, скажите, пожалуйста, как это правильно. Я надеюсь, что кто-то поможет мне, потому что я ищу это, и я не нахожу никакого конкретного ответа. Спасибо

1 Ответ

0 голосов
/ 20 сентября 2019

Вы можете просмотреть PDF-файл в проекте Android по-разному.Я опишу некоторые из них здесь -

1.Использование библиотеки: Шаги ниже: Установка Добавить в build.gradle : implementation 'com.github.barteksc:android-pdf-viewer:2.8.2' ProGuard Если вы используете ProGuard, добавьте следующее правило в файл конфигурации proguard:-keep class com.shockwave.** Включить PDFView в макет <com.github.barteksc.pdfviewer.PDFView android:id="@+id/pdfView" android:layout_width="match_parent" android:layout_height="match_parent"/>Дополнительная ссылка здесь 2.Загрузить PDF-URL в веб-просмотр:

webview = (WebView)findViewById(R.id.webview);
    progressbar = (ProgressBar) findViewById(R.id.progressbar);
    webview.getSettings().setJavaScriptEnabled(true);
    String filename = file_url_with_name;
    webview.loadUrl(file_url + filename);

    webview.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            // do your stuff here
            progressbar.setVisibility(View.GONE);
        }
    });

3.Вручную показать файл PDF в Imageview

// Example for creating manual PDF viewer into imageview used butterknife view binding<br/>

public class PdfRenderActivity extends AppCompatActivity {

    @BindView(R.id.pdf_image) ImageView imageViewPdf;
    @BindView(R.id.button_pre_doc) FloatingActionButton prePageButton;
    @BindView(R.id.button_next_doc) FloatingActionButton nextPageButton;

    private static final String FILENAME = "report.pdf";

    private int pageIndex;
    private PdfRenderer pdfRenderer;
    private PdfRenderer.Page currentPage;
    private ParcelFileDescriptor parcelFileDescriptor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_render);
        ButterKnife.bind(this);
        pageIndex = 0;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onStart() {
        super.onStart();
        try {
            openRenderer(getApplicationContext());
            showPage(pageIndex);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onStop() {
        try {
            closeRenderer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onStop();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @OnClick(R.id.button_pre_doc)
    public void onPreviousDocClick(){
        showPage(currentPage.getIndex() - 1);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @OnClick(R.id.button_next_doc)
    public void onNextDocClick(){
        showPage(currentPage.getIndex() + 1);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void openRenderer(Context context) throws IOException {
        // In this sample, we read a PDF from the assets directory.
        File file = new File(context.getCacheDir(), FILENAME);
        if (!file.exists()) {
            // Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
            // the cache directory.
            InputStream asset = context.getAssets().open(FILENAME);
            FileOutputStream output = new FileOutputStream(file);
            final byte[] buffer = new byte[1024];
            int size;
            while ((size = asset.read(buffer)) != -1) {
                output.write(buffer, 0, size);
            }
            asset.close();
            output.close();
        }
        parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        // This is the PdfRenderer we use to render the PDF.
        if (parcelFileDescriptor != null) {
            pdfRenderer = new PdfRenderer(parcelFileDescriptor);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void closeRenderer() throws IOException {
        if (null != currentPage) {
            currentPage.close();
        }
        pdfRenderer.close();
        parcelFileDescriptor.close();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void showPage(int index) {
        if (pdfRenderer.getPageCount() <= index) {
            return;
        }
        // Make sure to close the current page before opening another one.
        if (null != currentPage) {
            currentPage.close();
        }
        // Use `openPage` to open a specific page in PDF.
        currentPage = pdfRenderer.openPage(index);
        // Important: the destination bitmap must be ARGB (not RGB).
        Bitmap bitmap = Bitmap.createBitmap(currentPage.getWidth(), currentPage.getHeight(),
                Bitmap.Config.ARGB_8888);
        // Here, we render the page onto the Bitmap.
        // To render a portion of the page, use the second and third parameter. Pass nulls to get
        // the default result.
        // Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
        currentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        // We are ready to show the Bitmap to user.
        imageViewPdf.setImageBitmap(bitmap);
        updateUi();
    }

    /**
     * Updates the state of 2 control buttons in response to the current page index.
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void updateUi() {
        int index = currentPage.getIndex();
        int pageCount = pdfRenderer.getPageCount();
        prePageButton.setEnabled(0 != index);
        nextPageButton.setEnabled(index + 1 < pageCount);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public int getPageCount() {
        return pdfRenderer.getPageCount();
    }

}

Документ здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...