Logicchip

Itext 5 – creating custom PDF in android

Creating custom PDF using iText, iText Software is a global specialist in PDF. As a PDF library, it can be embedded into document solution workflows in industries such as; Legal, Finance, Governance, IT, Operations and more.We are using iText 5 here you can check there examples here.

The output is something like the image shown below.

pdf created using itext

Adding iText dependency

First add dependencies for iText5, We are using Material design 2 here .

dependencies {     implementation'com.itextpdf:itextg:5.5.10' } 

Main Activity

Conversion from array-list to PDF document took place in MainActivity. The array-list are provided by Const.java class Footer is created using HeaderFooter.java class. First we need to provide the location of the file in order to save it, run-time permission is required for accessing the storage of the device. This example shows a list of objects and the goal is to make PDF out of that list. We used table ( PdfPTable ) to arrange the contents to ensure the correct look and feel there are lot of other objects available for arranging contents to choose from. Different types of paper sizes are available also in the library, here it’s A4 because it’s the most common size used for billing . You can also include custom fonts to make the PDF more
appealing to the user. In this example we used custom fonts and images to change the look and feel of the PDF.

screenshots
	public class MainActivity extends AppCompatActivity {
		private RecyclerView recyclerMoney;
		private ListAdapter listAdapter;
		private ArrayList listItems;
		private SwipeRefreshLayout swipeMoney;
		private MaterialButton buttonPdf;


		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_main);
			Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
			setSupportActionBar(toolbar);
			swipeMoney=findViewById(R.id.swipeMoney);
			recyclerMoney=findViewById(R.id.recyclerMoney);
			buttonPdf=findViewById(R.id.buttonPdf);

			FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
			fab.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
							.setAction("Action", null).show();
				}
			});
			recyclerMoney.setHasFixedSize(true);
			recyclerMoney.setLayoutManager(new LinearLayoutManager(this));

			swipeMoney.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
				@Override
				public void onRefresh() {
					swipeMoney.setRefreshing(true);
					loadItems();
				}
			});

			swipeMoney.setRefreshing(true);
			loadItems();

			buttonPdf.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					AsyncMakePdf asyncMakePdf=new AsyncMakePdf();
					asyncMakePdf.execute(tempList());
				}
			});
		}


		public void loadItems(){
			listItems=new ArrayList();
			listItems=tempList();
			listAdapter=new ListAdapter(this,listItems);
			recyclerMoney.setAdapter(listAdapter);
			swipeMoney.setRefreshing(false);
		}



		public class AsyncMakePdf extends AsyncTask,String ,Integer>{

			AlertDialog dialogToShow;
			LayoutInflater inflater = getLayoutInflater();
			View view=inflater.inflate(R.layout.preloader_dialog,null);
			PlayGifView imgGif=view.findViewById(R.id.imgGif);
			TextView txtUpdate=view.findViewById(R.id.txtUpdate);
			AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

			String path=FOLDER_PDF+File.separator+"Report.pdf";
			PdfWriter writer;

			@Override
			protected Integer doInBackground(ArrayList... arrayLists) {

				/**
				 * Creating Document for report
				 */

				BaseFont baseFont = null;
				try {
					baseFont = BaseFont.createFont("res/font/montserratregular.ttf", "UTF-8",BaseFont.EMBEDDED);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (DocumentException e) {
					e.printStackTrace();
				}


				Font regularHead = new Font(baseFont, 15,Font.BOLD,BaseColor.WHITE);
				Font regularReport = new Font(baseFont, 30,Font.BOLD,printAccent);
				Font regularName = new Font(baseFont, 25,Font.BOLD,BaseColor.BLACK);
				Font regularAddress = new Font(baseFont, 15,Font.BOLD,BaseColor.BLACK);
				Font regularSub = new Font(baseFont, 12);
				Font regularTotal = new Font(baseFont, 16,Font.NORMAL,BaseColor.BLACK);
				Font regularTotalBold = new Font(baseFont, 16,Font.BOLD,BaseColor.BLACK);
				Font footerN = new Font(baseFont, 15,Font.BOLD,printAccent);
				Font footerE = new Font(baseFont, 12,Font.NORMAL,BaseColor.BLACK);


			 //   Document document = new Document(PageSize.A4);
				Document document = new Document(PageSize.A4, 36, 36, 36, 72);
				document.addCreationDate();
				document.addAuthor("Akhil");
				document.addCreator("logicchip.com");
				//document.setMargins(0,0,0,0);

	// Location to save
				try {
					writer =PdfWriter.getInstance(document, new FileOutputStream(path));
				} catch (DocumentException e) {
					e.printStackTrace();
				} catch (FileNotFoundException e) {
					e.printStackTrace();

				}




				PdfPTable tableFooter = new PdfPTable(1);
				tableFooter.setTotalWidth(523);

				PdfPCell footerName = new PdfPCell(new Phrase("LOGICCHIP",footerN));
				PdfPCell footerEmail = new PdfPCell(new Phrase("info@logicchip.com",footerE));

				PdfPCell footerEmpty = new PdfPCell(new Phrase(""));

				footerName.setBorder(Rectangle.NO_BORDER);
				footerEmpty.setBorder(Rectangle.NO_BORDER);
				footerEmail.setBorder(Rectangle.NO_BORDER);


				PdfPCell preBorderBlue = new PdfPCell(new Phrase(""));
				preBorderBlue.setMinimumHeight(5f);
				preBorderBlue.setUseVariableBorders(true);
				preBorderBlue.setBorder(Rectangle.TOP);
				preBorderBlue.setBorderColorTop(printPrimary);
				preBorderBlue.setBorderWidthTop(3);
				tableFooter.addCell(preBorderBlue);
				tableFooter.addCell(footerName);
				tableFooter.addCell(footerEmail);




				HeaderFooter event = new HeaderFooter(tableFooter);
				writer.setPageEvent(event);

				document.open();

				onProgressUpdate("Please wait...");


				PdfPCell preReport = new PdfPCell(new Phrase("REPORT",regularReport));


				preReport.setHorizontalAlignment(Element.ALIGN_RIGHT);
				preReport.setVerticalAlignment(Element.ALIGN_BOTTOM);
				preReport.setBorder(Rectangle.NO_BORDER);
				PdfPTable tableHeader = new PdfPTable(2);


				try {
					tableHeader.setWidths(new float[] { 1,3});
				} catch (DocumentException e) {
					e.printStackTrace();
				}

				try {
					Drawable d = getResources().getDrawable(R.drawable.logo);
					BitmapDrawable bitDw = ((BitmapDrawable) d);
					Bitmap bmp = bitDw.getBitmap();
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
					Image image = Image.getInstance(stream.toByteArray());
					// image.scaleToFit(50, 50);
					PdfPCell preImage =     new PdfPCell(image, true);
					preImage.setBorder(Rectangle.NO_BORDER);

					tableHeader.addCell(preImage);
					tableHeader.addCell(preReport);

					document.add(tableHeader);

				} catch (BadElementException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (DocumentException e) {
					e.printStackTrace();
				}




				PdfPTable tableHeading = new PdfPTable(2);
				tableHeading.setSpacingBefore(50);

				Date c = Calendar.getInstance().getTime();
				System.out.println("Current time => " + c);
				SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
				String formattedDate = df.format(c);

				String theName="",theAddress="";

				theName="Name of person";
				theAddress="Address of person";

				PdfPCell preName = new PdfPCell(new Phrase(theName,regularName));
				PdfPCell preAddress = new PdfPCell(new Phrase(theAddress,regularAddress));
				PdfPCell preDate = new PdfPCell(new Phrase("DATE: "+formattedDate,regularAddress));
				PdfPCell preBill=new PdfPCell(new Phrase("No : 0001",regularAddress));

				preBill.setVerticalAlignment(Element.ALIGN_BOTTOM);
				preBill.setHorizontalAlignment(Element.ALIGN_RIGHT);

				preDate.setVerticalAlignment(Element.ALIGN_BOTTOM);
				preDate.setHorizontalAlignment(Element.ALIGN_RIGHT);
				preName.setBorder(Rectangle.NO_BORDER);
				preAddress.setBorder(Rectangle.NO_BORDER);
				preDate.setBorder(Rectangle.NO_BORDER);
				preBill.setBorder(Rectangle.NO_BORDER);

				try {
					tableHeading.addCell(preName);
					tableHeading.addCell(preBill);
					tableHeading.addCell(preAddress);
					tableHeading.addCell(preDate);
					document.add(tableHeading);
				} catch (DocumentException e) {
					e.printStackTrace();
				}




				PdfPTable table = new PdfPTable(4);
				table.setSpacingBefore(20);
				try {
					table.setWidths(new float[] { 1f,2, 3,1.5f});
				} catch (DocumentException e) {
					e.printStackTrace();
				}
				table.setHeaderRows(1);

				table.setSplitRows(false);
				table.setComplete(false);




				PdfPCell headDate = new PdfPCell(new Phrase("NO",regularHead));
				PdfPCell headName = new PdfPCell(new Phrase("ITEM",regularHead));
				PdfPCell headDis = new PdfPCell(new Phrase("COMPANY",regularHead));
				PdfPCell headCr = new PdfPCell(new Phrase("AMOUNT",regularHead));
				PdfPCell headDe = new PdfPCell(new Phrase("DEBIT",regularHead));

				headDate.setPaddingLeft(15);
				headDate.setPaddingTop(10);
				headDate.setPaddingBottom(14);
				headDate.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headName.setPaddingTop(10);
				headName.setPaddingBottom(14);
				headName.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headDis.setPaddingTop(10);
				headDis.setPaddingBottom(14);
				headDis.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headCr.setPaddingTop(10);
				headCr.setPaddingBottom(14);
				headCr.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headDe.setPaddingTop(10);
				headDe.setPaddingBottom(14);
				headDe.setVerticalAlignment(Element.ALIGN_MIDDLE);



				headDate.setBackgroundColor(printPrimary);
				headName.setBackgroundColor(printPrimary);
				headDis.setBackgroundColor(printPrimary);
				headCr.setBackgroundColor(printPrimary);
				headDe.setBackgroundColor(printPrimary);


				headDate.setBorder(Rectangle.NO_BORDER);
				headName.setBorder(Rectangle.NO_BORDER);
				headDis.setBorder(Rectangle.NO_BORDER);
				headCr.setBorder(Rectangle.NO_BORDER);
				headDe.setBorder(Rectangle.NO_BORDER);




				table.addCell(headDate);
				table.addCell(headName);
				table.addCell(headDis);
				table.addCell(headCr);


				int amountFull=0;
				for (int aw=0;aw



HeaderFooter

HeaderFooter.java class is used for creating footer of the PDF, so users can add there company name and email at the bottom of PDF.

public class HeaderFooter extends PdfPageEventHelper {
    private PdfPTable footer;
    public HeaderFooter(PdfPTable footer) {
        this.footer = footer;
    }
    public void onEndPage(PdfWriter writer, Document document) {
        footer.writeSelectedRows(0, -1, 36, 64, writer.getDirectContent());
    }
}
Exit mobile version