web-dev-qa-db-fra.com

Créer un fichier pdf en Android par programmation et l'écrire dedans

J'essaie de créer un fichier pdf dans mon application, enregistrez-le sur le stockage externe et ouvrez-le. L'enregistrement d'un fichier n'est pas un problème pour moi, ni l'ouverture d'un, mon problème est de créer un et d'écrire dedans. Donc, après quelques recherches en ligne, j'ai trouvé la façon suivante de le faire:

        File file = new File(directoryName, fileName);

        // Creating output stream to write in the newly created file
        FileOutputStream fOut = null;

        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // Creating a new document
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        try {
            PdfWriter.getInstance(document, fOut);

            // Open the document for writing
            document.open();

            // Write in the document
            document.add(new Paragraph("Hello world"));
            document.close();

        } catch(DocumentException de) {
            System.err.println(de.getMessage());
        }

Lors de l'exécution de mon application et de l'exécution du code ci-dessus, j'obtiens l'erreur suivante:

Java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color;

Quelqu'un sait-il quel est le problème avec mon code, ou d'une autre manière qui fonctionnera à coup sûr pour créer et écrire un fichier pdf?

Merci !

10
Husayn Hakeem

Donc, apparemment, le code que j'utilisais n'était pas compatible avec Android, d'où l'erreur que j'obtenais. Vous trouverez ci-dessous le code correct qui fonctionne réellement (pour créer un fichier pdf, y mettre du contenu, l'enregistrer et ouvrir le fichier nouvellement créé):

PS: Pour cela, vous devrez ajouter le pot de iTextG à votre projet:

