앞으로 종이영수증은 고객이 요청이 있지 않는한 출력을 하지 않고 휴대폰으로 보내준다고 하자나요. 

카톡이나 문자나 마트전용앱등을 통해 보내겠죠. 

안드로이드 영수증 pdf 출력하는걸 만들었습니다. 코드를 공유합니다. 광고 한번만 눌러주세요 ㅎㅎ 큰힘이 됩니다.

준비물 : 컴퓨터, 안드로이드스튜디오, 안드로이드OS휴대폰 

 

1. AndroidManifest.xml에 다음과 같은 코드를 추가합니다. 

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

말 그대로 휴대폰 저장장치에 쓰기를 허가하는거에요. pdf파일을 저장해야하니깐요. 

 

2. 이미지 파일 삽입하기 

그리고 그림파일 피자가 주제라서 피자그림파일 아무거나 가져오세요. 사이즈는 1200 X 300입니다. 

이 이미지 파일을 res/drawable 폴더에 넣어주세요. 그냥 복사 붙여넣기하면됩니다. 

 

 

 

3. 이제 레이아웃 UI를 만들거에요  아래 그림처럼 간단히 만들겁니다. 

activity_mail.xml 에 아래 코드박스에 있는걸 붙여넣으면 위에 그림처럼 나옵니다. 

EditText는 입력할수 있는 거고, TextView는 그냥 보는거에요. Spinner는 선택해서 입력으로~ Button을 누르면 pdf가 완성됩니다. 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:width="350dp"
        android:height="50dp"
        android:ems="10"
        android:hint="고객 이름"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/editText2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:width="350dp"
        android:height="50dp"
        android:ems="10"
        android:hint="연락처"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.491"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText1" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="40dp"
        android:layout_marginBottom="40dp"
        android:width="50dp"
        android:height="50dp"
        android:text="1"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText2"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="40dp"
        android:layout_marginBottom="40dp"
        android:width="50dp"
        android:height="50dp"
        android:text="2"
        android:textSize="30sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView1"
         />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="40dp"
        android:background="#c4fdd835"
        android:entries="@array/pizza_menu"
        app:layout_constraintStart_toEndOf="@+id/textView1"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="40dp"
        android:background="#c4fdd835"
        android:entries="@array/pizza_menu"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/spinner1" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="80dp"
        android:layout_height="50dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:hint="수량"
        android:inputType="number"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.132"
        app:layout_constraintStart_toEndOf="@+id/spinner1"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="80dp"
        android:layout_height="50dp"

        android:layout_marginLeft="10dp"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:hint="수량"
        android:inputType="number"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.148"
        app:layout_constraintStart_toEndOf="@+id/spinner2"
        app:layout_constraintTop_toBottomOf="@+id/editText3" />

    <Button
        android:id="@+id/button"
        android:layout_width="230dp"
        android:layout_height="68dp"
        android:layout_marginTop="164dp"
        android:text="영수증 출력"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/spinner2"
        app:layout_constraintVertical_bias="0.14" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

4. 그리고 spinner에 피자메뉴 android:entries="@array/pizza_menu" 를 세팅해줘야 합니다. 

values/strings.xml에 들어가세요. 그리고 아래 코드를 넣어줍니다. 

<resources>
    <string name="app_name">pdf_example2</string>
    <string-array name="pizza_menu">
        <item>선택</item>
        <item>콤비네이션</item>
        <item>페파로니</item>
        <item>치즈피자</item>
        <item>불고기피자</item>
    </string-array>
</resources>

 

