HTML to PDF conversion in JAVA | HTML to PDF example in JAVA

HTML to PDF conversion is the most searched topics on google by Java developers. So I am going to explain steps to do it with example of code.

Step 1 : In step one we will render html object like browser render it, so that DOM(Document Object Model) can be clean and fire events like “document ready” and “body onload”. We can do it with help of htmlunit and htmlcleaner jars . To learn how to do it please click on below link.

How to render HTML in java

Step 2 : If you do not want to render html string and only wants to convert it to PDF as is, then you can avoid step 1 and convert that HTML string into DOM with help of DocumentBuilder.


DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(""));
Document document = db.parse(is);

Step 3 :In step three we will convert that rendered/parsed object into PDF with help of Itext and CoreRenderer Jars. Below is the code given for it.

ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(document,"file:///"+templateLogoPath);
File pdfFile = new File(filePath+pdfFileName);
OutputStream outputStream = new FileOutputStream(pdfFile);
renderer.layout();
rootLogger.debug("Before create PDF with file name --> "+pdfFileName);
renderer.createPDF(outputStream,true);
rootLogger.debug("After create PDF with file Name -->"+pdfFileName);
renderer.finishPDF();
outputStream.flush();
outputStream.close();

This is it now you have converted PDF object.
Jars required for this are :

  1. Itext
  2. CoreRenderer

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
How to render HTML in java
Top 10 spring interview questions and their answers. Spring basic concepts.
MQ connection not closed and giving MQ Error-2009
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Advertisements

How to render HTML in java

When we open a html content in browser then browser render that html also fire events like “document.ready”,”body onload”. Java script code do whatever we write in that code for document ready function. Eg: Render some grid on Document ready,show some image on basis of some condition etc.
But when we have that html code as a string in java and we want the html rendered object(with document ready and body onload functionality) in java then we need renderer API .
We majorly get this type of requirement when we need to create PDF from html or we want to write html object as input stream on some protocol etc.
Htmlunit and HTML Cleaner is the widely used API in java for this functionality.

I am going to explain below how to use it in java .

