Tuesday, September 10, 2024

Create Pdf with ITEXT

 ITEXT is one of the most common libraries used to create pdf files. you can get the library from the maven repository. below is the latest version as of now.

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.4</version>
</dependency>

If you have fair knowledge in java, it is more than enough to create a use Itext and generate a PDF file.

you can create a java project, mostly a springboot project via https://start.spring.io/

Then you can add the maven dependency. Here i use maven, but you can use anything eg:gradle

In this example i have added

1. plain text

2. some Alignment with text

3. insert an image ( keep image in classpath)

package com.example.poc.pdf.itext.sample;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class ExperienceLetter {

private static String FILE = "C:\\Project\\PoC\\docs\\Experience.pdf";

private static Font TO = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
private static Font TO_DATA = new Font(Font.FontFamily.TIMES_ROMAN, 12);
private static Font TITLE = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD | Font.UNDERLINE);

private static Font BODY = new Font(Font.FontFamily.TIMES_ROMAN, 11);

public static void main(String[] args) {
try {
//create Doc
Document document = new Document();
// pdf file
PdfWriter.getInstance(document, new FileOutputStream(FILE));
//open doc
document.open();
// add each section
// add metadata
addMetaData(document);
//
addParaTo(document);
addTitle(document);

addBody(document, "EMPLYEE NAME", "DESIGNATION", "2022-01-01", "2024-02-01", 2);

addSignature(document);
// close doc
document.close();
} catch (DocumentException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static void addMetaData(Document document) {
document.addTitle("Sample Pdf");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Amal Prasad");
document.addCreator("Amal Prasad");
}

public static void addParaTo(Document document)
throws DocumentException {
Paragraph toPara = new Paragraph();
addEmptyLine(toPara, 1);
// Lets write a big header
toPara.add(new Paragraph("TO:", TO));

addEmptyLine(toPara, 1);
toPara.add(new Paragraph("Employee Name", TO_DATA));
toPara.add(new Paragraph("Employee ID:", TO_DATA));
toPara.add(new Paragraph("Address Line 1", TO_DATA));
toPara.add(new Paragraph("Address Line 2", TO_DATA));
toPara.add(new Paragraph("City", TO_DATA));
toPara.add(new Paragraph("Country", TO_DATA));

document.add(toPara);
}

public static void addTitle(Document document)
throws DocumentException {
// create Para
Paragraph title = new Paragraph();
title.setAlignment(Element.ALIGN_CENTER);
addEmptyLine(title, 2);
title.add(new Paragraph("TO WHOM IT MAY CONCERN", TITLE));
title.setAlignment(Element.ALIGN_CENTER);

//add para to doc
document.add(title);
}

public static void addBody(Document document, String employeeName, String designation, String workStartDate, String workEndDate, int yearsOfExperience)
throws DocumentException {
StringBuilder experience = new StringBuilder("This letter is to certify that ");
experience.append(employeeName);
experience.append(" has worked in our organisation as ");
experience.append(designation);
experience.append(".");

experience.append("He had started working here on dated ");
experience.append(workStartDate);
experience.append(" and worked till dated ");
experience.append(workEndDate);
experience.append(".");


experience.append("He had served the company for about ");
experience.append(yearsOfExperience);
experience.append(" years.");
// create Para
Paragraph body = new Paragraph();

addEmptyLine(body, 2);
body.add(new Paragraph(experience.toString(), BODY));

//add para to doc
document.add(body);

// create Para
Paragraph bodyPart2 = new Paragraph();
addEmptyLine(bodyPart2, 1);
StringBuilder expereincePart2 = new StringBuilder("Until the day he joined, he had been quite responsible.");
expereincePart2.append("To date, he has accumulated a diverse set of talents and job experiences");
expereincePart2.append("His mind blowing abilities include: Team work,Management skills and Analytical skills");
expereincePart2.append("");

bodyPart2.add(new Paragraph(expereincePart2.toString(), BODY));
document.add(bodyPart2);

Paragraph bodyPart3 = new Paragraph();
addEmptyLine(bodyPart3, 1);

StringBuilder expereincePart3 = new StringBuilder("We wish him all the best for his future endeavours.");

bodyPart3.add(new Paragraph(expereincePart3.toString(), BODY));

addEmptyLine(bodyPart3, 1);
document.add(bodyPart3);
}

public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

public static void addSignature(Document document) throws URISyntaxException, DocumentException, IOException {
String imagePath = "signature.jpg";
Path path = Paths.get(ClassLoader.getSystemResource(imagePath).toURI());
// System.out.println(path.toAbsolutePath());
// String classpath = System.getProperty("java.class.path");
// String[] classpathEntries = classpath.split(File.pathSeparator);
// System.out.println(Arrays.toString(classpathEntries));
Image signImage = Image.getInstance(path.toAbsolutePath().toString());
// signImage.setAlignment(Image.LEFT | Image.TEXTWRAP);
signImage.setAlignment(Image.ALIGN_CENTER);
// signImage.setBorder(Image.BOX);
// signImage.setBorderWidth(15);
signImage.scaleToFit(100, 100);

document.add(signImage);

//////
// create Para
Paragraph afterSignature = new Paragraph();
// addEmptyLine(afterSignature, 3);
afterSignature.add(new Paragraph("Authorized Signatory", BODY));
document.add(afterSignature);
}


}


Explaining the main functionalities

1. Create a Document

//create Doc
Document document = new Document();

2. Create PDF writer instance to write input to generating pdf.

// pdf file
PdfWriter.getInstance(document, new FileOutputStream(FILE));

3. As we have added writer, Now let's open doc.

//open doc
document.open();

4. Do the functionalities/ or operations you need.

eg: add Meta data for the pdf. This also not need. BUt you can add , if you need.

public static void addMetaData(Document document) {
document.addTitle("Sample Pdf");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Alex Crow");
document.addCreator("Alex Crow");
}

you can add Text as Paragraph. Below example will help. Here we create a Paragraph. add content as Paragraphs.  After that add the Paragraph to the document, you already opened.

public static void addParaTo(Document document)
throws DocumentException {
Paragraph toPara = new Paragraph();
addEmptyLine(toPara, 1);
// Lets write a big header
toPara.add(new Paragraph("TO:", TO));

addEmptyLine(toPara, 1);
toPara.add(new Paragraph("Employee Name", TO_DATA));
toPara.add(new Paragraph("Employee ID:", TO_DATA));
toPara.add(new Paragraph("Address Line 1", TO_DATA));
toPara.add(new Paragraph("Address Line 2", TO_DATA));
toPara.add(new Paragraph("City", TO_DATA));
toPara.add(new Paragraph("Country", TO_DATA));

document.add(toPara);
}

you can use below functionality to add some empty lines

public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

Add Image

    public static void addSignature(Document document) throws URISyntaxException, DocumentException, IOException {
String imagePath = "signature.jpg";
Path path = Paths.get(ClassLoader.getSystemResource(imagePath).toURI());
Image signImage = Image.getInstance(path.toAbsolutePath().toString());
signImage.setAlignment(Image.ALIGN_CENTER);
signImage.scaleToFit(100, 100);

document.add(signImage);
}

Here we have added an image of an signature.

5. Finally Close the doc.

// close doc
document.close();


Saturday, August 3, 2024

Flutter Dart Position and Named Arguments

 Deep Dive: Position & Named Arguments

In the previous lecture, you learned about "positional" and "named" arguments / parameters.

In general, function parameters / arguments (the term is used interchangeably here) are a key concept.

You use arguments to pass values into a function. The function may then use these parameter values to work with them - e.g., to display them on the screen, use them in a calculation or send them to another function.

In Dart (and therefore Flutter, since it uses Dart), you have two kinds of parameters you can accept in functions:

  • Positional: The position of an argument determines which parameter receives the value

  • Named: The name of an argument determines which parameter receives the value

Besides the different usage, there's one very important difference between positional and named arguments: By default, positional parameters are required and must not be omitted - on the other hand, named arguments are optional and can be omitted.

In the example above, when using named parameters, you could call add() like this:

or

When using positional parameters, calling add() like this would be invalid and hence cause an error!

You can change these behaviors, though. You can make positional arguments optional and named arguments required.

Positional arguments can be made optional by wrapping them with square brackets ([]):

Once a parameter is optional, you can also assign a default value to it - this value would be used if no value is provided for the argument:

Default values can also be assigned to named parameters - which are optional by default:

You can also make named parameters required by using the built-in required keyword:

You will, of course, see these different use-cases in action throughout the course.

Thursday, August 1, 2024

Flutter Basics and Let's start to code

 2.0

Folders

Lib -  Contain actual dart files

At start it is “main.dart” file , but as application grows you can create more folder structure

Android, MacOs , Linux, IOS -Folders comes in platforms names as this, contains platform specific files

Typically you do not need to do any changes – Flutter will take of that

Build – important folder – you won’t work here

Output files and temporary files generated by Flutter as it builds your app

Test – contains dart code - test code, automated test code for your app

.idea , .dart_tool – folders start with dot “.” Contains some extra configurations.

.idea – contain some extra configurations for Android Studio

.gitignore – version control file used by Git.  You don’t have to use Git, but don’t delete the file.

-          You cam manage snapshots

.metadata -  managed automatically by Flutter , keep track some internal information, meta data about your project.

You should not delete or Edit the file.

Analysis_option.yaml – configures some Flutter and Dart tooling that is used by code editor

-          To show you warnings and errors in code , before you even run the app

o   Amazing feature to catch errors early

-          You can dive into this file for customize.

Puspec.yml – ignore that -never managed file. You may edit when needed.

-          Add third party packages

-          Add images also

README.md – General Information about this project

-          short description about this project and resources

 

 

Flutter Code Compilation

From Top to Bottom

Code is compiled by various start and Flutter tools à and translated into native iOS and machine code ( understood by target platform)

Compiled code will executed on the mobile device

Understanding Languages

Two sections

-          Keywords

o   Import / void / const – basically highlighted or colored in Blue (depends on context , in VSCode blue, yellow for return …)

§  Built into programming language , reserved words

§  Have clear Specific meaning

-          Identifiers

o   Word as a developer defined yourself

§  Developed by developers of the programming language

§  To identify specific detail or block

·       Name given to a variable

·       Label in class in the program or function

 

Editor ( VsCode)

-          Colors for keywords and identifiers

o   Increase readability

-          Highlight error

 

 

Write First Code

-          You can edit main.dart

-          Here , we delete and start write from scratch

 

Start Write

runApp() ;  Ã  Function

-          Funtion

o   Simply instructions that can be executed

 

 

runApp() is a function and instructions provided Flutter ( neither written by you nor built into Dart programming language )

 

-          All about getting App up and running

-          Actually to show some interfaces on the screen

-          But above will give error

-          Why

-          You need to wrap these functions to other Functions

-          We must create a custom function

-          In this case start with void and identifier must be main followed by parenthesis and opening and closing braces

 

Void main () { }

-          Void  - return type

-          Main – function name

-          { } between opening and closing braces , is Function Body

-          Code should executed when this function executed

 

              Those Functions are not executed by device (mobile ) or computer on which the code runs, unless you tell computer, device to Run the instructions

How

-          Using that instruction name

o   Followed by opening and closing parenthesis

 

Void main() {}  à Defining a function

RunApp() ; à Executing (or calling ) a function

 

Now Let’s put runApp() inside main

void main(){
              runApp(); -à The function runApp() isn’t defined.
}

 

Where should runApp(); come from
Remember runApp(); coming from Flutter. But Code editor does not know?
Goto pubspec.yaml à manage dependencies
This already has dependency for “Flutter”

dependencies:
  flutter:
    sdk: flutter
 

we need to import à

              import keyword within quotes/double quotes followed by ‘package’ and colon

import 'package:';

 

Then follow ‘flutter’ 

import 'package:flutter';

 

use arrow keys to select and TAB to finish.

import 'package:flutter/material.dart';

 

Questions

What's the most important folder, in which you'll work most of the time, in a Flutter project?

The “lib” folder

Which file is the entry point for a Flutter application?

Lib/main.dart

What is the main purpose of the Dart compiler?

Convert Dart code into machine code that can run on various platforms

What are functions in programming?

    Sequence of Instructions that perform specific task.

How do you import a package in a Dart file?

    Import “package_name”

Which key "elements" are involved in the startup process of drawing a UI onto the device screen?

    The main function and the runApp() function

 

Now code looks like

 

import 'package:flutter/material.dart';
 
void main(){
  runApp();
}
 
 

But still has an error __-> 1 positional argument expected by 'runApp', but 0 found.

 

Flutter code build with widgets and you will end up with Widget tree.

1.     Material App -root app require by most other widgets

a.     Scaffold – Screen layout widget that adds base styling and more

                                               i.     Row -  Widget that displays multiple adjacent child widgets

1.     Text – Widget that displays some Text on screen

2.     Text

3.     Text