在android应用程序中以片段形式显示PDF

在android应用程序中以片段形式显示PDF,android,android-fragments,pdf-viewer,Android,Android Fragments,Pdf Viewer,在我的应用程序中,我必须在android中显示SD卡上的PDF文件。该应用程序使用选项卡功能,因此我在应用程序中使用了片段。那么,如何在片段中显示pdf文件呢? 我已经使用了pdfviewer.jar,但我无法显示内部片段,它只能在活动中工作 另一个问题是,我想通过多重缩放和垂直页面滚动来显示pdf,以查看下一页/上一页,而不是手动单击缩放图标和箭头图标来查看pdfviewer.jar中使用的下一页。我在下面给出更改片段的完整代码。我三年前就这么做了,那时夏洛克图书馆被使用了。我想现在你必须用a

在我的应用程序中,我必须在android中显示SD卡上的PDF文件。该应用程序使用选项卡功能,因此我在应用程序中使用了片段。那么,如何在片段中显示pdf文件呢? 我已经使用了pdfviewer.jar,但我无法显示内部片段,它只能在活动中工作


另一个问题是,我想通过多重缩放和垂直页面滚动来显示pdf,以查看下一页/上一页,而不是手动单击缩放图标和箭头图标来查看pdfviewer.jar中使用的下一页。

我在下面给出更改片段的完整代码。我三年前就这么做了,那时夏洛克图书馆被使用了。我想现在你必须用appcompat库来代替它

package net.sf.andpdf.pdfviewer;

import java.io.*;
import java.nio.channels.FileChannel;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.*;
import android.widget.ImageView;
import android.widget.TextView;
import net.sf.andpdf.nio.ByteBuffer;
import net.sf.andpdf.pdfviewer.gui.TouchImageView;
import net.sf.andpdf.refs.HardReference;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFImage;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFPaint;
import com.sun.pdfview.decrypt.PDFAuthenticationFailureException;
import com.sun.pdfview.decrypt.PDFPassword;
import com.sun.pdfview.font.PDFFont;




public class PdfViewerFragment extends SherlockFragment  {

    private static final int STARTPAGE = 1;
    private static float STARTZOOM = 1f;


    private static final String TAG = "PDFVIEWER";
    private static final String FTAG = "PDFVIEWERFRG";

    public static final String EXTRA_PDFFILENAME = "net.sf.andpdf.extra.PDFFILENAME";
    public static final String EXTRA_SHOWIMAGES = "net.sf.andpdf.extra.SHOWIMAGES";
    public static final String EXTRA_ANTIALIAS = "net.sf.andpdf.extra.ANTIALIAS";
    public static final String EXTRA_USEFONTSUBSTITUTION = "net.sf.andpdf.extra.USEFONTSUBSTITUTION";
    public static final String EXTRA_KEEPCACHES = "net.sf.andpdf.extra.KEEPCACHES";

    public static final boolean DEFAULTSHOWIMAGES = true;
    public static final boolean DEFAULTANTIALIAS = true;
    public static final boolean DEFAULTUSEFONTSUBSTITUTION = false;
    public static final boolean DEFAULTKEEPCACHES = true;

    private String pdffilename;
    private PDFFile mPdfFile;
    private int mPage;
    private float mZoom;
    private File mTmpFile;
    private ProgressDialog progress;

    private TextView tv_page_no;
    String imgFileName;
    private ImageView rightArrow;
    private ImageView leftArrow;

    private PDFPage mPdfPage;

    private Thread backgroundThread;
    private Activity activity;

    TouchImageView tiv;

