如何将PdfDocument对象保存到android中的文件中?

时间:2015-08-21 09:29:07

标签: android android-file android-print-framework android-pdf-api

在我的应用程序中,我创建了一个关于按钮点击事件的PDF文档。我使用Print Framework打印该文档。所有这些都正常工作。我需要的是,我想将该pdf文档保存到文件夹中我的手机存储。如何做到这一点,我不会'知道如何将这个pdf保存到文件中。可以帮助我吗?请提前感谢。

我的代码生成pdf

public class CustomPrintActivity extends Activity {





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_custom_print);
}



public void printDocument(View view)
{
    PrintManager printManager = (PrintManager) this
            .getSystemService(Context.PRINT_SERVICE);

    String jobName = this.getString(R.string.app_name) +
            " Document";

    printManager.print(jobName, new MyPrintDocumentAdapter(this),
            null);
}
public class MyPrintDocumentAdapter extends PrintDocumentAdapter {
    Context context;
    private int pageHeight;
    private int pageWidth;
    public PdfDocument myPdfDocument;
    public int totalpages = 1;


    public MyPrintDocumentAdapter(Context context) {
        this.context = context;
    }

    @Override
    public void onLayout(PrintAttributes oldAttributes,
                         PrintAttributes newAttributes,
                         CancellationSignal cancellationSignal,
                         LayoutResultCallback callback,
                         Bundle metadata) {


        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(final PageRange[] pageRanges,
                        final ParcelFileDescriptor destination,
                        final CancellationSignal cancellationSignal,
                        final WriteResultCallback callback) {

        for (int i = 0; i < totalpages; i++) {
            if (pageInRange(pageRanges, 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()));

      /*   String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/cookbook";

            File dir = new File(path);
            if(!dir.exists())
                dir.mkdirs();

            Log.d("PDFCreator", "PDF Path: " + path);


            File file = new File(dir, "recipe.pdf");
            FileOutputStream fOut = new FileOutputStream(file);
            myPdfDocument.writeTo(fOut);

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(myPdfDocument);
            bw.close();*/


        } catch (IOException e) {
            callback.onWriteFailed(e.toString());
            return;
        } finally {
            myPdfDocument.close();
            myPdfDocument = null;
        }

        callback.onWriteFinished(pageRanges);

    }

    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++; //

        int titleBaseLine = 90;
        int leftMargin = 50;

        /*Drawable icon = getResources().getDrawable(R.drawable.pot);
        icon.setBounds(leftMargin - 40, 40, 60, 80);
        icon.getIntrinsicHeight();
        icon.getIntrinsicWidth();

        icon.draw(canvas);*/


        Paint paint = new Paint();
        paint.setColor(Color.BLACK);

        paint.setTextSize(18);
        Typeface fontRegular = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");

        paint.setTypeface(fontRegular);
        canvas.drawText("PDF SAMPLE", leftMargin, titleBaseLine, paint);
        paint.setTextSize(14);
        canvas.drawText("PDF LINE NO 1", leftMargin, titleBaseLine + 30, paint);

        paint.setTextSize(12);
        canvas.drawText("PDF LINE NO 1", leftMargin, titleBaseLine + 50, paint);

        paint.setTextSize(14);
        canvas.drawText("PDF LINE NO 1", leftMargin, titleBaseLine + 80, paint);

        paint.setTextSize(12);
        canvas.drawText("PDF LINE NO 1", leftMargin, titleBaseLine + 100, paint);


    }
}



}

enter image description here

2 个答案:

答案 0 :(得分:3)

使用此方法。

 public void saveFile( String fileName, PdfDocument document) {

     try {

            File mypath=new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"filename.pdf");
            document.writeTo(new FileOutputStream(mypath));

            document.close();

        }

答案 1 :(得分:0)

调用方法writeTo(outputStream out)

public createFile(String fileName, PdfDocument document){
    FileOutputStream os;
    try {   
        //Create folder in which you want to save Pdf documents
        File folder = new File(Environment.getExternalStorageDirectory(), "PdfFolder");
        if(!folder.exists()){
           folder.mkdirs();
        }
        //Create pdf file
        File mPdfFile = new File(folder,fileName);
        //Make sure that there isn't a file with the same name
        if(!mPdfFile.exists(){
            mPdfFile.createNewFile();
        }
        os =  new FileOutputStream(mPdfFile);  
        document.writeTo(os);
        Toast.makeText(getApplicationContext, "File saved succesfully",
                Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(getApplicationContext, "Something was wrong",
                Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }finally{
        document.close();
        if(os!=null)os.close();
    }
}

使用此代码,您将pdf保存在SD卡中,您可以对其进行修改以将其保存在您想要的位置。