如何在Android中获取PDF的当前页码

时间:2016-11-08 12:05:23

标签: android pdf

我必须在我的Android应用程序中实现自定义PDF查看器,我已经实现了这个:

https://github.com/barteksc/AndroidPdfViewer

要打开我的pdf,我使用了这个功能:

/* Load PDF in the activity */
private void openPDF(){
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/Download/verbale.pdf");
    PDFView pdfView = (PDFView) findViewById(R.id.pdfView);

    pdfView.fromFile(file)
            .defaultPage(0)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .onPageChange(this)
            .scrollHandle(new DefaultScrollHandle(this))
            .load();
}

PDF已正确呈现,但现在我需要在滚动期间获取页面的页码。

我怎么能这样做?

我试过用这个:

pdfView.getCurrentPage()
pdfView.getPageCount()

但不是没有用......

 @Override
    public void loadComplete(int nbPages) {
        totalPages = nbPages;
    }

@Override
public void onPageChanged(int page, int pageCount) {
    //Page contains che current page
}

3 个答案:

答案 0 :(得分:3)

您可以查看AndroidPdfViewer的官方示例:Link

从这个例子中看看这两个片段:

1)创建PDFView:

pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();

2)并实现onPageChanged(..):

@Override
public void onPageChanged(int page, int pageCount) {
    pageNumber = page;
    //do what you want with the pageNumber
}

也不要忘记implement OnPageChangeListener

答案 1 :(得分:2)

@EActivity(R.layout.activity_pdf_app_bar_main)
@OptionsMenu(R.menu.options)
public class PDFActivity extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener
{
    private static final String TAG = PDFActivity.class.getSimpleName();
    private final static int REQUEST_CODE = 42;
    public static final int PERMISSION_CODE = 42042;
    public static final String SAMPLE_FILE = "myPDF.pdf";
    public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";
    private int mCurrentPage = 0;
    private final static String KEY_CURRENT_PAGE = "current_page";
    private ProgressDialog progressDialog;
    @ViewById
    PDFView pdfView;
    @NonConfigurationInstance
    Uri uri;
    @NonConfigurationInstance
    String pdfFileName;
    @OptionsItem(R.id.pickFile)
    void pickFile()
    {
        int permissionCheck = ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE}, PERMISSION_CODE);
            return;
        }
        launchPicker();
    }
    void launchPicker()
    {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/pdf");
        try
        {
            startActivityForResult(intent, REQUEST_CODE);
        }
        catch (ActivityNotFoundException e)
        {
            Toast.makeText(this, R.string.toast_pick_file_error, Toast.LENGTH_SHORT).show();
        }
    }
    @AfterViews
    void afterViews()
    {
        pdfView.setBackgroundColor(Color.WHITE);
        if (uri != null)
        {
            displayFromUri(uri);
        }
        else
        {
            displayFromAsset(SAMPLE_FILE);
        }
        setTitle(pdfFileName);
    }

    private void displayFromAsset(String assetFileName)
    {
        pdfFileName = assetFileName;
        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(mCurrentPage)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .enableDoubletap(true)
                .password(null)
                .enableAntialiasing(true)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onPageScroll(new OnPageScrollListener() {
                    @Override
                    public void onPageScrolled(int page, float positionOffset) {
                        Log.d(TAG, "onPageScrolled: page " + page + " positionOffset " + positionOffset);
                    }
                })
                .onRender(new OnRenderListener()
                {
                    @Override
                    public void onInitiallyRendered(int nbPages, float pageWidth, float pageHeight)
                    {
                        pdfView.fitToWidth(mCurrentPage);
                    }
                })
                .onLoad(new OnLoadCompleteListener() {
                    @Override
                    public void loadComplete(int nbPages) {
                        Log.d(TAG, "loadComplete: totalPages " + nbPages);
                    }
                })
                .onError(new OnErrorListener() {
                    @Override
                    public void onError(Throwable t) {
                        Log.d(TAG, " onError");
                    }
                })
                .scrollHandle(new DefaultScrollHandle(this))
                .spacing(2)
                .load();
    }
    private void displayFromUri(Uri uri)
    {
        pdfFileName = getFileName(uri);
        pdfView.fromUri(uri)
                .defaultPage(mCurrentPage)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }
    @OnActivityResult(REQUEST_CODE)
    public void onResult(int resultCode, Intent intent)
    {
        if (resultCode == RESULT_OK)
        {
            uri = intent.getData();
            displayFromUri(uri);
        }
    }
    @Override
    public void onPageChanged(int page, int pageCount)
    {
        mCurrentPage = page;
        setTitle(String.format("%s %s / %s", "Page Number", page + 1, pageCount));
    }
    public String getFileName(Uri uri)
    {
        String result = null;
        if (uri.getScheme().equals("content"))
        {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            try
            {
                if (cursor != null && cursor.moveToFirst())
                {
                    result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.close();
                }
            }
        }
        if (result == null)
        {
            result = uri.getLastPathSegment();
        }
        return result;
    }
    @Override
    public void loadComplete(int nbPages)
    {
        if (mCurrentPage >= 0)
        {
            pdfView.jumpTo(mCurrentPage);
        }
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        Log.e(TAG, "title = " + meta.getTitle());
        Log.e(TAG, "author = " + meta.getAuthor());
        Log.e(TAG, "subject = " + meta.getSubject());
        Log.e(TAG, "keywords = " + meta.getKeywords());
        Log.e(TAG, "creator = " + meta.getCreator());
        Log.e(TAG, "producer = " + meta.getProducer());
        Log.e(TAG, "creationDate = " + meta.getCreationDate());
        Log.e(TAG, "modDate = " + meta.getModDate());
        Log.d(TAG, "totalPages " + nbPages);
        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 + "-");
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults)
    {
        if (requestCode == PERMISSION_CODE)
        {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                launchPicker();
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null)
        {
            mCurrentPage = savedInstanceState.getInt(KEY_CURRENT_PAGE);
        }
        else
        {
            mCurrentPage = -1;
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        mCurrentPage = savedInstanceState.getInt(KEY_CURRENT_PAGE);
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_CURRENT_PAGE, mCurrentPage);
    }
}

