PDf工具

package com.atomic.moretool;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListPopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.documentfile.provider.DocumentFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PdfTool extends AppCompatActivity implements View.OnClickListener {
    private ImageView imageView;
    private static ParcelFileDescriptor mFileDescriptor = null;
    private static PdfRenderer pdfRender = null;
    private static PdfRenderer.Page page = null;
    private static int totalpages;
    private int count=0;
    private int btncount=2;
    private TextView savepdfpath;
    private TextView pagenum;
    private TextView savepdftopicfolderpath;
    private EditText inputjumppage;
    private boolean isImageViewNotNull=false;
    private Button jumppage,superpage,nextpage,shareonepic,transforpic,openpdf,batchconversion,operatepdf;
    private ProgressBar ShowPdfToPicProgress;
    private ProgressBar OneProgress;
    private ExecutorService executorService;
    private DocumentFile[] files;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdftool);
        imageView=findViewById(R.id.showpic);
        savepdfpath=findViewById(R.id.savepdfpath);//保存pdf路径
        inputjumppage=findViewById(R.id.inputjumppage);//输入跳转页码
        jumppage=findViewById(R.id.jumppage);
        superpage=findViewById(R.id.superpage);
        nextpage=findViewById(R.id.nextpage);
        shareonepic=findViewById(R.id.shareonepic);
        transforpic=findViewById(R.id.transforpic);
        openpdf=findViewById(R.id.openpdf);
        batchconversion=findViewById(R.id.batch_conversion);
        operatepdf=findViewById(R.id.operatepdf);
        pagenum=findViewById(R.id.pagenum);//显示当前页码
        ShowPdfToPicProgress=findViewById(R.id.showpdftopicprogress);
        OneProgress=findViewById(R.id.one_progress);
        savepdftopicfolderpath=findViewById(R.id.savepdftopicfolderpath);//保存pdf转pic的文件夹路径
        executorService= Executors.newFixedThreadPool(1);
        //获取屏幕宽高
        DisplayMetrics metrics = new DisplayMetrics();
        Display display = getWindowManager().getDefaultDisplay();
        display.getRealMetrics(metrics);
        int screenWidth = metrics.widthPixels;
        int screenHeight = metrics.heightPixels;
        imageView.setMaxHeight(screenHeight);
        imageView.setMaxWidth(screenWidth);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        String pdfpath=savepdfpath.getText().toString().trim();//获取pdf路径
        switch (v.getId()){
            case R.id.operatepdf:
                btncount++;
                if (!String.valueOf(btncount).matches("([1-9]\\d*)?[02468]")){
                    //Log.i(tag,"奇数-展开");
                    inputjumppage.setVisibility(View.VISIBLE);
                    jumppage.setVisibility(View.VISIBLE);
                    superpage.setVisibility(View.VISIBLE);
                    nextpage.setVisibility(View.VISIBLE);
                    shareonepic.setVisibility(View.VISIBLE);
                    transforpic.setVisibility(View.VISIBLE);
                    openpdf.setVisibility(View.VISIBLE);
                    batchconversion.setVisibility(View.VISIBLE);
                    operatepdf.setText("折叠");
                }else{
                    //Log.i(tag,"偶数-折叠");
                    inputjumppage.setVisibility(View.INVISIBLE);
                    jumppage.setVisibility(View.INVISIBLE);
                    superpage.setVisibility(View.INVISIBLE);
                    nextpage.setVisibility(View.INVISIBLE);
                    shareonepic.setVisibility(View.INVISIBLE);
                    transforpic.setVisibility(View.INVISIBLE);
                    openpdf.setVisibility(View.INVISIBLE);
                    batchconversion.setVisibility(View.INVISIBLE);
                    operatepdf.setText("展开");
                }
                break;
            case R.id.nextpage:
                if (isImageViewNotNull){
                    if (count<totalpages-1){
                        count++;
                        TransferPdfToBitmap(pdfpath,count);
                    }else{
                        Toast.makeText(this, "已经是最后一页", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(this, "还没有选择pdf文件", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.superpage:
                if (isImageViewNotNull){
                    if (count>0){
                        count--;
                        TransferPdfToBitmap(pdfpath,count);
                    }else{
                        Toast.makeText(this, "已经是第一页", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(this, "还没有选择pdf文件", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.jumppage:
                if (isImageViewNotNull){
                    String x=inputjumppage.getText().toString().trim();
                    if (!x.equals("")){
                        int jumpnum=Integer.parseInt(x);//获取跳转页面数
                        if (jumpnum>0 && jumpnum<=totalpages){
                            TransferPdfToBitmap(pdfpath,jumpnum-1);
                        }else{
                            Toast.makeText(this, "超出跳转范围", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(this, "没有输入跳转页数", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(this, "还没有选择pdf文件", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.shareonepic:
                if (isImageViewNotNull){
                    //分享pdf单张图片
                    Bitmap bm =((BitmapDrawable) imageView.getDrawable()).getBitmap();
                    //先保存成png文件
                    File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"temporary.png");
                    try {
                        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(file));
                        bm.compress(Bitmap.CompressFormat.PNG,100,bos);
                        bos.flush();
                        bos.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    //再获取文件分享
                    Uri uri= FileProvider.getUriForFile(this,getPackageName()+".fileprovider",file);
                    Intent intent = new Intent(Intent.ACTION_SEND);//创建发送意图
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                    intent.setType("image/*");
                    startActivity(Intent.createChooser(intent, "分享图片"));
                }else{
                    Toast.makeText(this, "还没有选择pdf文件", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.transforpic:
                if(isImageViewNotNull){
                    int i=0;
                    doAsyncCode(savepdfpath.getText().toString().trim(),i);
                }else{
                    Toast.makeText(this, "还没有选择pdf文件", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.openpdf:
                Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent,120);
                break;
            case R.id.batch_conversion:
                ShowPdfToPicProgress.setProgress(0);
                OneProgress.setProgress(0);
                Intent intent1=new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivityForResult(intent1,121);
                break;
            default:
                Toast.makeText(this, "异常错误,联系开发人员", Toast.LENGTH_SHORT).show();
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        if (requestCode==120 && resultCode==RESULT_OK){
            Uri uri=data.getData();
            String path= GetPath.getFilePath(this,uri,"pdf");
            if (path!=null){
                try {
                    savepdfpath.setText(path.trim());//将获取到的pdf文件路径放入textview中
                    TransferPdfToBitmap(path,0);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else if (requestCode==121 && resultCode==RESULT_OK){
            Uri uri=data.getData();
            files= Objects.requireNonNull(DocumentFile.fromTreeUri(this,uri)).listFiles();
            ShowPdfToPicProgress.setMax(files.length);//设置总进度条最大值
            for(int i=0;i<files.length;i++){
                try {
                    String path=GetPath.getFilePath(files[i].getUri());
                    doAsyncCode(path,i);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
    private void doAsyncCode(String path,int i){
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                TransferAllPdfToBitmap(path);
                ShowPdfToPicProgress.setProgress(i+1);//设置总进度条进度
                doOnUiCode();
            }
        });
    }
    private void doOnUiCode(){
        Handler uiThread=new Handler(Looper.getMainLooper());
        uiThread.post(new Runnable() {
            @Override
            public void run() {
                //更新UI
                if (ShowPdfToPicProgress.getProgress()==files.length){
                    ToastUtils.showShortToast(getApplicationContext(),"转换完成");
                }
            }
        });
    }
    @SuppressLint("SetTextI18n")
    private void TransferPdfToBitmap(String path, int num){
        try {
            mFileDescriptor = ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY);
            if (mFileDescriptor != null) {
                pdfRender = new PdfRenderer(mFileDescriptor);
                if (pdfRender.getPageCount() > 0) {
                    totalpages = pdfRender.getPageCount();
                    if (page!=null)
                        page.close();
                    page = pdfRender.openPage(num);
                    Bitmap bmp = Bitmap.createBitmap(page.getWidth() * 2, page.getHeight() * 2, Bitmap.Config.ARGB_8888);
                    page.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
                    imageView.setImageBitmap(bmp);
                    isImageViewNotNull=true;
                    int y=num+1;
                    GestrueDetection.gestruedetection(imageView);//手势缩放移动图片
                    pagenum.setText("页码:"+y+"/"+totalpages);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @SuppressLint("SetTextI18n")
    private void TransferAllPdfToBitmap(String path){
        try {
            String folderpath=GetPath.getFilepath(path)+"/";
            File file1=new File(folderpath);
            if (!file1.exists()){
                file1.mkdirs();
            }
            mFileDescriptor = ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY);
            if (mFileDescriptor != null) {
                pdfRender = new PdfRenderer(mFileDescriptor);
                if (pdfRender.getPageCount() > 0) {
                    totalpages = pdfRender.getPageCount();
                    OneProgress.setMax(totalpages);//设置进度条最大值
                    Log.i("tag",String.valueOf(totalpages));
                    for (int i=0;i<totalpages;i++){
                        if (page!=null)
                            page.close();
                        page = pdfRender.openPage(i);
                        Bitmap bmp = Bitmap.createBitmap(page.getWidth() * 2, page.getHeight() * 2, Bitmap.Config.ARGB_8888);
                        page.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
                        OneProgress.setProgress(i+1);//设置图片转换进度
                        String filename= i+1 +".png";
                        File file=new File(folderpath,filename);
                        try {
                            BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(file));
                            bmp.compress(Bitmap.CompressFormat.PNG,70,bos);
                            bos.flush();
                            bos.close();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            e.printStackTrace();
        }
    }

    private void OperatePdf(Button button) {

        final String[] list={"打开Pdf","全转图片"};
        final ListPopupWindow listPopupWindow;
        listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list));
        listPopupWindow.setWidth(350);
        listPopupWindow.setAnchorView(button);//显示在该按钮控件上方
        listPopupWindow.setModal(true);

        listPopupWindow.setOnItemClickListener((adapterView, view, i, l) -> {
            switch (list[i]) {
                case "打开Pdf":
                    Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent,100);
                    break;
                case "全转图片":
                    if(isImageViewNotNull){
                        Intent intent1=new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                        startActivityForResult(intent1,101);
                    }else{
                        Toast.makeText(this, "还没有选择pdf文件", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    Toast.makeText(this, "操作失败,联系开发人员", Toast.LENGTH_SHORT).show();
                    break;
            }
            listPopupWindow.dismiss();
        });
        listPopupWindow.show();
    }
    @Override
    protected void onResume(){
        super.onResume();
    }
    @Override
    protected void onStop(){
        super.onStop();
        /*if (!executorService.isShutdown()){
            executorService.shutdownNow();
        }*/
    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
        try {
            mFileDescriptor.close();
            pdfRender.close();
            page.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}


<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/showpic"
        android:clickable="true"
        android:focusable="true"
        android:scaleType="matrix"
        android:adjustViewBounds="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <TextView
        android:id="@+id/pagenum"
        android:layout_marginTop="50sp"
        android:layout_marginStart="10sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/savepdftopicfolderpath"
        android:text="0%"
        android:textSize="8sp"
        android:visibility="invisible"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="SmallSp" />
    <LinearLayout
        android:layout_margin="10sp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:gravity="center"
            android:layout_marginBottom="5sp"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_weight="0"
                android:text="总进度: "
                android:textSize="10sp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                tools:ignore="SmallSp" />
            <ProgressBar
                android:layout_weight="1"
                android:id="@+id/showpdftopicprogress"
                android:progress="0"
                android:maxHeight="8sp"
                android:minHeight="8sp"
                style="@style/Widget.AppCompat.ProgressBar.Horizontal"
                android:progressDrawable="@drawable/progressbar_show_page_num"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <LinearLayout
            android:gravity="center"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_weight="0"
                android:text="单进度: "
                android:textSize="10sp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                tools:ignore="SmallSp" />
            <ProgressBar
                android:layout_weight="1"
                android:id="@+id/one_progress"
                android:progress="0"
                android:maxHeight="8sp"
                android:minHeight="8sp"
                style="@style/Widget.AppCompat.ProgressBar.Horizontal"
                android:progressDrawable="@drawable/progressbar_show_page_num"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:layout_gravity="bottom"
        android:orientation="vertical"
        android:layout_marginStart="10sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <EditText
            android:layout_marginBottom="8sp"
            android:text="@string/_1"
            android:textColor="@color/red"
            android:background="@drawable/raidus"
            android:visibility="invisible"
            android:textAlignment="center"
            android:inputType="number"
            android:textSize="16sp"
            android:id="@+id/inputjumppage"
            android:layout_width="50sp"
            android:layout_height="35sp"/>
        <Button
            android:layout_marginBottom="8sp"
            android:background="@drawable/button_style"
            android:visibility="invisible"
            android:id="@+id/jumppage"
            android:text="跳页"
            android:onClick="onClick"
            android:textSize="12sp"
            android:layout_width="50sp"
            android:layout_height="wrap_content"/>
        <Button
            android:layout_marginBottom="8sp"
            android:background="@drawable/button_style"
            android:visibility="invisible"
            android:id="@+id/shareonepic"
            android:textSize="12sp"
            android:text="分享"
            android:onClick="onClick"
            android:layout_width="50sp"
            android:layout_height="wrap_content"/>
        <Button
            android:layout_marginBottom="8sp"
            android:background="@drawable/button_style"
            android:id="@+id/transforpic"
            android:text="转图"
            android:visibility="invisible"
            android:textSize="12sp"
            android:onClick="onClick"
            android:layout_width="50sp"
            android:layout_height="wrap_content"
            tools:ignore="RtlHardcoded" />
        <Button
            android:layout_marginBottom="8sp"
            android:background="@drawable/button_style"
            android:visibility="invisible"
            android:id="@+id/superpage"
            android:textSize="12sp"
            android:text="上页"
            android:onClick="onClick"
            android:layout_width="50sp"
            android:layout_height="wrap_content"/>
        <Button
            android:layout_marginBottom="8sp"
            android:background="@drawable/button_style"
            android:visibility="invisible"
            android:id="@+id/nextpage"
            android:textSize="12sp"
            android:text="下页"
            android:onClick="onClick"
            android:layout_width="50sp"
            android:layout_height="wrap_content"/>
        <Button
            android:layout_marginBottom="8sp"
            android:background="@drawable/button_style"
            android:id="@+id/openpdf"
            android:text="打开"
            android:visibility="invisible"
            android:textSize="12sp"
            android:onClick="onClick"
            android:layout_width="50sp"
            android:layout_height="wrap_content"
            tools:ignore="RtlHardcoded" />
        <Button
            android:layout_marginBottom="8sp"
            android:background="@drawable/button_style"
            android:id="@+id/batch_conversion"
            android:text="批转"
            android:visibility="invisible"
            android:textSize="12sp"
            android:onClick="onClick"
            android:layout_width="50sp"
            android:layout_height="wrap_content"
            tools:ignore="RtlHardcoded" />
        <Button
            android:background="@drawable/button_style"
            android:id="@+id/operatepdf"
            android:text="展开"
            android:textSize="12sp"
            android:onClick="onClick"
            android:layout_width="50sp"
            android:layout_height="wrap_content"
            tools:ignore="RtlHardcoded" />
        <TextView
            android:id="@+id/savepdfpath"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"/>
    </LinearLayout>
</FrameLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Atomic_space

你的鼓励就是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值