Create First PDF : Android Studio 안드로이드에서 PDF 생성하기

 

1. AndroidManifest.xml 에 다음과 같이 추가한다. 

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

2. activity_main.xml에 다음과 같이 버튼을 추가한다. 

 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Create PDF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

 

 

3. MainActivity.java를 다음과 같이 코딩한다. 

package com.jwlee.pdf_example2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

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

public class MainActivity extends AppCompatActivity {

    Button button;

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

        button = findViewById(R.id.button);
        ActivityCompat.requestPermissions(this,new String[] {
                Manifest.permission.WRITE_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);
        
        createPDF();
        

    }

    private void createPDF() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PdfDocument pdfDocument = new PdfDocument();
                Paint paint = new Paint();

                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(250,400,1).create();
                PdfDocument.Page page = pdfDocument.startPage(pageInfo);

                Canvas canvas = page.getCanvas();
                canvas.drawText("안드로이드 PDF 첫번째 문서 만들기 ",30,30,paint);
                pdfDocument.finishPage(page);

                File file = new File(Environment.getExternalStorageDirectory(),"/myPDF.pdf");

                try {
                    pdfDocument.writeTo(new FileOutputStream(file));
                }catch (IOException e) {
                    e.printStackTrace();
                }

                pdfDocument.close();

            }
        });
    }
}

4. pdf 생성확인. (Check pdf)

 

 

5. 비디오 보고 따라한다. (Follow the video )

 

 

+ Recent posts