答案 2 :(得分:1)

有时@inherits LayoutComponentBase @inject IJSRuntime JSRuntime @using System.ComponentModel.DataAnnotations <div class="sidebar"> <NavMenu /> </div> <MatDialog @bind-IsOpen="@DialogIsOpen"> <EditForm EditContext="EditContext" OnValidSubmit="@HandleValidSubmit"> <DataAnnotationsValidator /> <p> <MatTextField Style="margin:2px;" Label="Password" @bind- Value="passWordModel.PassWord" Type="password" /> <ValidationMessage For="@(() => passWordModel.PassWord)" /> </p> <MatButton Class="cancelbtn" Type="reset" @onclick="@CancelClicked">Cancel</MatButton> <MatButton Type="submit">OK</MatButton> </EditForm> </MatDialog> <div class="main"> <div class="top-row px-4"> <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a> <button type="button" class="btn btn-success" @onclick="@ExitClicked">Close</button> </div> <div class="content px-4"> @Body </div> </div> 无法获取当前页码。

@code{
    EditContext EditContext { get; set; }
    PassWordModel passWordModel = new PassWordModel();
        public bool DialogIsOpen { get; set; } = false;

    public class PassWordModel
    {
        [CustomValidation(typeof(PassWordModel), nameof(ValidatePassWord))]
        public string PassWord { get; set; }

        public static ValidationResult ValidatePassWord(string password, ValidationContext vc)
        {

            return string.Equals("1234", password)
                ? ValidationResult.Success
                : new ValidationResult("The password is not correct.", new[] { vc.MemberName 
});
        }
    }

    protected override void OnInitialized()
    {
        EditContext = new EditContext(passWordModel);
        base.OnInitialized();
    }

    void ExitClicked()
    {
        DialogIsOpen = true;
    }

    void CancelClicked()
    {
        passWordModel.PassWord = null;
        EditContext = new EditContext(passWordModel);

        DialogIsOpen = false;

    }

    private async void HandleValidSubmit()
    {
        System.Diagnostics.Debug.WriteLine("HandleValidSubmit!");

        try
        {
            await JSRuntime.InvokeVoidAsync("winclose");
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e.Message);
        }

    }
}