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);
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);
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();
switch (v.getId()){
case R.id.operatepdf:
btncount++;
if (!String.valueOf(btncount).matches("([1-9]\\d*)?[02468]")){
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{
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){
Bitmap bm =((BitmapDrawable) imageView.getDrawable()).getBitmap();
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());
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() {
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();
}
@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>