Showing posts with label Printing. Show all posts
Showing posts with label Printing. Show all posts

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

Java.PrintServiceLookUp is not working in jBoss AS 7

I had a task to print a file as part of the web application. The app is deployed in jBoss AS 7.1.1. Java has given the ability to pull the network printers connected to the server by calling the following line.

PrintServiceLookup.lookupPrintServices()

You can also get the default printer connected to the server by using the code:

PrintServiceLookup.lookupDefaultPrintService()

When I use the above code in standalone java program, it pulls the printers and I was able to print it, but the same is not working while doing it through Web application. jBoss does not allow the java print services to look up on the printers connected to it. After doing analysis, I found out the following configuration solving the issues

1) Add extra tag in modules/sun/jdk/main/module.xml of jbossAs as mentioned: path name="sun/print"

<dependencies>
        <system export="true">
            <paths>
                <path name="com/sun/script/javascript"/>
                <path name="com/sun/jndi/dns"/>
                <path name="com/sun/jndi/ldap"/>
                <path name="com/sun/jndi/url"/>
                <path name="com/sun/jndi/url/dns"/>
                <path name="com/sun/security/auth"/>
                <path name="com/sun/security/auth/login"/>
                <path name="com/sun/security/auth/module"/>
                <path name="sun/misc"/>
                <path name="sun/io"/>
                <path name="sun/nio"/>
                <path name="sun/nio/ch"/>
                <path name="sun/security"/>
                <path name="sun/security/krb5"/>
                <path name="sun/util"/>
                <path name="sun/util/calendar"/>
                <path name="sun/util/locale"/>
                <path name="sun/security/provider"/>
                <path name="META-INF/services"/>
    
    <!-- Updated for implementing SAML  on 22nd June 2015-->
     <path name="javax/xml/crypto/dsig"/>
                 <path name="javax/xml/crypto"/>
                 <path name="javax/xml/crypto/dsig/dom"/>
                 <path name="javax/xml/crypto/dsig/keyinfo"/>
                 <path name="com/sun/org/apache/xml/internal/security/transforms/implementations"/>
                 <path name="org/jcp/xml/dsig/internal/dom"/>
     
     <!-- Updated for adding PrintServices to print the files from jBoss server-->
     <path name="sun/print"/>
            </paths>
            <exports>
                <include-set>
                    <path name="META-INF/services"/>
                </include-set>
            </exports>
        </system>
    </dependencies>

2) Open up resources.jar from your JRE, and extract META-INF/services/javax.print.PrintServiceLookup and copy to location modules/sun/jdk/main/service-loader-resources/META-INF/services of JbossAS.

3) Restart JBoss and run the application.