public void renderHtml(String htmlToConvert){
HtmlCleaner cleaner = new HtmlCleaner();
ByteArrayOutputStream out = new ByteArrayOutputStream();
final WebClient webClient = new WebClient();
try
{
String htmlFileName="D:\\gaurav\htmlFile.html";
String pdfFileName=null;
File htmlFile = new File(filePath+htmlFileName);
FileWriter fileWriter = new FileWriter(htmlFile);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write(htmlToConvert);
writer.close();
fileWriter.close();
final HtmlPage page = webClient.getPage(htmlFile.toURI().toURL().toString());
final String pageAsXml = page.asXml();
system.out.println("Before tag node -->"+pageAsXml);
TagNode node = cleaner.clean(pageAsXml);
DomSerializer domSerializer = new DomSerializer(props);
Document document = domSerializer.createDOM(node);
new PrettyXmlSerializer(props).writeToStream(node, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
webClient.closeAllWindows();
if(webClient!=null && webClient.getCookieManager()!=null)
{
webClient.getCookieManager().clearCookies();
}
}
}

HtmlCleaner cleans the html. Eg: If there is a tag which is not closed then it make them close to make html proper.
Htmlunit then perform rendering.
Jars required for these functionality are given below:

  1. htmlcleaner-2.2.jar
  2. htmlunit-2.14.jar
  3. htmlunit-core-js-2.14.jar
  4. httpclient-4.3.2.jar
  5. httpcore-4.3.1.jar
  6. httpmime-4.3.2.jar

You can download these jars from sourceforge or mvnrepository .

If you want to learn how to convert this rendered HTML object into PDF please click on below link

HTML to PDF conversion in JAVA | HTML to PDF example in JAVA

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
HTML to PDF conversion in JAVA | HTML to PDF example in JAVA
Top 10 spring interview questions and their answers. Spring basic concepts.
MQ connection not closed and giving MQ Error-2009
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

String interview questions and answers

String is favourite topic of any java programmer and interviewer. Every interviewer think that at least interviewee should have knowledge about string if he is saying that he is a java developer.

Top String interview questions

Question 1 : What is String in java. Is string a data type.
Answer : It will be first question to start so your answer will be. String is not a primitive data type in java like long and int. String is a class in java which contain it’s content as character array. It resides in java.lang package. It provide different methods like equal,concat,substring etc. to provide character operations .

Question 2 : How to define String in java. What is string pool .
Answer : There are two ways to define string in java.

String s1 = new String("string1");
String s2 = "string2";

In first one we have created a new object of string class by having content as “string1”. We can also define string by only using double quotes as defined in second line. If he have not asked about string pool still it’s time that you mention stringpool to make your interview excited by telling difference between both methods. Difference between both in java is that in first one object is created in heap but in second way object will be created in string pool if only there is not a object having same content “string2” in pool. If there is an object having content “string2” in pool then JVM will point String s2 to the same object . Like in below code string3 and string2 of above code will point to same object in pool .
String s3 ="string2";
Note, benefit of string pool is that JVM is not creating so many objects for single content .

Question 3 : If two references are pointing to same object then what will happen when we perform operation on one referenced object.
Answer : Well now he wants to know if you know about immutability of string class. You will answer that as string is immutable(String class is final) in java so you can not change already created object. So if two reference will point to same object it will be same for both reference like s2 and s3 having above.
When you perform operation on s2 it will create a new object. If you want s2 to hold changed data then you have to assign s2 that new object.
s2 = s2.subString(0,1);
Now s2 have a separate object with content “s” and s3 still having object with content “string2”.

Question 4 : How can i put a string object created with new keyword in string pool.
Answer : To achieve that you have to execute intern() method on that object because by default that object will be in heap memory not in pool. This question will be asked by interviewer if he have knowledge about intern method.

Question 5 : How to compare two Strings in java program.
Answer : String class overrides equals method of object class to provide it’s own functionality and that equal method compare content of two string object and return true and false accordingly. Also there is equalsIgnoreCase method which compare string without caring about their upper case or lower case .It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison.

Question 6 : How does substring works.
Answer : Most people have used this method in his life but many of us does not have idea how doest it work internally. In substring method string class convert first string to char array. Then it define one more char array of same length. Then it took characters from first char array to another char array on basis of given index in sustring method. Well if an interviewer is smart then he may ask if original string and substring are using same length char array then it may create memory leakage then answer is yes unintentionally but yes. Only when a very big string is converting into a very small string by substring method.

Question 7 : Can we use string inside switch case.
Answer : After java7 we can use string in switch case. But upto java6 we can not use string in switch case we have make if-elseif chain to acheive this.

Question 8 : Is string threadsafe.
Answer : Due to immutabilty string is thread-safe in java because thread can not change it and it’s value will be same for every thread.

Question 9 : What is difference between String,StringBuffer,StringBuilder.
Answer : Basic difference between all three is that string is immutable class but stringbuffer and stringbuilder are not.
Between stringbuffer and stringbuilder dufference is that buffer is thread safe so it’s slow performancewise respected to builder which is not thread safe.To know detailed discussion about them go to String vs StringBuffer vs StringBuilder.

Question 10 : What are other benefits of immutable functionality of string .
Answer : Due to being immutable is popular key inside Hashmap because it can not be changed it’s hashcode is cached at time of creation so it make best choice inside hashmap key because hashmap works searching on basis of hashcode.
Also we can use string to store password due to immutabilty hacker can not change it.

Other related posts are :
String vs StringBuffer vs StringBuilder
Top 10 spring interview questions and their answers. Spring basic concepts.
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Set datasource spring bean properties dynamically if server is not available

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

String vs StringBuffer vs StringBuilder

Difference between String, StringBuffer and StringBuilder are popular interview questions in java.

Question 1 : What is difference between string and stringbuffer or stringbuilder.
Answer : String is an immutable class in java so you can not change it’s object once it is created. If you want to perform operation on this object then it will create new object. But when you want to perform operations on string value without creating multiple objects then java has provided two classes for this functionality. These classes are StringBuffer and StringBuilder. Both of these classes have all functionality provided by string without being immutable. So when should we use these two classes depends on our requirement.

For eg: If we require string value after performing multiple operations basis on some conditions then we should go for these classes.

Question 2 : What is the difference between StringBuffer and StringBuilder.
Answer : Next question of interviewer will be, If java have provided two classes then what is the difference between them or why there is two classes. Difference between these two classes is. StringBuffer is thread-safe so basically this class have synchronised methods so only one thread will access these method at a time and can change string value, so next thread will get updated value. When you are going to perform operation on string value in multi-threading environment then we should always use StringBuffer. On the other hand StringBuilder have same functionality as StringBuffer but it is not thread-safe. Then why should we use stringbuilder. Well when we want to perform operation on stringvalue in single threaded environment then we should use StringBuilder because it is much faster then stringbuffer. When we need performance in single thread environment then StringBuilder is right choice.

Other related posts are :
Top 10 spring interview questions and their answers. Spring basic concepts.
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Set datasource spring bean properties dynamically if server is not available

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Top 10 spring interview questions and their answers. Spring basic concepts.

Spring framework is the most recognized framework in java right now . So if you are thinking about changing job in java profile spring framework knowledge is must . Spring IOC and spring-mvc are two hot topics of any interviewer in java these days .The basic categorisation any interviewer will do in front of any interviewee will be :

  1. spring IOC
  2. Dependency Injection
  3. spring security
  4. spring mvc
  5. spring AOP

 

some less recognized topics also like spring jdbc , spring  JMS but they can be only ask by person who seriously worked on them.  Let’s start with spring IOC and dependency injection first.

Top10  spring interview questions and their answers

Question 1 : What is Dependency Injection

Answer :  Mostly every interviewer start interview this question of spring if he requires spring knowledge in a candidate. As it is explained by name when you injecting dependency of one  java object into another java object that is called dependency injection. Then interviewer  will ask Do I need spring framework for dependency injection then answer is  No.  We were doing it since java started with association of one java object into another that is also dependency injection . Then why do, I need spring for dependency injection. We do not need spring framework for dependency injection we need it for Inversion of control . Means without spring we need to initialize our associated class(injected) class with new   keyword of java but with spring framework is doing this for us. Now he will think that you know basic fundamental of spring at least.

Question 2 : What is Inversion of control as you mentioned in your answer and how spring is defining object for us without using new keyword.

Answer :  Now you will say that spring took control in his hand of creating object and that is called inversion of control. Second how spring is doing it . Spring took definition in xml or in annotation from us that at runtime which object is need to be injected in which one at runtime and create that object using reflection at time of container loading.

Question 3 : What is the benefit I got using spring , I could used new keyword what is the issue with that.

Answer :  Now you will explain it by writing a code below.

You will say if I have an interface called PET .

Interface Pet{}

Now I have an implementation class Dog having name as “pet” (In annotation or XML where bean is defined ) for this Pet interface.

@Named("pet")Class Dog{}

Now I have one object called Manav and this manav has a pet as dog.

Class Manav{
@inject/@autowired@named("pet")/@resource("pet")
private Pet pet;
}

Now spring will define Dog object for Pet interface at runtime. But if we were using new keyword we have to define pet  = new Dog(); inside manav and in future manav does not need Dog he need Cat now then we have to replace Dog with Cat in code everywhere but with help of spring  we will remove @named(“pet”) from Dog class and put it at Cat class like below.

@Named("pet")
Class Cat{}

and spring will initialized Pet which Manav have with cat implementation without changing any code. Now he will be satisfied that you know why we are using spring IOC.

Question 4 : What are different type of IOC.

Answer :  Two types of IOC are present in spring.

  1. Constructor Based : When container called constructor with number of arguments and use that constructor to set associated objects  value with help of those arguments.
  2. Setter Based : Setter based DI happened when container call different setter methods of associated objects to initialize those objects if a non augmented constructor found in that bean.
  3. Field Injection : Field injection happen when we define @inject on field and does not want to define it’s setter and getter . Then spring container assign value to these fields directly through reflection without calling any method.

 

Question 5 : What are different stages of a bean(Life of a bean).

Answer :  Below steps are followed.

  1. Container will look bean definition in xml or annotations and initialize that bean through reflection.
  2. If an augmented constructor is found then it will call that constructor based on arguments given in beans.xml or else call their setter methods that is also based on beans.xml .
  3. If somebody used annotation then container will look out for annotated associated objects in that bean and initialize them according to their implementations.
  4. If a BeanPostProcessor is attached with that bean then container will call overridden processBeforeInitialization() method .If an init() method is specified then it will call. If a method with nay name but having @postprocessor annotation is present then it will be called.
  5. Now bean will be in container until container will feel that there is no live reference using this bean and let java garbage collector collect this bean.
  6. If bean has implemented DisposableBean interface then destroy method will be called before this bean will be destroyed. If a method with any name but having @predestroy annotation is present then it will be called.

 

Question 6 : Difference between BeanFactory and ApplicationContext.

Answer :

A BeanFactory is like a factory class that separate beans configurations ,their dependency from actual code and instantiates the bean whenever needed. XMLBeanFactory is one of the implementation of Beanactory which takes xml file as configuration data and instantiate beans according to that XML file.

BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));

