How to Create PDF using TCPDF using volley, php and mysql in android studio
- Setting up the Database
- Create a MySQL database to store the data that will be included in the PDF file. For instance, you can create a table named "products" that includes fields such as "product_name," "description," "price," etc.
- Creating a PHP script
- Write a PHP script that connects to the MySQL database and retrieves the data that will be included in the PDF file. You can use the "TCPDF" library to generate the PDF file.
- In the PHP script, define the layout of the PDF file by specifying the margins, orientation, font, etc.
- Connecting to the PHP Script using Volley
- In your Android Studio project, use Volley to connect to the PHP script and retrieve the data that will be included in the PDF file.
- Once the data has been retrieved, generate the PDF file using the TCPDF library.
- Displaying the PDF File
- Finally, display the PDF file in your Android Studio app using a PDF viewer library such as "PDFViewer."
xml Code..
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".AdminPanel.UserByProInvoice.AdminBuyProInvoice">
<LinearLayout
android:id="@+id/headerpanel_user"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/userById"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:gravity="center"
android:text="PID"
android:textColor="#000"
android:textSize="18dp"
android:textStyle="bold"
android:visibility="gone"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_weight="1"
android:gravity="center"
android:text="পণ্য"
android:textColor="#fff"
android:textSize="18dp"
android:textStyle="bold"
android:visibility="gone" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_weight="1"
android:gravity="center"
android:text="মূল্য"
android:textColor="#fff"
android:textSize="18dp"
android:textStyle="bold"
android:visibility="gone" />
<TextView
android:id="@+id/userOrderName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_weight="1"
android:gravity="center"
android:text="sad"
android:textColor="#000"
android:textSize="18sp"
android:textStyle="bold"
android:visibility="gone" />
</LinearLayout>
<ScrollView
android:id="@+id/scroller"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/headerpanel_user">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycel_userOrderList"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
<LinearLayout
android:id="@+id/btnCheckOutLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:background="@drawable/border_bd"
android:elevation="5dp"
android:layout_alignParentBottom="true"
android:gravity="center">
<soup.neumorphism.NeumorphButton
android:id="@+id/btnCheckOutUser"
style="@style/Widget.Neumorph.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="8dp"
android:text="Create Invoice"
android:textColor="@color/white"
app:neumorph_backgroundColor="#13C625"
/>
</LinearLayout>
</RelativeLayout>
Adapter Class:
public class AdminOrderUserAdapter extends RecyclerView.Adapter<AdminOrderUserAdapter.ViewHolder> {
Context mCtx;
List<ProductModel> adminOrderModelList;
public AdminOrderUserAdapter(Context mCtx, List<ProductModel> adminOrderModelList) {
this.mCtx = mCtx;
this.adminOrderModelList = adminOrderModelList;
}
@NonNull
@Override
public AdminOrderUserAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.admin_user_item_order_list,viewGroup,false);
return new AdminOrderUserAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull AdminOrderUserAdapter.ViewHolder holder, int position) {
ProductModel model = adminOrderModelList.get(position);
holder.OrderProPTitleName.setText(model.getPTitleName());
holder.OrderProName.setText(model.getPTitle());
Glide.with(mCtx)
.load(model.getPImage())
.placeholder(R.drawable.profile)
.error(R.drawable.img)
.into(holder.OrderProImg);
}
@Override
public int getItemCount() {
return adminOrderModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView OrderProPTitleName,OrderProName;
CircleImageView OrderProImg;
public ViewHolder(@NonNull View itemView) {
super(itemView);
OrderProPTitleName = itemView.findViewById(R.id.OrderProPTitleName);
OrderProName = itemView.findViewById(R.id.OrderProName);
OrderProImg = itemView.findViewById(R.id.OrderProImg);
}
}
}
Model Class
public class ProductModel {
public String PID, PTitleName,PTitle,Price,PImage,PDiscription,Brand,Genders,Quantity,Stock;
public ProductModel() {
}
public ProductModel(String PID, String PTitleName, String PTitle, String price, String PImage, String PDiscription, String brand, String genders, String quantity, String stock) {
this.PID = PID;
this.PTitleName = PTitleName;
this.PTitle = PTitle;
Price = price;
this.PImage = PImage;
this.PDiscription = PDiscription;
Brand = brand;
Genders = genders;
Quantity = quantity;
Stock = stock;
}
public String getPID() {
return PID;
}
public void setPID(String PID) {
this.PID = PID;
}
public String getPTitleName() {
return PTitleName;
}
public void setPTitleName(String PTitleName) {
this.PTitleName = PTitleName;
}
public String getPTitle() {
return PTitle;
}
public void setPTitle(String PTitle) {
this.PTitle = PTitle;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getPImage() {
return PImage;
}
public void setPImage(String PImage) {
this.PImage = PImage;
}
public String getPDiscription() {
return PDiscription;
}
public void setPDiscription(String PDiscription) {
this.PDiscription = PDiscription;
}
public String getBrand() {
return Brand;
}
public void setBrand(String brand) {
Brand = brand;
}
public String getGenders() {
return Genders;
}
public void setGenders(String genders) {
Genders = genders;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public String getStock() {
return Stock;
}
public void setStock(String stock) {
Stock = stock;
}
}
create LayoutInflater
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/admin_order_layout"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_margin="5dp"
android:elevation="3dp"
android:background="@drawable/bg_item"
android:orientation="vertical"
android:weightSum="2">
<TextView
android:id="@+id/proID_Admin"
android:fontFamily="@font/solaimanlipi"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="Watch"
android:textStyle="bold"
android:textColor="#000000"
android:textSize="16dp"
android:layout_weight="1"
android:padding="15dp"
android:visibility="gone"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="end">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/OrderProImg"
android:layout_width="96dp"
android:layout_height="96dp"
android:layout_gravity="center_horizontal"
android:src="@drawable/img"
app:civ_border_width="2dp"
app:civ_border_color="#EF1B1B"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/OrderProName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:fontFamily="@font/g3f"
android:textSize="14dp"
android:padding="5dp"
android:textColor="#000000"
android:text="adfasdfasd faasdfas"/>
<TextView
android:id="@+id/OrderProPTitleName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:fontFamily="@font/g3f"
android:textSize="14dp"
android:padding="5dp"
android:textColor="#000000"
android:text="adfasdfasd faasdfas"/>
<TextView
android:id="@+id/OrderProPrice"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:fontFamily="@font/g3f"
android:textSize="14dp"
android:padding="5dp"
android:textColor="#000000"
android:text="adfasdfasd faasdfas"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
ManiActivity java Class
private String urls = "https://yourwebsite.com/MakeInvoice.php?JRegID=";
private ProgressDialog progressDialog;
String categoryName;
TextView userOrderName,userById;
RecyclerView recycel_userOrderList;
List<ProductModel> productModelList;
AdminOrderUserAdapter adminOrderUserAdapter;
LinearLayoutManager linerLayoutManager;
NeumorphButton btnCheckOutUser;
FileOutputStream outputStream;
String response = "";
categoryName = getIntent().getStringExtra("JRegID");
userOrderName = findViewById(R.id.userOrderName);
userById = findViewById(R.id.userById);
userById.setText(categoryName);
recycel_userOrderList = findViewById(R.id.recycel_userOrderList);
btnCheckOutUser = findViewById(R.id.btnCheckOutUser);
linerLayoutManager= new LinearLayoutManager(this);
linerLayoutManager.setOrientation(linerLayoutManager.VERTICAL);
productModelList = new ArrayList<>();
recycel_userOrderList.setHasFixedSize(true);
ProductsViewOne();
btnCheckOutUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MakeInVoices();
}
});
public void MakeInVoices(){
final ProgressDialog progressDialog = new ProgressDialog(AdminBuyProInvoice.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
String urla = "https://yourwebsite.com/MakeInvoice.php?JRegID="+categoryName;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, urla,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
String pdfContentBase64 = jsonResponse.getString("pdf_content_base64");
byte[] pdfContent = Base64.decode(pdfContentBase64, Base64.DEFAULT);
// Write the PDF content to a file
File pdfFile = new File(getExternalFilesDir(null), "invoice.pdf");
FileOutputStream outputStream = new FileOutputStream(pdfFile);
outputStream.write(pdfContent);
outputStream.close();
// Open the PDF file using a PDF viewer app
Uri pdfUri = FileProvider.getUriForFile(AdminBuyProInvoice.this,
BuildConfig.APPLICATION_ID + ".provider", pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(pdfUri, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
VolleySingleton.getInstance(AdminBuyProInvoice.this).addToRequestQueue(stringRequest);
}
PHP Code:
<?php
require('../tcpdf/tcpdf.php');
$pdf = new TCPDF('P', 'mm', 'A4');
$pdf->SetMargins(25, 25, 25);
$pdf->SetFont('times', '', 12);
$pdf->AddPage();
//$pdf->Image('https://website.com/belt.png', 30, 10, 30, 0, '', '', '', false, 300, '', false, false, 0, false, false, false);
//$pdf->Image('https://website.com/belt.png', 150, 10, 30, 0, '', '', '', false, 300, '', false, false, 0, false, false, false);
$JRegID = $_GET['JRegID'];
$conn = mysqli_connect("localhost","root","password","dbname");
$sql = "SELECT * FROM tbl_usersorder WHERE JRegID = '".$JRegID."'";
$result = mysqli_query($conn, $sql);
$invoice = mysqli_fetch_assoc($result);
$sql = "SELECT * FROM tbl_jregistration WHERE JRegID = ".$invoice['JRegID'];
$result = mysqli_query($conn, $sql);
$customer = mysqli_fetch_assoc($result);
$pdf->SetMargins(25, 25, 25);
$pdf->SetFont('times', '', 12);
$pdf->Cell(50, 0, 'To: Moniruzzaman Monir', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, 'From:', 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(50, 0, 'Wholesaler & Retailer', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(52, 0, 'UserID: '.$customer['JRegID'], 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(50, 0, 'HB Tower, 2nd Floor', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(61, 0, 'User Name: '.$customer['UserName'], 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(50, 0, 'HMM Road, Jashore.', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(75, 0, 'Mobile No: '.$customer['PhoneNo'], 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(42, 0, '01723-819182.', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(86, 0, 'Issue Date: '.date("d/m/Y"), 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(42, 0, '01913-345154.', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 1, 'C');
$pdf->SetFont('helvetica', 'B', 30);
// Set fill color
$pdf->SetFillColor(220, 220, 220);
// Set border color
$pdf->SetDrawColor(128, 128, 128);
$pdf->SetTextColor(0, 0, 0);
// Set text color
$pdf->Cell(0, 10, 'Invoice', 0, 1, 'C');
$pdf->SetFont('times', 'B', 10);
$pdf->Cell(0, 10, 'Customer Information', 0, 1);
$pdf->SetFont('times', '', 10);
// Create a cell with custom attributes
$pdf->Cell(50, 10, 'Name:', 1, 0, 'L', 1);
// Create a cell with different fill and border colors
$pdf->SetFillColor(255, 255, 255);
$pdf->SetDrawColor(192, 192, 192);
$pdf->Cell(0, 10, $customer['UserName'], 1, 1, 'L', 1);
// Create a cell with custom attributes
$pdf->SetFont('times', '', 10);
$pdf->Cell(50, 10, 'Address:', 1, 0, 'L', 1);
$pdf->SetFillColor(255, 255, 255);
$pdf->SetDrawColor(192, 192, 192);
$pdf->Cell(0, 10, $customer['UserAddress'], 1, 1, 'L', 1);
$pdf->Ln(10);
$pdf->SetFont('times', 'B', 10);
//$pdf->Cell(30, 10, 'ID', 1, 0, 'C');
$pdf->Cell(90, 10, 'Products Name', 1, 0, 'C');
$pdf->Cell(30, 10, 'Price', 1, 0, 'C');
$pdf->Cell(20, 10, 'Quantity', 1, 0, 'C');
$pdf->Cell(20, 10, 'Total', 1, 1, 'C');
$pdf->SetFont('times', '', 10);
$sql = "SELECT uo.PID, uo.Qty, uo.JRegID,
pduct.PID, pduct.PTitleName, pduct.PTitle, pduct.Price, pduct.PImage,
pduct.PDiscription, pduct.Stock, reg.UserName, reg.PhoneNo
FROM tbl_usersorder uo
INNER JOIN tbl_product pduct ON pduct.PID = uo.PID
INNER JOIN tbl_jregistration reg ON reg.JRegID = uo.JRegID
WHERE uo.JRegID='".$JRegID."'";
$result = mysqli_query($conn, $sql);
$total = 0;
while ($row = mysqli_fetch_assoc($result)) {
//$pdf->Cell(30, 10, $row['PID'], 1, 0, 'C');
$pdf->Cell(90, 10, $row['PTitle'], 1, 0, 'C');
$pdf->Cell(30, 10, 'BDT '.$row['Price'].'/-', 1, 0, 'C');
$pdf->Cell(20, 10, $row['Qty'], 1, 0, 'C');
$subtotal = $row['Price'] * $row['Qty'];
$pdf->Cell(20, 10, 'BDT '.$subtotal.'/-', 1, 1, 'C');
$total += $subtotal;
}
$pdf->SetFont('times', 'B', 12);
$pdf->Cell(70, 10, 'Total', 1, 0, 'R');
$pdf->Cell(90, 10, 'BDT '.$total.'/-', 1, 1, 'C');
$pdf->Ln(10);
$pdf->Ln(10);
$pdf->Ln(10);
$pdf->Ln(10);
$pdf->SetMargins(25, 25, 25);
$pdf->SetFont('times', 'Signature', 10);
$pdf->Cell(42, 0, 'Signature', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(61, 0, 'Signature', 0, 1, 'C');
$pdf->SetFont('times', '', 12);
$pdf->Cell(50, 0, 'Moniruzzaman Monir', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(30, 0, 'User Name: '.$customer['UserName'], 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(50, 0, 'Wholesaler & Retailer', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(52, 0, 'Mobile No: '.$customer['PhoneNo'], 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(50, 0, '', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(61, 0, '', 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(50, 0, '', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(75, 0, '', 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(42, 0, '', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(86, 0, '', 0, 1, 'C');
$pdf->SetFont('times', '', 10);
$pdf->Cell(42, 0, '', 0, 0, 'C');
$pdf->Cell(30, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 0, 'C');
$pdf->Cell(20, 0, '', 0, 1, 'C');
//$pdf->Output('invoice.pdf', 'I');
$pdf_content = $pdf->Output('invoice.pdf', 'S');
$pdf_content_base64 = base64_encode($pdf_content);
header('Content-Type: application/json');
echo json_encode(array('pdf_content_base64'=> $pdf_content_base64));
?>