web-dev-qa-db-ja.com

AndroidでプログラムでPDFファイルを作成して書き込む

アプリ内でpdfファイルを作成し、外部ストレージに保存して開きます。ファイルを保存することは私にとっては問題ではなく、開くことでもありません。私の問題は、ファイルを作成して書き込むことです。そこで、オンラインで調査したところ、次の方法が見つかりました。

        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());
        }

アプリを実行して上記のコードを実行すると、次のエラーが表示されます。

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

誰かが私のコードの問題を知っていますか、またはpdfファイルを作成して書くために確実に動作する別の方法ですか?

ありがとう!

10
Husayn Hakeem

したがって、明らかに私が使用していたコードはAndroidと互換性がなかったため、エラーが発生しました。以下に、実際に正しく機能する正しいコードを見つけます(pdfファイルを作成し、その中にコンテンツを入れ、保存し、新しく作成したファイルを開くため):

PS:このためには、プロジェクトに iTextG のjarを追加する必要があります。

// 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 クラスにより、ネイティブPDFコンテンツからAndroidドキュメントを生成できます。このクラスを使用することで、pdfを作成し、 PdfRenderer を使用して開くこともできます。 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

ここからソースコードをダウンロードします( PDFファイルをAndroidプログラムで作成

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();

            }
        }
    }


}

ありがとう!

4
Deepshikha Puri