5. 이제 자바코딩해줍니다. 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.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    Button btn;
    Spinner item1_spinner, item2_spinner;
    EditText et_customer, et_phone, et_qty1, et_qty2;
    Bitmap bitmap, scaledbmp;
    int pageWidth = 1200;
    Date dateObj;
    DateFormat dateFormat;
    float[] prices = new float[]{0,2000,3000,4500,5000};

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

        btn = findViewById(R.id.button);
        item1_spinner = findViewById(R.id.spinner1);
        item2_spinner = findViewById(R.id.spinner2);
        et_customer = findViewById(R.id.editText1);
        et_phone = findViewById(R.id.editText2);
        et_qty1 = findViewById(R.id.editText3);
        et_qty2 = findViewById(R.id.editText4);
        bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.pizza);
        scaledbmp = Bitmap.createScaledBitmap(bitmap, 1200, 300, false);

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

    private void createPDF() {
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dateObj = new Date();


                if(et_customer.getText().toString().length()==0 ||
                et_phone.getText().toString().length()==0 ||
                et_qty1.getText().toString().length()==0 ||
                et_qty2.getText().toString().length()==0) {
                    Toast.makeText(MainActivity.this,"모두입력해주세요",Toast.LENGTH_SHORT).show();
                }else{
                    PdfDocument pdfDocument = new PdfDocument();
                    Paint paint = new Paint();
                    Paint titlePaint = new Paint();

                    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(1200,2000,1).create();
                    PdfDocument.Page page = pdfDocument.startPage(pageInfo);
                    Canvas canvas = page.getCanvas();

                    canvas.drawBitmap(scaledbmp,0,0,paint);
                    titlePaint.setTextAlign(Paint.Align.CENTER);
                    titlePaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
                    titlePaint.setTextSize(70);
                    canvas.drawText("맛있는 피자",pageWidth/2,150,titlePaint);

                    paint.setColor(Color.rgb(0,113,188));
                    paint.setTextSize(30f);
                    paint.setTextAlign(Paint.Align.RIGHT);
                    canvas.drawText("Tel:02-1234-5678",1160,40,paint);
                    canvas.drawText("Tel:02-1234-123",1160,80,paint);

                    titlePaint.setTextAlign(Paint.Align.CENTER);
                    titlePaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.ITALIC));
                    titlePaint.setTextSize(70);
                    canvas.drawText("영수증",pageWidth/2,500,titlePaint);

                    paint.setTextAlign(Paint.Align.LEFT);
                    paint.setTextSize(35f);
                    paint.setColor(Color.BLACK);
                    canvas.drawText("고객 이름: "+et_customer.getText(),20,590,paint);
                    canvas.drawText("연락처: " +et_phone.getText(),20,640,paint);

                    paint.setTextAlign(Paint.Align.RIGHT);
                    canvas.drawText("영수정 번호: "+"20202211",pageWidth-20,590,paint);

                    dateFormat = new SimpleDateFormat("yy/MM/dd");
                    canvas.drawText("Date: "+dateFormat.format(dateObj),pageWidth-20,640,paint);

                    dateFormat = new SimpleDateFormat("HH:mm:ss");
                    canvas.drawText("시간: "+dateFormat.format(dateObj), pageWidth-20, 690,paint);

                    paint.setStyle(Paint.Style.STROKE);
                    paint.setStrokeWidth(2);
                    canvas.drawRect(20,780,pageWidth-20,860,paint);

                    paint.setTextAlign(Paint.Align.LEFT);
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawText("번호",40,830,paint);
                    canvas.drawText("구매목록", 200,830,paint);
                    canvas.drawText("가격",700,830,paint);
                    canvas.drawText("수량",900,830,paint);
                    canvas.drawText("총금액",1050,830,paint);

                    canvas.drawLine(180,790,180,840,paint);
                    canvas.drawLine(680,790,680,840,paint);
                    canvas.drawLine(880,790,880,840,paint);
                    canvas.drawLine(1030,790,1030,840,paint);

                    float total1 = 0;
                    if(item1_spinner.getSelectedItemPosition() != 0 )
                    {
                        canvas.drawText("1.",40,950,paint);
                        canvas.drawText(item1_spinner.getSelectedItem().toString(),200,950,paint);
                        canvas.drawText(String.valueOf(prices[item1_spinner.getSelectedItemPosition()]),700,950,paint);
                        canvas.drawText(et_qty1.getText().toString(),900,950,paint);
                        total1 = Float.parseFloat(et_qty1.getText().toString())*prices[item1_spinner.getSelectedItemPosition()];
                        paint.setTextAlign(Paint.Align.RIGHT);
                        canvas.drawText(String.valueOf(total1),pageWidth-40,950,paint);
                        paint.setTextAlign(Paint.Align.LEFT);
                    }

                    float total2 = 0;
                    if(item2_spinner.getSelectedItemPosition() != 0 )
                    {
                        canvas.drawText("2.",40,1050,paint);
                        canvas.drawText(item2_spinner.getSelectedItem().toString(),200,1050,paint);
                        canvas.drawText(String.valueOf(prices[item2_spinner.getSelectedItemPosition()]),700,1050,paint);
                        canvas.drawText(et_qty2.getText().toString(),900,1050,paint);
                        total2 = Float.parseFloat(et_qty2.getText().toString())*prices[item2_spinner.getSelectedItemPosition()];
                        paint.setTextAlign(Paint.Align.RIGHT);
                        canvas.drawText(String.valueOf(total2),pageWidth-40,1050,paint);
                        paint.setTextAlign(Paint.Align.LEFT);
                    }

                    float subtotal = total1 + total2;
                    canvas.drawLine(680,1200,pageWidth-20,1200,paint);
                    canvas.drawText("합계",700,1250,paint);
                    canvas.drawText(":",900,1250,paint);
                    paint.setTextAlign(Paint.Align.RIGHT);
                    canvas.drawText(String.valueOf(subtotal),pageWidth-40,1250,paint);

                    paint.setTextAlign(Paint.Align.LEFT);
                    canvas.drawText("부가세(10%)",700,1300,paint);
                    canvas.drawText(":",900,1300,paint);
                    paint.setTextAlign(Paint.Align.RIGHT);
                    canvas.drawText(String.valueOf(subtotal*10/100),pageWidth-40,1300,paint);
                    paint.setTextAlign(Paint.Align.LEFT);

                    paint.setColor(Color.rgb(247,147,30));
                    canvas.drawRect(680,1350,pageWidth-20,1450,paint);

                    paint.setColor(Color.BLACK);
                    paint.setTextSize(50f);
                    paint.setTextAlign(Paint.Align.LEFT);
                    canvas.drawText("총합계",700,1415,paint);
                    paint.setTextAlign(Paint.Align.RIGHT);
                    canvas.drawText(String.valueOf(subtotal+(subtotal*10/100)),pageWidth-40,1415,paint);




                    pdfDocument.finishPage(page);
                    File file = new File(Environment.getExternalStorageDirectory(),"/pizza.pdf");

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

                    pdfDocument.close();
                }


            }
        });
    }
}

 

 

 

7. 동영상보고 따라하기. 구독과 좋아요는 큰힘이 될거에요 ㅎㅎ 

 

 

https://youtu.be/264FmC9AyYM

 

YouTube

 

www.youtube.com

 

+ Recent posts