Back to project page PDF2ImageForEP.
The source code is released under:
GNU General Public License
If you think the Android project PDF2ImageForEP listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
/* * PDF????????????????????????????// w w w .jav a 2 s.c om * PDF??????????????????????MuPDF???????????????????????????????????? * http://mupdf.com * * ???????????????????????????GPLv3????????????? */ package jp.co.muratec.pdf2image; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import com.artifex.mupdf.MuPDFActivity; import com.artifex.mupdf.MuPDFCore; import com.artifex.mupdf.SafeAsyncTask; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.text.InputType; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.graphics.PointF; import android.graphics.Bitmap.CompressFormat; import android.util.Log; import jp.co.muratec.pdfdrawerdata.DrawerData; public class PDF2ImageActivity extends Activity { private static final int REQUEST_CODE_SRCFILE = 1; // ???????????? private static final int REQUEST_CODE_DSTDIR = 2; // ???????????? private static final int REQUEST_CODE_PREVIEW = 3; // PDF???????? private static final int DIALOG_ID_ALERT_SRC = 1; // ?????????????????????????????????? private static final int DIALOG_ID_ALERT_DST = 2; // ?????????????????????????????????? private static final int DIALOG_ID_OUTPUT_SETTING = 3; // ??????????????????? private static final int DIALOG_ID_PROGRESS = 4; // ???????????????????? private static final int DIALOG_ID_PASSWORD = 5; // ?????????????????????? private static final int DIALOG_ID_PASSWORD_ERROR = 6; // ????????????????????????? private static String TAG = "PDF2Image"; private TextView srcDirView,dstDirView; // ???????????????????? private String srcDirPath,dstDirPath; // ?????????????? private String srcFilePath = null; // ??????? private EditText passwordView; // ??????????? private boolean passwordDialogFlag = false; // ????????????????????????? private Intent filerIntent; // ?????????Intent // ???? private AlertDialog editDialog; // ????????? private TextView page_info_view; // ????? private TextView page_start_view; // ???????? private int page_start_value = 1; // ???????? private TextView page_end_view; // ???????? private int page_end_value = -1; // ???????? private DeepRadioGroup size_group_view; // ??????????????? private int size_group_value = 0; // ???????? private TextView custom_width_view; // ???????????????????? private int custom_width_value = -1; // ?????? private TextView custom_height_view; // ??????????????????????? private int custom_height_value = -1; // ?????? private Spinner format_spinner_view; // ???????????????? private int format_spinner_value = 0; // ???????? private TextView quality_view; // ?? private int quality_value = 100; // ?????? ProgressDialog progressBar; // ???????????????????????? private int processingCount = 0; // ??????????????????????? private int processingMax = 0; // ???????????????? private boolean processingFlag = false; // ?????????????????true??? private int processingSuccessFlag = RESULT_FIRST_USER;// ????????????????????????????? private MuPDFCore core = null; private DrawerData draw = null; private boolean isIntentStart = false; //xujie debug private boolean isGetPage = false; //xujie debug @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate()"); // ????????????????????????????????????????????????????????????????????????????????? //this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); // ??????????????????????????????????????????????????????????????????????????????? //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Activity??????????????? requestWindowFeature(Window.FEATURE_NO_TITLE); // ????????ClassLoader????????????????????????????????????????????????????????????????????????????????????????????? LoadLibrary instance = LoadLibrary.getInstance(); try { instance.setAppPath(getPackageManager().getApplicationInfo("jp.co.muratec.pdf2image", 0).sourceDir , getFilesDir().getAbsolutePath()); instance.init(); } catch (NameNotFoundException e) { // TODO ???????????? catch ???? e.printStackTrace(); } //xujie debug String pdf_name_for_preview= null;//PDF????Preview????? String pdf_name_for_get_pages= null;//PDF???????????????? boolean isSetPreviewFinish = false; //luo boolean isMobilePhone = false; //luo try { Intent intent = getIntent(); pdf_name_for_preview = intent.getStringExtra("PDF_NAME_FOR_PREVIEW"); pdf_name_for_get_pages = intent.getStringExtra("PDF_NAME_FOR_GET_PAGES"); isSetPreviewFinish = intent.getBooleanExtra("IS_SET_PREVIEW_FINISH", false); //luo isMobilePhone = intent.getBooleanExtra("IS_MOBILE_PHONE", false); //luo } catch (Exception e) { e.printStackTrace(); } if(pdf_name_for_preview != null){//PDF????Preview????? Uri uri = Uri.parse(pdf_name_for_preview); Intent intent = new Intent(PDF2ImageActivity.this,MuPDFActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.setData(uri); //luo intent.putExtra("IS_MOBILE_PHONE", isMobilePhone); //luo intent.putExtra("IS_FROM_MOBILEPRINT_PREVIEW", true); //startActivityForResult(intent, REQUEST_CODE_PREVIEW); startActivity(intent); finish(); return; } if(pdf_name_for_get_pages != null){//PDF???????????????? isGetPage = true; int pdfPages = getPDFPages(pdf_name_for_get_pages); if (isSetPreviewFinish) { if (!MuPDFActivity.mPreviewActivity.isFinishing()) { MuPDFActivity.mPreviewActivity.finish(); } } Intent intent = new Intent(); intent.putExtra("PDF_PAGES", pdfPages); setResult(RESULT_OK, intent); finish(); isGetPage = false; return; } if (isSetPreviewFinish) { if (!MuPDFActivity.mPreviewActivity.isFinishing()) { MuPDFActivity.mPreviewActivity.finish(); } finish(); return; } //xujie debug // Intent ??????????? draw = (DrawerData)getIntent().getSerializableExtra("DrawerData"); // Intent??????????????????(?????????????) if (draw != null) { // ????????????????????????????????????????????????????????????????????????????????? //this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); // ??????????????????????????????????????????????????????????????????????????????? getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // ??????????????????????????????????????????? if (draw.getFinishApp()) { for (int m = draw.getStartPage(); m < draw.getEndPage() + 1; m++){ draw.deleteFile(m); } finish(); return; } isIntentStart = true; srcFilePath = draw.getDataPath(); Log.d(TAG, "srcFilePath:" + srcFilePath); Convert(); processingSuccessFlag = RESULT_FIRST_USER; doConvert(); Log.d(TAG, "debug3"); // ?????????????????????????????? // while (processingSuccessFlag == RESULT_FIRST_USER) { // try { // Thread.sleep(200); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // ???????????????????????? Intent intent = new Intent(); if (processingSuccessFlag == RESULT_OK) { intent.putExtra("DrawerData", draw); setResult(RESULT_OK,intent); } else { setResult(RESULT_CANCELED,intent); } finish(); } // ???????????? else { setContentView(R.layout.activity_main); isIntentStart = false; // TODO ?????????????????????SD????????????? srcDirView = (TextView)this.findViewById(R.id.srcPath); srcDirPath = Environment.getExternalStorageDirectory().getAbsolutePath(); srcDirView.setText(getString(R.string.info_src_file_path).toString()); dstDirView = (TextView)this.findViewById(R.id.dstPath); dstDirPath = Environment.getExternalStorageDirectory().getAbsolutePath(); dstDirView.setText(dstDirPath); filerIntent = new Intent(this, jp.co.muratec.pdf2image.FilerActivity.class); // ?????????Intent??? } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction()==KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: // ????? processingFlag = false; // ???????????????????? break; } } return super.dispatchKeyEvent(event); } /* * ???? */ // ?????????????? public void onChangeSrc(View v){ filerIntent.putExtra("openPath" , srcDirPath); filerIntent.putExtra("mode" , REQUEST_CODE_SRCFILE); startActivityForResult(filerIntent, REQUEST_CODE_SRCFILE ); } // ??????????? public void onChangeDst(View v){ filerIntent.putExtra("openPath" , dstDirPath); filerIntent.putExtra("mode" , REQUEST_CODE_DSTDIR); startActivityForResult(filerIntent, REQUEST_CODE_DSTDIR ); } // ????????????????????? @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == Activity.RESULT_OK){ if(requestCode == REQUEST_CODE_SRCFILE){ // ???????????????? srcDirPath = data.getStringExtra("path"); srcFilePath = data.getStringExtra("filepath"); srcDirView.setText(srcFilePath); // ???????????????????????????????????? page_start_value = 1; page_end_value = -1; } else if (requestCode == REQUEST_CODE_DSTDIR) { // ???????????????? dstDirPath = data.getStringExtra("path"); dstDirView.setText(dstDirPath); } // //xujie debug // else if (requestCode == REQUEST_CODE_PREVIEW) { // int pdfPages = data.getIntExtra("PDF_PAGES", 1); // // Intent intent = new Intent(); // intent.putExtra("PDF_PAGES", pdfPages); // setResult(RESULT_OK, intent); // finish(); // } // //xujie debug } // //xujie debug // else if (resultCode == Activity.RESULT_CANCELED) { // if (requestCode == REQUEST_CODE_PREVIEW) { // setResult(RESULT_CANCELED); // finish(); // } // } // else if (resultCode == MuPDFActivity.RESULT_BACK) { // if (requestCode == REQUEST_CODE_PREVIEW) { // setResult(MuPDFActivity.RESULT_BACK); // finish(); // } // } // //xujie debug } // ?????? @SuppressWarnings("deprecation") public void onExecConvert(final View v){ Convert(); } // ?????? public void Convert(){ // ????????? if(srcFilePath == null || ( !srcFilePath.toLowerCase().endsWith(".pdf") && !srcFilePath.toLowerCase().endsWith(".xps") && !srcFilePath.toLowerCase().endsWith(".cbz") ) ){ // ???????????????????????? showDialog(DIALOG_ID_ALERT_SRC); return; } if (isIntentStart == false) { // ??????????????????? // ????????? File outDir = new File(dstDirPath); if(outDir == null || outDir.canWrite() == false){ // ????????????? showDialog(DIALOG_ID_ALERT_DST); return; } } // ??????????????????????? openPDF(srcFilePath,""); } // PDF????????? @SuppressWarnings("deprecation") private void openPDF(String src,String password){ try { core = new MuPDFCore(srcFilePath); if (core != null && core.needsPassword()) { if(core.authenticatePassword(password) != true){ // ??????????? if(passwordDialogFlag){ showDialog(DIALOG_ID_PASSWORD_ERROR); } else { // ??????? showDialog(DIALOG_ID_PASSWORD); } return; } passwordDialogFlag = false; } if(core != null && isIntentStart == false){ // ????????? showDialog(DIALOG_ID_OUTPUT_SETTING); } if (core != null) { core.setRenderResolution(320); } } catch (Exception e) { // TODO ???????????? catch ???? e.printStackTrace(); } } // ????????? @Override protected Dialog onCreateDialog(int id){ switch (id) { case DIALOG_ID_ALERT_SRC: // ???????????????????????? return new AlertDialog.Builder(this) .setTitle(getString(R.string.warning_dialog_title_src)) .setMessage(getString(R.string.warning_dialog_message_src)) .create(); case DIALOG_ID_ALERT_DST: // ????????????? return new AlertDialog.Builder(this) .setTitle(getString(R.string.warning_dialog_title_dst)) .setMessage(getString(R.string.warning_dialog_message_dst)) .create(); case DIALOG_ID_OUTPUT_SETTING: // ???? LayoutInflater factory = LayoutInflater.from(this); View editView = factory.inflate(R.layout.pdf2image_output, null); // ??????????????? // ????????View page_info_view = (TextView)editView.findViewById(R.id.page_info); // ????? page_start_view = (TextView)editView.findViewById(R.id.page_start); // ???????? page_end_view = (TextView)editView.findViewById(R.id.page_end); // ???????? size_group_view = (DeepRadioGroup)editView.findViewById(R.id.size_group); // ???????? custom_width_view = (TextView)editView.findViewById(R.id.custom_width); // ????????? custom_height_view = (TextView)editView.findViewById(R.id.custom_height); // ???????????? format_spinner_view = (Spinner)editView.findViewById(R.id.format); // ????????????? quality_view = (TextView)editView.findViewById(R.id.quality); // ?? //???????????(AlertDialog.Builder) editDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(getString(R.string.output_setting_title).toString()) .setView(editView) .setPositiveButton(getString(R.string.execution_button).toString(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // ???????? doConvert(); } }) .create(); return editDialog; case DIALOG_ID_PROGRESS: // ???????? progressBar = new ProgressDialog(this); progressBar.setTitle(getString(R.string.progress_dialog_title)); progressBar.setMessage(getString(R.string.progress_dialog_title)+"..."); progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressBar.setCancelable(true); progressBar.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { processingFlag = false; // ????????????????????????????????????? } }); return progressBar; case DIALOG_ID_PASSWORD: passwordView = new EditText(this); passwordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(getString(R.string.input_password)) .setView(passwordView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { passwordDialogFlag = true; String input = passwordView.getText().toString(); dialog.dismiss(); openPDF(srcFilePath,input); } }) .setNegativeButton(getString(R.string.cancel_button), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .create(); case DIALOG_ID_PASSWORD_ERROR: return new AlertDialog.Builder(this) .setTitle(getString(R.string.password_error_title)) .setMessage(getString(R.string.password_error_msg)) .setPositiveButton(getString(R.string.input_password_retry), new DialogInterface.OnClickListener() { @SuppressWarnings("deprecation") public void onClick(DialogInterface dialog, int whichButton) { showDialog(DIALOG_ID_PASSWORD); } }) .setNegativeButton(getString(R.string.cancel_button), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .create(); } return null; } @SuppressWarnings("deprecation") protected void onPrepareDialog(int id, Dialog dialog,Bundle data) { switch (id) { case DIALOG_ID_OUTPUT_SETTING: // ????????? if(core == null){ // ?????????????????????????core??????????????? return; } // ????? int page_max = core.countPages(); page_info_view.setText(getString(R.string.output_setting_page_info,page_max)); if(page_end_value == -1){ page_end_value = page_max; } page_start_view.setText(Integer.toString(page_start_value)); page_end_view.setText(Integer.toString(page_end_value)); // ????????????? size_group_view.check(size_group_view.getChildAt(size_group_value).getId()); // ??????????? if(custom_width_value == -1 || custom_height_value == -1){ Display display = getWindowManager().getDefaultDisplay(); custom_width_value = display.getWidth(); custom_height_value = display.getHeight(); } custom_width_view.setText(Integer.toString(custom_width_value)); custom_height_view.setText(Integer.toString(custom_height_value)); // ???????? format_spinner_view.setSelection(format_spinner_value); // ?? quality_view.setText(Integer.toString(quality_value)); break; case DIALOG_ID_PROGRESS: progressBar.setProgress(0); progressBar.setMax(processingMax); break; case DIALOG_ID_PASSWORD: case DIALOG_ID_PASSWORD_ERROR: passwordDialogFlag = false; default: super.onPrepareDialog(id, dialog,data); } } // ???????? @SuppressWarnings("deprecation") protected void doConvert(){ // ????????????????? // ??? if (isIntentStart == false) { // ??????????????????? doConvertAsBackGround(); } else { // ??????????? String input_page_start = ""; String input_page_end = ""; page_start_value = draw.getStartPage(); page_end_value = draw.getEndPage(); if (page_start_value == 0) { page_start_value = 1; page_end_value = 1; } // ??? size_group_value = 0; // PDF???? // ?????? format_spinner_value = 0; // ?? String input_quality = ""; try { int page_max = core.countPages(); // ???? int page_column = Integer.toString(page_max).length(); // ?????????? // ???????????????????????????????????_page????.(jpg|png)? String fileName = (new File(srcFilePath)).getName(); // ????PDF???????????? String baseFileName = fileName; int index = fileName.lastIndexOf("."); if(index >= 0){ baseFileName = fileName.substring(0, index); // ??????? } // ??????? PointF size = new PointF(); for(int i = page_start_value - 1;i<page_end_value;i++){ // ????? if(size_group_value == 1){ // ??????????? size.set((float)custom_width_value, (float)custom_height_value); } else { // PDF????????? size = core.getPageSize(i); } Log.d(TAG, "PDF Size:X=" + size.x + " :Y=" + size.y); // ?????????????? double MemorySize = size.x * size.y; // ????????? double freeSize = (Runtime.getRuntime().freeMemory()); // ????????????? Log.d(TAG, "Memory:" + MemorySize + " freeSize:" + freeSize); Bitmap bm = core.drawPage(i,(int)size.x, (int)size.y, 0, 0, (int)size.x, (int)size.y); // PDF??????????????????????? // ????????????????? draw.SetBitmap(bm, i + 1, getApplicationContext()); Log.d(TAG, "Write Done"); if (bm != null) { bm.recycle(); } processingSuccessFlag = RESULT_OK; } } catch (Exception e) { e.printStackTrace(); } } } private void doConvertAsBackGround(){ // ????????????????? int page_max = core.countPages(); // ????? String input_page_start = page_start_view.getText().toString(); if(input_page_start.equals("")){ page_start_value = 1; // ??????????? } else { page_start_value = Integer.parseInt(input_page_start); if(page_start_value < 1){ page_start_value = 1; // ?????????????????????? } else if (page_start_value > page_max) { page_start_value = page_max; // ??????????????????????? } } // ????? String input_page_end = page_end_view.getText().toString(); if(input_page_end.equals("")){ page_end_value = page_max; // ??????????? } else { page_end_value = Integer.parseInt(input_page_end); if(page_end_value < 1){ page_end_value = 1; // ???????????????????????? } else if (page_end_value > page_max) { page_end_value = page_max; // ??????????????????????? } } if(page_start_value > page_end_value){ // ?? > ?? ??????? // TODO ?????????????????????? return; } // ??? size_group_value = 0; // ????????PDF???? if(size_group_view.getCheckedRadioButtonId() == R.id.size_custom){ // ??????? String input_width = custom_width_view.getText().toString(); String input_height = custom_height_view.getText().toString(); if(!input_width.equals("") && !input_height.equals("")){ custom_width_value = Integer.parseInt(input_width); custom_height_value = Integer.parseInt(input_height); if(custom_width_value > 0 && custom_height_value > 0){ size_group_value = 1; // ??????????????????????????????????????? } } } // ?????? format_spinner_value = format_spinner_view.getSelectedItemPosition(); // ?? String input_quality = quality_view.getText().toString(); if(input_quality.equals("")){ quality_value = 100; } else { quality_value = Integer.parseInt(input_quality); if(quality_value < 0){ quality_value = 0; } else if (quality_value > 100) { quality_value = 100; } } // ?????????????????? try { SafeAsyncTask<Void,Void,Void> sizingTask = new SafeAsyncTask<Void,Void,Void>() { @Override protected void onPreExecute() { // ??????????? processingCount = 0; processingMax = page_end_value - page_start_value + 1; processingFlag = true; showDialog(DIALOG_ID_PROGRESS); } @Override protected Void doInBackground(Void... arg0) { int page_max = core.countPages(); // ???? int page_column = Integer.toString(page_max).length(); // ?????????? // ???????????????????????????????????_page????.(jpg|png)? String fileName = (new File(srcFilePath)).getName(); // ????PDF???????????? String baseFileName = fileName; int index = fileName.lastIndexOf("."); if(index >= 0){ baseFileName = fileName.substring(0, index); // ??????? } // ??????? PointF size = new PointF(); for(int i = page_start_value - 1;i<page_end_value;i++){ if(processingFlag == false || isCancelled()){ // ?????? break; } // ????? if(size_group_value == 1){ // ??????????? size.set((float)custom_width_value, (float)custom_height_value); } else { // PDF????????? size = core.getPageSize(i); } Log.d(TAG, "PDF Size:X=" + size.x + " :Y=" + size.y); // ?????????????? double MemorySize = size.x * size.y; // ????????? double freeSize = (Runtime.getRuntime().freeMemory()); // ????????????? Log.d(TAG, "Memory:" + MemorySize + " freeSize:" + freeSize); if(MemorySize > freeSize){ // ???????????????????????????????? double round = Math.sqrt(freeSize / MemorySize); size.x = (float) (round * size.x); size.y = (float) (round * size.y); Log.d(TAG, "Re Sampling:X=" + size.x + " :Y=" + size.y); } Bitmap bm = core.drawPage(i,(int)size.x, (int)size.y, 0, 0, (int)size.x, (int)size.y); // PDF??????????????????????? try { // ????????? if(format_spinner_value == 0){ // JPEG? FileOutputStream fos = new FileOutputStream(new File(dstDirPath+"/"+baseFileName+"_page"+String.format("%1$0"+page_column+"d", i+1)+".jpg")); bm.compress(CompressFormat.JPEG, quality_value, fos); fos.close(); } else { // PNG? FileOutputStream fos = new FileOutputStream(new File(dstDirPath+"/"+baseFileName+"_page"+String.format("%1$0"+page_column+"d", i+1)+".png")); bm.compress(CompressFormat.PNG, quality_value, fos); fos.close(); } bm.recycle(); // ??????????? processingCount++; publishProgress(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Void... values){ progressBar.setProgress(processingCount); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if(progressBar != null && progressBar.isShowing()){ progressBar.dismiss(); } } @Override protected void onCancelled() { if(progressBar != null && progressBar.isShowing()){ progressBar.dismiss(); } super.onCancelled(); } }; // ????? sizingTask.safeExecute(); } catch (Exception e) { e.printStackTrace(); } } //xujie debug private int getPDFPages(String path) { int pages = 1; MuPDFCore pdfCore = null; try { pdfCore = new MuPDFCore(path); pages = pdfCore.countPages(); } catch (Exception e) { e.printStackTrace(); } finally { if (pdfCore != null) pdfCore.onDestroy(); pdfCore = null; } return pages; } @Override public void onBackPressed() { // PDF??????????????Back???? if (isGetPage) { return; } super.onBackPressed(); } //xujie debug }