// Method for creating a pdf file from text, saving it then opening it for display
    public void createandDisplayPdf(String text) {

        Document doc = new Document();

        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir";

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

            File file = new File(dir, "newFile.pdf");
            FileOutputStream fOut = new FileOutputStream(file);

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

            Paragraph p1 = new Paragraph(text);
            Font paraFont= new Font(Font.COURIER);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);

            //add paragraph to document
            doc.add(p1);    

        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        }
        finally {
            doc.close();
        }

        viewPdf("newFile.pdf", "Dir");
    }

    // Method for opening a pdf file
    private void viewPdf(String file, String directory) {

        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
        Uri path = Uri.fromFile(pdfFile);

        // Setting the intent for pdf reader
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try {
            startActivity(pdfIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(TableActivity.this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
        }
    }
18
Husayn Hakeem

PdfDocument classe permet de générer un PDF à partir du contenu natif Android contenu. En utilisant cette classe, nous pouvons créer un pdf et également l'ouvrir par en utilisant PdfRenderer . Exemple de code pour créer un fichier pdf

 public void stringtopdf(String data)  {
    String extstoragedir = Environment.getExternalStorageDirectory().toString();
    File fol = new File(extstoragedir, "pdf");
    File folder=new File(fol,"pdf");
    if(!folder.exists()) {
        boolean bool = folder.mkdir();
    }
    try {
        final File file = new File(folder, "sample.pdf");
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file);


        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new 
        PdfDocument.PageInfo.Builder(100, 100, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);
        Canvas canvas = page.getCanvas();
        Paint paint = new Paint();

        canvas.drawText(data, 10, 10, Paint);



        document.finishPage(page);
        document.writeTo(fOut);
        document.close();

    }catch (IOException e){
        Log.i("error",e.getLocalizedMessage());
    }
9
baswaraj

Téléchargez le code source à partir d'ici ( Créer un fichier pdf dans Android par programme )

activity_main.xml:

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:background="#ffffff"
    Android:orientation="vertical">

    <Button
        Android:id="@+id/btn_generate"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:text="Generate PDF" />

    <LinearLayout
        Android:layout_width="match_parent"
        Android:orientation="vertical"
        Android:id="@+id/ll_pdflayout"
        Android:background="#ffffff"
        Android:layout_height="match_parent">

        <ImageView
            Android:id="@+id/iv_image"
            Android:src="@drawable/image"
            Android:layout_width="300dp"
            Android:scaleType="fitXY"
            Android:layout_marginTop="10dp"
            Android:layout_gravity="center"
            Android:layout_height="250dp" />

        <TextView
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:textSize="14dp"
            Android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
            Android:layout_marginTop="10dp"
            Android:gravity="center"
            Android:paddingLeft="10dp"
            Android:paddingRight="10dp"
            Android:textColor="#000000"/>


        <TextView
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:id="@+id/tv_link"
            Android:textSize="10dp"
            Android:textColor="#000000"/>


    </LinearLayout>

</LinearLayout>

MainActivity.Java

package com.deepshikha.generatepdf;

import Android.Manifest;
import Android.app.ProgressDialog;
import Android.content.Context;
import Android.content.Intent;
import Android.content.pm.PackageManager;
import Android.content.res.Resources;
import Android.graphics.Bitmap;
import Android.graphics.BitmapFactory;
import Android.graphics.Canvas;
import Android.graphics.Color;
import Android.graphics.Paint;
import Android.graphics.Rect;
import Android.graphics.pdf.PdfDocument;
import Android.support.v4.app.ActivityCompat;
import Android.support.v4.content.ContextCompat;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.util.DisplayMetrics;
import Android.util.Log;
import Android.view.Display;
import Android.view.View;
import Android.view.WindowManager;
import Android.widget.Button;
import Android.widget.ImageView;
import Android.widget.LinearLayout;
import Android.widget.ProgressBar;
import Android.widget.TextView;
import Android.widget.Toast;

import Java.io.File;
import Java.io.FileNotFoundException;
import Java.io.FileOutputStream;
import Java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button btn_generate;
    TextView tv_link;
    ImageView iv_image;
    LinearLayout ll_pdflayout;
    public static int REQUEST_PERMISSIONS = 1;
    boolean boolean_permission;
    boolean boolean_save;
    Bitmap bitmap;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        fn_permission();
        listener();
    }


    private void init(){
        btn_generate = (Button)findViewById(R.id.btn_generate);
        tv_link = (TextView)findViewById(R.id.tv_link);
        iv_image = (ImageView) findViewById(R.id.iv_image);
        ll_pdflayout = (LinearLayout) findViewById(R.id.ll_pdflayout);

    }

    private void listener(){
        btn_generate.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_generate:

                if (boolean_save) {
                    Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
                    startActivity(intent);

                } else {
                    if (boolean_permission) {
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setMessage("Please wait");
                         bitmap = loadBitmapFromView(ll_pdflayout, ll_pdflayout.getWidth(), ll_pdflayout.getHeight());
                        createPdf();
//                        saveBitmap(bitmap);
                    } else {

                    }

                    createPdf();
                    break;
                }
        }
    }

    private void createPdf(){
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        float hight = displaymetrics.heightPixels ;
        float width = displaymetrics.widthPixels ;

        int convertHighet = (int) hight, convertWidth = (int) width;

//        Resources mResources = getResources();
//        Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.screenshot);

        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();


        Paint paint = new Paint();
        canvas.drawPaint(Paint);


        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);

        Paint.setColor(Color.BLUE);
        canvas.drawBitmap(bitmap, 0, 0 , null);
        document.finishPage(page);


        // write the document content
        String targetPdf = "/sdcard/test.pdf";
        File filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));
            btn_generate.setText("Check PDF");
            boolean_save=true;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }

        // close the document
        document.close();
    }



    public static Bitmap loadBitmapFromView(View v, int width, int height) {
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);

        return b;
    }

    private void fn_permission() {
        if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)||
                (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }
        } else {
            boolean_permission = true;


        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSIONS) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                boolean_permission = true;


            } else {
                Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();

            }
        }
    }


}

Merci!

4
Deepshikha Puri