Thursday, 25 June 2015

How to print web page automatically in Java

There are different ways of printing the web page such as using windows printing service. If you need to customize web page like you want to create a table or extract certain content and the final page to be printed, you need to follow the steps.

I initially created an HTML page out of Java (POJO) using Freemarker
Generated PDF out of HTML file using iText, FlyingSaucer Library. FlyingSaucer is required as it is applying external or internal CSS styles attached in the HTML file.
Call the defaultPrinter attached to the server and then print it.


Create HTML Page:

It creates output.html page
public void processFreeMarker() throws IOException, TemplateException {
  
  Configuration cfg = new Configuration();

  
  cfg.setClassForTemplateLoading(this.getClass(), "templates");
  cfg.setDefaultEncoding("UTF-8");
  cfg.setLocale(Locale.US);
  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

  Map<String, Object> input = new HashMap<String, Object>();

  input.put("title", "Vogella example");

  input.put("exampleObject", new ValueExampleObject("Java object", "me"));

  List<ValueExampleObject> systems = new ArrayList<ValueExampleObject>();
  systems.add(new ValueExampleObject("Android", "Google"));
  systems.add(new ValueExampleObject("iOS States", "Apple"));
  systems.add(new ValueExampleObject("Ubuntu", "Canonical"));
  systems.add(new ValueExampleObject("Windows7", "Microsoft"));
  input.put("systems", systems);

  // 2.2. Get the template

  Template template = cfg.getTemplate("helloworld.ftl");

  // 2.3. Generate the output

  // Write output to the console
  Writer consoleWriter = new OutputStreamWriter(System.out);
  template.process(input, consoleWriter);

  // For the sake of example, also write output into a file:
  Writer fileWriter = new FileWriter(new File("output.html"));
  try {
   template.process(input, fileWriter);
  } finally {
   fileWriter.close();
  }

 }

Generate PDF:

public void printPdf() throws DocumentException, IOException {
  String url = new File(HTML).toURI().toURL().toString();
  OutputStream os = new FileOutputStream(PDF);

  ITextRenderer renderer = new ITextRenderer();
  renderer.setDocument(url);
  renderer.layout();
  renderer.createPDF(os);

  os.close();
 }

Print PDF:

private void print(String fileName) throws CFAException {

  // get the printer service by printer name
  PrintService pss = PrintServiceLookup.lookupDefaultPrintService();
  System.out.println("********* PSSSS ******** " + pss);
  System.out.println("Printer - " + pss.getName());
  DocPrintJob job = pss.createPrintJob();
  DocAttributeSet das = new HashDocAttributeSet();
  Doc document;
  try {
   document = new SimpleDoc(new FileInputStream(new File(fileName)), DocFlavor.INPUT_STREAM.AUTOSENSE, das);

   PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
   // job.setPrintService(pss);
   // job.setPrintable(template);
   // if (job.printDialog()) {
   job.print(document, pras);
  } catch (FileNotFoundException e) {
   throw new CustomException("", "File to be printed is not found. Please contact System Administrator", e);
  } catch (PrintException e) {
   throw new CustomException("", "Error occured while printing. Please contact System Administrator", e);
  }
 }


Reference:
StackOverflow.com

Oracle-Java Print Services


Maven Plugin:
Flying saucer 9.0.0 maven plugin is not working. So, use the following plugins to create PDF using Flying Saucer

<dependency>
   <groupId>org.xhtmlrenderer</groupId>
   <artifactId>core-renderer</artifactId>
   <version>R8pre2</version>
  </dependency>
  <dependency>
   <groupId>com.lowagie</groupId>
   <artifactId>itext</artifactId>
   <version>2.0.8</version>
  </dependency>




Supporting Libraries:
freemarker-2.3.19.jar
itext-4.2.1.jar
core-renderer-R8-final.jar
com.lowagie.text-2.1.7.jar

No comments:

Post a Comment