    @Override
    public void onAttach(Activity activity) {
        Log.i(FTAG, "PDFFragment.onAttatch");
        this.activity = activity;
        super.onAttach(activity);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Display display = activity.getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();

        if(activity.getResources().getConfiguration().orientation ==  Configuration.ORIENTATION_LANDSCAPE )
        {
            STARTZOOM = (1f*width)/800.0f;

        }
        else
        {
            STARTZOOM = (1f*height)/800.0f;

        }
        Log.i(FTAG, "PDFFragment: onCreate");
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i(FTAG, "PDFFragment: onCreateView");

        View docView = inflater.inflate(R.layout.doc_viewer, container, false);
        setRetainInstance(true);

        boolean showImages = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_SHOWIMAGES, PdfViewerFragment.DEFAULTSHOWIMAGES);
        PDFImage.sShowImages = showImages;
        boolean antiAlias = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_ANTIALIAS, PdfViewerFragment.DEFAULTANTIALIAS);
        PDFPaint.s_doAntiAlias = antiAlias;
        boolean useFontSubstitution = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_USEFONTSUBSTITUTION, PdfViewerFragment.DEFAULTUSEFONTSUBSTITUTION);
        PDFFont.sUseFontSubstitution= useFontSubstitution;
        boolean keepCaches = activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_KEEPCACHES, PdfViewerFragment.DEFAULTKEEPCACHES);
        HardReference.sKeepCaches= keepCaches;

        Bundle args = getArguments();
        if (args != null) {
            Log.i(FTAG, "Args Value: "+args.getString(EXTRA_PDFFILENAME));
            pdffilename = args.getString(EXTRA_PDFFILENAME);;
        } else {
            // TODO: open a default document
            pdffilename = "/mnt/sdcard/documents/3.pdf";
        }

        tiv = (TouchImageView) docView.findViewById(R.id.imageView); 
        leftArrow = (ImageView) docView.findViewById(R.id.leftArrow);
        rightArrow = (ImageView) docView.findViewById(R.id.rightArrow);

        leftArrow.setVisibility(View.GONE);
        rightArrow.setVisibility(View.GONE);

        if (pdffilename == null)
        {
            pdffilename = "No file selected";
        }
        else if(pdffilename.contains(".pdf"))
        {
            imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_1.jpg";

            mPage = STARTPAGE;
            mZoom = STARTZOOM;
            progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page", true, true);

            leftArrow.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    prevPage();
                }
            });

            rightArrow.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    nextPage();
                }
            });

            tv_page_no = (TextView) docView.findViewById(R.id.navigationText);

            tiv.setParent(this);
            setContent(null);
        }
        else if(pdffilename.contains(".jpg") || pdffilename.contains(".jpeg") || pdffilename.contains(".png") || pdffilename.contains(".gif") || pdffilename.contains(".bmp"))
        {
            imgFileName = pdffilename;
            tiv.setImageLocation(imgFileName);
        }
        else
        {
            pdffilename = "Invalid file extension";
        }

        return docView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Log.i(FTAG, "PDFFragment: onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.i(FTAG, "PDFFragment: onActivityCreated");
    }

    @Override
    public void onStart() {
        Log.i(FTAG, "PDFFragment.onStart");
        super.onStart();
        //Bundle args = getArguments();
    }

    @Override
    public void onResume() {
        Log.i(FTAG, "PDFFragment.onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.i(FTAG, "PDFFragment.onPause");
        super.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.i(FTAG, "PDFFragment.onSaveInstanceState");
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onStop() {
        Log.i(FTAG, "PDFFragment.onStop");
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        Log.i(FTAG, "PDFFragment.onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        Log.i(FTAG, "PDFFragment.onDestroy");
        super.onDestroy();
        if (mTmpFile != null) {
            mTmpFile.delete();
            mTmpFile = null;
        }
    }

    @Override
    public void onDetach() {
        Log.i(FTAG, "PDFFragment.onDetach");
        super.onDetach();
    }

    private boolean setContent(String password) {
        try {
            parsePDF(pdffilename, password);
            if(new File(imgFileName).exists())
            {
                tiv.setImageLocation(imgFileName);
                updateTexts(1);
                progress.dismiss();
            }
            else
                startRenderThread(mPage, mZoom);
        }
        catch (PDFAuthenticationFailureException e) {

        } catch (Exception e) {

        }
        return true;
    }

    public synchronized void startRenderThread(final int page, final float zoom) {
        if (backgroundThread != null)
            return;

        backgroundThread = new Thread(new Runnable() {
            public void run() {
                try {
                    if (mPdfFile != null) {
                        generatePDFPage(page, zoom);
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
                backgroundThread = null;
            }
        });
        backgroundThread.start();
    }


    public void nextPage() {
        if (mPdfFile != null) {
            if (mPage < mPdfFile.getNumPages()) {
                mPage += 1;
                imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_"+String.valueOf(mPage)+".jpg";
                if(new File(imgFileName).exists())
                {
                    tiv.setImageLocation(imgFileName);
                    updateTexts(mPage);
                    progress.dismiss();
                }
                else
                {
                    progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page " + mPage, true, true);
                    startRenderThread(mPage, STARTZOOM);
                }
            }
        }
    }

    public void prevPage() {
        if (mPdfFile != null) {
            if (mPage > 1) {
                mPage -= 1;
                imgFileName= pdffilename.substring(0, pdffilename.lastIndexOf("."))+"_"+String.valueOf(mPage)+".jpg";
                if(new File(imgFileName).exists())
                {
                    tiv.setImageLocation(imgFileName);
                    updateTexts(mPage);
                    progress.dismiss();
                }
                else
                {
                    progress = ProgressDialog.show(activity, "Loading", "Loading PDF Page " + mPage, true, true);
                    startRenderThread(mPage, STARTZOOM);
                }
            }
        }
    }

    protected void updateTexts(int pageNo) {

        if (mPdfFile != null) {
            tv_page_no.setText("Page "+pageNo+"/"+mPdfFile.getNumPages());
            if(mPdfFile.getNumPages() > 1)
            {
                if(pageNo==1)
                    leftArrow.setVisibility(View.GONE);
                else
                    leftArrow.setVisibility(View.VISIBLE);

                if(pageNo == mPdfFile.getNumPages())
                    rightArrow.setVisibility(View.GONE);
                else
                    rightArrow.setVisibility(View.VISIBLE);
            }
        }
    }

    public void generatePDFPage(final int page, float zoom) throws Exception {

        try {
            // Only load the page if it's a different page (i.e. not just changing the zoom level)
            if (mPdfPage == null || mPdfPage.getPageNumber() != page) {
                mPdfPage = mPdfFile.getPage(page, true);
            }

            float width = mPdfPage.getWidth();
            float height = mPdfPage.getHeight();

            RectF clip = null;

            Bitmap bmp =  mPdfPage.getImage((int)(width*zoom), (int)(height*zoom), clip, true, true);
            //imgFileName +=  String.valueOf(page)+".jpg";

            FileOutputStream fo = null;
            try {
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
                File f = new File(imgFileName);
                f.createNewFile();
                fo = new FileOutputStream(f);
                fo.write(bytes.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (Exception ex) {

            } finally {
                if (fo != null) {
                    try {
                        fo.close();
                    } catch (IOException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                }
            }

            activity.runOnUiThread(new Runnable() {
                public void run() {
                    tiv.setImageLocation(imgFileName);
                    //tiv.setImageBitmap(BitmapFactory.decodeFile(imgFileName));
                    updateTexts(page);
                    if (progress != null)
                        progress.dismiss();
                }
            });




        } catch (Throwable e) {
            Log.e(TAG, e.getMessage(), e);

        }

    }

    public void parsePDF(String filename, String password) throws PDFAuthenticationFailureException {
        pdffilename =  filename;
        try {
            File f = new File(filename);
            long len = f.length();
            if (len == 0) {

            }
            else {

                openFile(f, password);
            }
        }
        catch (PDFAuthenticationFailureException e) {
            throw e;
        } catch (Throwable e) {
            e.printStackTrace();

        }

    }

    /**
     * <p>Open a specific pdf file.  Creates a DocumentInfo from the file,
     * and opens that.</p>
     *
     * <p><b>Note:</b> Mapping the file locks the file until the PDFFile
     * is closed.</p>
     *
     * @param file the file to open
     * @throws IOException
     */
    public void openFile(File file, String password) throws IOException {
        // first open the file for random access
        RandomAccessFile raf = null;
        try
        {
            raf = new RandomAccessFile(file, "r");
            // extract a file channel
            FileChannel channel = raf.getChannel();

            // now memory-map a byte-buffer
            ByteBuffer bb = ByteBuffer.NEW(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()));
            // create a PDFFile from the data
            if (password == null)
                mPdfFile = new PDFFile(bb);
            else
                mPdfFile = new PDFFile(bb, new PDFPassword(password));


        } catch (Exception ex)
        {

        } finally {
            raf.close();
        }


    }

}
package net.sf.andpdf.pdfviewer;
导入java.io.*;
导入java.nio.channels.FileChannel;
导入android.app.Activity;
导入android.content.res.Configuration;
导入android.graphics.*;
导入android.widget.ImageView;
导入android.widget.TextView;
导入net.sf.andpdf.nio.ByteBuffer;
导入net.sf.andpdf.pdfviewer.gui.TouchImageView;
导入net.sf.andpdf.refs.HardReference;
导入android.app.ProgressDialog;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Display;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入com.sun.pdfview.PDFFile;
导入com.sun.pdfview.PDFImage;
导入com.sun.pdfview.PDFPage;
导入com.sun.pdfview.PDFPaint;
导入com.sun.pdfview.decrypt.PDFAuthenticationFailureException;
导入com.sun.pdfview.decrypt.PDFPassword;
导入com.sun.pdfview.font.PDFFont;
公共类PdfViewerFragment扩展了SherlockFragment{
专用静态最终整数起始页=1;
专用静态浮动起始空间=1f;
私有静态最终字符串TAG=“PDFVIEWER”;
私有静态最终字符串FTAG=“PDFVIEWERFRG”;
公共静态最终字符串EXTRA_PDFFILENAME=“net.sf.andpdf.EXTRA.PDFFILENAME”;
公共静态最终字符串EXTRA_SHOWIMAGES=“net.sf.andpdf.EXTRA.SHOWIMAGES”;
公共静态最终字符串EXTRA_antialas=“net.sf.andpdf.EXTRA.antialas”;
公共静态最终字符串EXTRA_USEFONTSUBSTITUTION=“net.sf.andpdf.EXTRA.USEFONTSUBSTITUTION”;
公共静态最终字符串EXTRA\u KEEPCACHES=“net.sf.andpdf.EXTRA.KEEPCACHES”;
公共静态最终布尔值DEFAULTSHOWIMAGES=true;
公共静态最终布尔值DEFAULTANTIALIAS=true;
公共静态最终布尔值DEFAULTUSEFONTSUBSTITUTION=false;
公共静态最终布尔值DEFAULTKEEPCACHES=true;
私有字符串pdffilename;
私有pdffilempdffile;
私人公寓;
私有浮动缩放;
私有文件mTmpFile;
私人进展对话进展;
私人文本视图电视页面号;
字符串imgFileName;
私有图像视图右箭头;
私有图像视图左箭头;
私人PDFPage mPdfPage;
私有线程背景线程;
私人活动;
触摸图像视图tiv;
@凌驾
公共事务主任(活动){
Log.i(FTAG,“pdfffragment.onantatch”);
这个。活动=活动;
超级转速计(活动);
}
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Display Display=activity.getWindowManager().getDefaultDisplay();
int width=display.getWidth();
int height=display.getHeight();
if(activity.getResources().getConfiguration().orientation==Configuration.orientation\u横向)
{
起始空间=(1f*宽度)/800.0f;
}
其他的
{
起始空间=(1f*高度)/800.0f;
}
Log.i(FTAG,“PDF片段:onCreate”);
}
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
Log.i(FTAG,“PDFFracent:onCreateView”);
视图docView=充气机。充气(R.layout.doc\u查看器,容器,假);
setRetainInstance(真);
boolean showImages=activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_showImages,PdfViewerFragment.DEFAULTSHOWIMAGES);
PDFImage.sShowImages=showImages;
boolean antiAlias=activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_antiAlias,PdfViewerFragment.DEFAULTANTIALIAS);
PDFPaint.s_DOATIAS=反别名;
boolean useFontSubstitution=activity.getIntent().GetBooleanExtract(PdfViewerFragment.EXTRA_useFontSubstitution,PdfViewerFragment.DEFAULTUSEFONTSUBSTITUTION);
PDFFont.sUseFontSubstitution=useFontSubstitution;
布尔keepCaches=activity.getIntent().getBooleanExtra(PdfViewerFragment.EXTRA_keepCaches,PdfViewerFragment.DEFAULTKEEPCACHES);
HardReference.sKeepCaches=keepCaches;
Bundle args=getArguments();
如果(args!=null){
Log.i(FTAG,“Args值:”+Args.getString(EXTRA_PDFFILENAME));
pdffilename=args.getString(额外的pdffilename);;
}否则{
//TODO:打开默认文档
pdffilename=“/mnt/sdcard/documents/3.pdf”;
}
tiv=(TouchImageView)docView.findViewById(R.id.imageView);
leftArrow=(ImageView)docView.findViewById(R.id.leftArrow);
rightArrow=(ImageView)docView.findViewById(R.id.rightArrow);
leftArrow.setVisibility(View.GONE);
rightArrow.setVisibility(View.GONE);
if(pdffilename==null)
{
pdffilename=“未选择任何文件”;
}
else if(pdffilename.contains(“.pdf”))
{
imgFileName=pdffilename.substring(0,pdffilename.lastIndexOf(“.”)+“\u 1.jpg”;
mPage=起始页;
mZoom=STARTZOOM;
progress=ProgressDialog.show(活动“加载”,“加载PDF页面”,true,true);
leftArrow.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
prevPage();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_keluarga, container, false);     
    pdfView = (PDFView) v.findViewById(R.id.keluargaPdf);        
    pdfView.fromAsset("tiga.pdf").load();

    // Inflate the layout for this fragment     
    return v;    
}