将内部存储中的pdf文件路径保存到Sqlite中

时间:2015-01-28 12:47:46

标签: android pdf android-sqlite

我是Android新手,我正在制作一个应用程序,它从访问者那里获取信息并从中制作pdf并保存内部存储,它还可以选择通过wifi连接的打印机打印信息

这是我的主要java文件Visitor_pass -

package com.example.sayedshazeb.practical1;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.nfc.Tag;
import android.print.PrintManager;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.content.Context;
import android.print.PrintDocumentInfo;
import android.print.pdf.PrintedPdfDocument;
import android.graphics.pdf.PdfDocument;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;


public class Visitor_pass extends ActionBarActivity implements ImageAndTextContainer {

    ImageView iv;
    public Context c;






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_visitor_pass);
        iv = (ImageView) findViewById(R.id.image);

             Button cbtn = (Button)findViewById(R.id.captureimage);
        cbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,0);

            }
        });



        Button pbtn = (Button) findViewById(R.id.print);

    pbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            printDocument(v);

        }
    });

        Button s =(Button)findViewById(R.id.Dbsave);

        s.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Bitmap bm = (Bitmap) data.getExtras().get("data");
        iv.setImageBitmap(bm);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void printDocument(View view)
    {

        // Get a PrintManager instance
        PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);

        // Give the job a name.
        String jobName = this.getString(R.string.app_name) +
                " Document";

        // Start a print job, passing a printDocumentAdapter as
        //argument to handle the generation of a print document
        MyPrintDocumentAdapter printDoc = new MyPrintDocumentAdapter(this);
        printManager.print(jobName, printDoc, null);
    }

    @Override
    public Bitmap getImage() {
        ImageView imageView = (ImageView) findViewById(R.id.image);
        Bitmap image = null;
        // Get the image
        if ((imageView.getDrawable()) != null) {
            // Send it to the print helper
            image = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        }
        return image;
    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    public class MyPrintDocumentAdapter extends PrintDocumentAdapter
    {
        private ImageAndTextContainer imageAndTextContainer;
        Context context;
        private int pageHeight;
        private int pageWidth;
        public PdfDocument myPdfDocument;
        public int totalpages = 1;
        String pts;
        String ats;
        String cts;


        public MyPrintDocumentAdapter(ImageAndTextContainer container) {
            this.context =context;
            this.imageAndTextContainer = container;
        }


        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
            myPdfDocument = new PrintedPdfDocument(context, newAttributes);

            pageHeight =
                    newAttributes.getMediaSize().getHeightMils()/1000 * 72;
            pageWidth =
                    newAttributes.getMediaSize().getWidthMils()/1000 * 72;

            if (cancellationSignal.isCanceled() ) {
                callback.onLayoutCancelled();
                return;
            }

            if (totalpages > 0) {
                PrintDocumentInfo.Builder builder = new PrintDocumentInfo
                        .Builder("print_output.pdf")
                        .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                        .setPageCount(totalpages);

                PrintDocumentInfo info = builder.build();
                callback.onLayoutFinished(info, true);
            } else {
                callback.onLayoutFailed("Page count is zero.");
            }
        }

        @Override
        public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {



            for (int i = 0; i < totalpages; i++) {
                if (pageInRange(pages, i))
                {
                    PdfDocument.PageInfo newPage = new PdfDocument.PageInfo.Builder(pageWidth,
                            pageHeight, i).create();

                    PdfDocument.Page page =
                            myPdfDocument.startPage(newPage);

                    if (cancellationSignal.isCanceled()) {
                        callback.onWriteCancelled();
                        myPdfDocument.close();
                        myPdfDocument = null;
                        return;
                    }
                    drawPage(page, i);
                    myPdfDocument.finishPage(page);
                }
            }

            try {
                myPdfDocument.writeTo(new FileOutputStream(
                        destination.getFileDescriptor()));
            } catch (IOException e) {
                callback.onWriteFailed(e.toString());
                return;
            } finally {
                myPdfDocument.close();
                myPdfDocument = null;
            }

            callback.onWriteFinished(pages);
        }


        private boolean pageInRange(PageRange[] pageRanges, int page)
        {
            for (int i = 0; i<pageRanges.length; i++)
            {
                if ((page >= pageRanges[i].getStart()) &&
                        (page <= pageRanges[i].getEnd()))
                    return true;
            }
            return false;
        }


        private void drawPage(PdfDocument.Page page,
                              int pagenumber) {
            Canvas canvas = page.getCanvas();

            pagenumber++; // Make sure page numbers start at 1

            int titleBaseLine = 72;
            int leftMargin = 54;


            EditText pt = (EditText)findViewById(R.id.textname);
            EditText ct = (EditText)findViewById(R.id.textphone);
            pts = pt.getText().toString();
            EditText at = (EditText)findViewById(R.id.textaddress);
            ats = at.getText().toString();

            cts = ct.getText().toString();

            DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
            int day = datePicker.getDayOfMonth();
            String d = ""+day;
            int month = datePicker.getMonth() + 1;
            String m = ""+month;
            int year = datePicker.getYear();
            String y=""+year;

            Paint paint = new Paint();
            paint.setColor(Color.BLACK);
            paint.setTextSize(40);
            canvas.drawText("Visitor Details " + pagenumber, leftMargin, titleBaseLine, paint);
            paint.setTextSize(25);
            canvas.drawText("Name :", leftMargin, titleBaseLine + 400, paint);
            canvas.drawText(pts ,leftMargin + 110,titleBaseLine + 400,paint);
            canvas.drawText("Address :",leftMargin,titleBaseLine + 450,paint);
            canvas.drawText(ats ,leftMargin + 110,titleBaseLine + 450,paint);
            canvas.drawText("Number :",leftMargin,titleBaseLine + 500,paint);
            canvas.drawText(cts ,leftMargin + 110,titleBaseLine + 500,paint);
            canvas.drawText("Date :" ,leftMargin,titleBaseLine + 550,paint);
            canvas.drawText( d + "/" +m+"/"+y  ,leftMargin+110,titleBaseLine + 550,paint);
            Rect imageRect = new Rect(100, 100, canvas.getWidth() - 240, canvas.getHeight() / 2 - 10);
            drawImage(imageAndTextContainer.getImage(), canvas, imageRect);





        }
        private void drawImage(Bitmap image, Canvas canvas, Rect r) {
            canvas.drawBitmap(image, null, r, new Paint());
        }






    }

}

