Multithreaded report generation where reports are saved in PDF format

Source: Internet
Author: User
Tags readfile

The design idea uses the producer consumer model, the producer produces the report consumer expense report to generate the PDF file where the report is stored as HTML in the thread safe list. Using to technology are: multi-threaded collaboration, thread pooling, threading security, HTML generation PDF.

A Producers generate HTML templates that use Freemarker to integrate data and HTML templates through multithreading.

1. Valpdfproduce

Package Hk.buttonwood.ops.report;import Java.io.file;import Java.util.hashmap;import java.util.list;import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.linkedblockingqueue;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.timeunit;import HK.BUTTONWOOD.OPS.PDF.MSG; Import Hk.buttonwood.ops.pdf.pdfproducer;import Hk.buttonwood.ops.portfolio.portfolioservice;import Net.zweb.core.ioc.annotation.inject;import Net.zweb.core.ioc.annotation.resource;import net.zweb.core.util.fileutil;/** * @author Maybo October 31, 2015 */@Resourcepublic class Valpdfproduce {private String root = " /home/maybo/myproject/";//Save the file's root directory private String Tpath =" Src/main/webapp/web-inf/templates/ops/report/cash_ Pdf.html ";//html template file public threadpoolexecutor producerpool;public pdfproducer pdfproducer; @Injectprivate Portfolioservice portfolioservice;//Portfolio Service to get all columns private valproducer producer;public threadpoolexecutor Getproducerpool () {return this.producerpool;} public voidSetportfolioservice (Portfolioservice portfolioservice) {this.portfolioservice = Portfolioservice;}  Public valpdfproduce (String root, String Tpath, Valproducer producer) {this.root = Root;this.tpath = Tpath;this.producer = Producer;} Public Valpdfproduce () {}/* * generates PDF */public void produce (list<integer> portfolios,string from,string to,String Roo T, String Tpath, valproducer producer) {This.root=root;this.tpath=tpath;this.producer=producer;int CPU = Runtime.getruntime (). Availableprocessors (); MSG msg=new MSG ()//if portfolio exists without querying if (portfolios==null| | Portfolios.size () <=0) {//Get all portfolio list portfolios = This.portfolioService.findAll ();} if (portfolios = = NULL | | portfolios.isempty () | | Portfolios.size () <=0) {msg.state state=new msg.state (); state.setstate (Msg.State.NO_DATA); Msg.add (state); Msg.settotal ( -1); return;} Pdfproducer = Pdfproducer.newinstance (); linkedblockingqueue

2.

Package Hk.buttonwood.ops.report;import java.util.map;import hk.buttonwood.ops.pdf.exctask;/** * @author Maybo October 31, 2015 */public abstract class valproducer{/* * Save the Monthly statement data in the data template * *  @param:p Ortfolio ID *  * @param: Save the root directory of the file *  * @param: Htmlfile's Location * @param: Update date */protected abstract map<string, object> valtopdftemplate (int portfolio, String root, string html,string date),/* * Save the Monthly statement data in the data template * *  @param:p Ortfolio ID *  * @param: Save the root directory of the file *  * @par Am:htmlfile location *  * @param: Update date * @param: up to date */protected abstract map<string, object> valtopdftemplate (int Portfolio, String root, String html,string from,string to);}

3. Production tasks

Package Hk.buttonwood.ops.report;import Java.util.hashmap;import Java.util.map;import Java.util.concurrent.linkedblockingqueue;import hk.buttonwood.ops.pdf.msg;/* * Create a thread that gets the data *//** * @author Maybo * October 31, 2015 */public class Valproducetask extends thread {//thread-safe queue to store data private linkedblockingqueue

Two The consumer is also the PDF producer consuming HTML template generated PDF.

1. The underlying class implementation will be HTML to PDF.

/* To change this template, choose Tools | Templates * and open the template in the editor. */package zweb.plugins.pdf;/** * * @author John */import Java.io.bytearrayinputstream;import Java.io.file;import Java.io.fileoutputstream;import Java.util.hashmap;import Java.util.map;import Net.zweb.core.config.Config;import Net.zweb.core.config.mapconfig;import Net.zweb.core.util.fileutil;import org.apache.commons.lang.StringUtils; Import Com.itextpdf.text.basecolor;import Com.itextpdf.text.document;import Com.itextpdf.text.font;import Com.itextpdf.text.pagesize;import Com.itextpdf.text.pdf.pdfwriter;import Com.itextpdf.tool.xml.xmlworkerfontprovider;import Com.itextpdf.tool.xml.xmlworkerhelper;public class HtmlToPDF { Private HeaderFooter HeaderFooter = Null;public htmltopdf () {}public htmltopdf (HeaderFooter HeaderFooter) { This.headerfooter = HeaderFooter;} public string print (string html, map<string, object> data, String path) throws Exception {try {document document = N Ull;if (Data!=null){config<string, object> cfg = new mapconfig<string, object> (data); String pageSize = cfg.getstring ("PageSize"); String Direction = cfg.getstring ("direction"), if (Stringutils.isblank (pageSize)) {pageSize = "letter";} if (Stringutils.isblank (direction)) Direction = "verticle"; if (stringutils.equals (direction, "verticle") document = New Document (Pagesize.getrectangle (PageSize)); Vertical Printing elsedocument = new Document (Pagesize.getrectangle (PageSize). rotate ()); Transverse print}else{document = new document (Pagesize.letter);} PDFWriter PDFWriter = pdfwriter.getinstance (document, new FileOutputStream (path)); if (this.headerfooter! = null) Pdfwriter.setpageevent (HeaderFooter);d ocument.open ();d Ocument.addauthor (string.valueof (Data.get ("author")); Document.addcreator (String.valueof (Data.get ("creator"));d Ocument.addsubject (string.valueof (Data.get ("subject") ));d ocument.addcreationdate ();d ocument.addtitle (string.valueof (Data.get ("title")); Xmlworkerhelper worker = Xmlworkerhelper.getinstance ();//Worker.parseXHtml (PDFWriter, document, new StringReader (str)), worker.parsexhtml (PDFWriter, document, New Bytearrayinputstream ( Html.getbytes ()), NULL, new Xmlworkerfontprovider () {@Override public Font getfont (final string fontname, final string en          Coding, Final Boolean embedded, final float size, final int style,final basecolor color) {String fntname = FontName;              if (fntname==null) {fntname= "Arial";         Fntname= "Microsoft Jas Black";          Fntname= "Uming"; } return Super.getfont (Fntname, encoding, size, style); }});//worker.parsexhtml (PDFWriter, document, new//Bytearrayinputstream (Html.getbytes ()));d ocument.close ();} catch (Exception e) {throw e;} return null;} public static void Main (string ... args) throws Exception {string root = "Src/main/webapp"; HeaderFooter HeaderFooter = new HeaderFooter (root); Headerfooter.setprintdirection ("horizon"); Headerfooter.setx (-30 ); Headerfooter.sety (630); Headerfooter.setimg ("/images/print_holder.png"); Htmltopdf topdf = new Htmltopdf (HeaderFooter); String Path = "d:/testpdf3.pdf";//string str = fileutil.readfile (new File ("src/main/webapp/web-inf/templates/custody/ Fund/voucher/print.html ")); String str = fileutil.readfile (new File ("src/main/webapp/web-inf/templates/register/holder/print_bond.html")); map<string, object> data = new hashmap<string, object> ();d ata.put ("Author", "author");d Ata.put ("creator", "creator");d Ata.put ("Subject", "subject");d Ata.put ("title", "title");d ata.put ("direction", "Horizon");d Ata.put (" PageSize "," A4 "); Topdf.print (str, data, path);}}

2. Pdfprint basic execution generates PDF.

Package Hk.buttonwood.ops.pdf;import Java.util.map;import Org.slf4j.logger;import org.slf4j.loggerfactory;import Net.zweb.core.mvc.template.abstracttemplateengineplugin;import Net.zweb.core.mvc.template.templateengine;import Zweb.plugins.pdf.headerfooter;import Zweb.plugins.velocity.velocityplugin;public class PrintPdf implements ExcTask { Private map<string, object> data;private static templateengine engine;private HeaderFooter headerfooter;private Logger Logger=loggerfactory.getlogger (pdftask.class); static {Abstracttemplateengineplugin plugin = new Velocityplugin (); engine = Plugin.templateengine ();} Public Printpdf (map<string, object> data,headerfooter HeaderFooter) {this.data = data;this.headerfooter= HeaderFooter;} @SuppressWarnings ("unchecked") @Overridepublic void Excute () throws Exception {String html = ""; html = htmltostring ( String) data.get ("HTML"), (map<string, object>) data.get ("Datas")), if ("". Equals (HTML)) {return;} New Buildpdfutil (This.headerfooter). Build (HTML, (string) data.get ("SaveFile"), (map<string, object>) data.get ("Datas")); Logger.debug ((String) Data.get (" SaveFile ") +"---------------completed ");} /* * Integrate HTML and data together * * @param: HTML file path * * @param: Data Model */private string htmltostring (string html, map<string, object& Gt datas) {String Htl = ""; Htl = Engine.render (HTML, datas); return HTL;}}

3. Thread task generates PDF call Pdfprint

Package Hk.buttonwood.ops.pdf;import Java.util.hashmap;import Java.util.map;import Java.util.concurrent.linkedblockingqueue;import zweb.plugins.pdf.headerfooter;/** * @author Maybo October 28, 2015 Valuation Report Thread Task */public class Pdftask extends thread {//thread-safe queue to store data private linkedblockingqueue

4. Pdfproducer//Consumer

Package Hk.buttonwood.ops.pdf;import Java.util.hashmap;import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.linkedblockingqueue;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.timeunit;import Zweb.plugins.pdf.headerfooter;public class Pdfproducer {private Linkedblockingqueue

  

Multithreaded report generation where reports are saved in PDF format

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.