ApplicationContext is same like BeanFactory except it have some more features like. It supports multiple files as config XML. It supports bean life cycle events. It supports internationalization etc.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");

ApplicationContext is preferred way to use spring but if project require only basic functionality of spring then BeanFactory can also be used.

Question 7 : Why beans are singleton in spring. Does it make them thread unsafe.

Answer :  Beans are singleton in spring . Well if we are using beans as functionality exposures( Means services who are exposing their methods) then it will not be thread safe but if we are using beans as data carriers and trying to modifying or performing some operation on that data then it is not thread safe. For that kind of functionality we should use prototype bean or commonpool functionality of spring.

Question 8 : In how many ways, we can provide configuration data to Spring.

Answer :  We can provide configuration data in three ways to spring framework so that spring can instantiate and inject beans into each other when required.

  1. XML based configuration(Beans.xml)
  2. Annotation based configuration(@autowired/@resources etc.)
  3. Java based configuration(@inject,@named)

Question 9 : What is XML based configuration and it’s example.

Answer :  In spring we can configure beans definition and their dependency on each other in XML files and register those files with help of BeanFactory or ApplicationContext while making application up as I explained above.

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    <!-- A simple bean definition -->   <bean id="..." class="...">       <!-- collaborators and configuration for this bean go here -->   </bean></beans>