这是我的主要Xml文件 -

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Visitor_pass"
    android:orientation="vertical"
    android:weightSum="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Visitor&apos;s Pass"
        android:id="@+id/visitorpass"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center"
        android:textSize="20dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/textname"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:hint="Enter visitor&apos;s name"
        android:focusableInTouchMode="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPostalAddress"
        android:ems="10"
        android:id="@+id/textaddress"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:hint="Enter Address"
        android:focusableInTouchMode="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/textphone"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:focusableInTouchMode="true"
        android:hint="Enter Number" />

    <DatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/datePicker"
        android:layout_gravity="center_horizontal"
        android:calendarViewShown="false"
        android:datePickerMode="spinner" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="150dp"
        android:id="@+id/image"
        android:layout_gravity="center"
        android:layout_marginTop="10dp" />

    <Button
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:text="Capture Image"
        android:id="@+id/captureimage"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:text="Save "
        android:id="@+id/Dbsave"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:text="Print"
        android:id="@+id/print"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:text="Discard"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal" />

</LinearLayout>
</ScrollView>

这是print_dialog xml -

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <WebView android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</RelativeLayout>

现在我想保存创建并保存在内部存储中的pdf文件的路径,以保存在我的sqlite数据库中。我知道如何将值存储到数据库中我只想知道如何获取存储在我的内部存储器中的文件的路径?

2 个答案:

答案 0 :(得分:0)

您可以使用Environment.getExternalStorageDirectory()

此方法返回主外部存储目录。 例如,如果您有一个名为/ pdf的文件夹,那么您的文件路径将为:

Environment.getExternalStorageDirectory() + "/pdf/" + <pd_file_name>

注意:不要被&#34;外部&#34;这个词弄糊涂。这里。此目录最好被视为媒体/共享存储。它是一个文件系统,可以容纳相对大量的数据,并在所有应用程序之间共享(不强制执行权限)。传统上这是一张SD卡,但它也可以作为内置存储器实现,该设备不同于受保护的内部存储器,可以作为文件系统安装在计算机上。

更多信息here

答案 1 :(得分:0)

“我只是想知道如何获取存储在我内部存储器中的文件的路径?” 你试过getFilesDir()吗?实施例。

String path = this.getFilesDir().toString()+"/"+nameOfFile;