Question 10 : What is Annotation and Java based configuration and it’s example.

Answer :  In spring we can configure beans definition and their dependency on each other in java source code with help of annotations. These annotations are of two types .

  1. Spring Based : These annotations are given by spring and present in spring framework jars .They can only be used when spring framework is present in application. These annotations majorly are
    @component(To define  a unique name for bean)
    @autowwired(To autowire bean into another bean)
    @resource(To define implementation of this bean which need to bean injected at object creation it match this with @component).
  2. Java Based : These are given by java and can be used with any inversion of control framework. Noo dependency on spring. These annotations majorly are
    @named(To define unique name)
    @inject(To inject bean into another).

Other related posts are :
String interview questions and answers
String vs StringBuffer vs StringBuilder
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming

When you do not want only hibernate sequence to generate primary key of your all tables then you have three options given by JPA and Hibernate .

  1. Sequence Generator
  2. Identity Column
  3. Table Sequence

Let’s talk about Sequence generator and it’s proper use so that it won’t give you Odd and Negative Numbers as your primary key .

Sequence Generator : To use a specific named sequence object (whether it is generated by schema generation or already exists in the database) you must define a sequence generator using a @SequenceGenerator annotation. In this you provide a unique name as name tag, provide database sequence name in sequenceName tag.You can define sequencegenerator at top of class or field both. To use this sequenceGenerator you need to define @Generatedvalue tag with stratgeyType as sequence and sequenceGenerator name on field for which you want this value to be assigned.
Refer below code.


@Entity
public class Inventory implements Serializable {


@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="InvSeq")
@SequenceGenerator(name="InvSeq",sequenceName="INV_SEQ")
private long id;

We have learn how to use sequence generator but still there is possibility of Odd and Negative Numbers as primary key values.

It will happen when database sequence is already exist in database and you are not defining database through hibernate.
How it is happening: Well JPA have allocationSize tag in Sequencegenerator , value of allocationSize is 50 by default if you have not assigned any value. So when Jpa persist that record and demand sequence value from database, it treat that database sequence has incremented that value by 50 so it will substract 50 from that value and try to persist record with that value.
On the other hand database is incrementing value by it’s increment by syntax given at time of it’s defination . Which is not guaranteed to be increment by 50. So there is a possibility of value mismatch and odd value generation which could give you integrityconstraintviolation exception.
So to avoid this problem you need to define allocationSize equal to increment by of database sequence or as 1.Refer below code.

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="InvSeq")
@SequenceGenerator(name="InvSeq",sequenceName="INV_SEQ", allocationSize=1)
private long id;

If you find this post useful please follow,comment and share it.Please feel free to ask questions if you have any.

Other Related Posts :

Set datasource spring bean properties dynamically if server is not available
Logback logs are not working. Log4j logs are not working. Steps to make logging work.
MQ connection not closed and giving MQ Error-2009