Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Eclipse Projects » BIRT » PDF and barcode generation through iText(PDF, barcode, iText)
icon3.gif  PDF and barcode generation through iText [message #517780] Mon, 01 March 2010 21:39 Go to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
I'm new on the BIRT designing world.

I'm using BIRT 2.5.1 and comes with iText 1.54 and I'd like to use iText barcode generation capabilities in my web app.

I can obtain a PDF "subreport" or piece if you want to call it something but I'm unable to display it on my report design. It displays once deployed ""Current report item is not supported in this report format"...

This is what I have in my servlet:

SubReport folio = new SubReport();
ByteArrayOutputStream baos = folio.getFolioBC("123456");
			
byte[] bytes = baos.toByteArray();
task.getAppContext().put("imageBarcode", bytes);


That code gets a ByteArray that starts with %PDF... and so on, so I assume it is a whole PDF with the barcode I need.

The SubReport class that outputs the ByteArrays is as follows:

public ByteArrayOutputStream getFolioBC (String folio) throws IOException, DocumentException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	Document document = new Document();
	PdfWriter writer = PdfWriter.getInstance(document, baos);
	document.open();
	PdfContentByte cb = writer.getDirectContent();

	//Barcode 3 of 9 extended
	Barcode39 code39ext = new Barcode39();
	code39ext.setCode(folio);
	code39ext.setStartStopText(false);
	code39ext.setExtended(true);
	document.add(code39ext.createImageWithBarcode(cb, null, null));

	document.close();

	return baos;
}


Can you suggest me a way in with I don't have to depend on barcode fonts?

Hope to hear from you.
Re: PDF and barcode generation through iText [message #517985 is a reply to message #517780] Tue, 02 March 2010 11:25 Go to previous messageGo to next message
Jason Weathersby is currently offline Jason Weathersby
Messages: 9167
Registered: July 2009
Senior Member

Do the byte[] only come back as a pdf? Can it be retrieved as an image?

Jason

Ivan Hoe wrote:
> I'm new on the BIRT designing world.
>
> I'm using BIRT 2.5.1 and comes with iText 1.54 and I'd like to use iText
> barcode generation capabilities in my web app.
>
> I can obtain a PDF "subreport" or piece if you want to call it something
> but I'm unable to display it on my report design. It displays once
> deployed ""Current report item is not supported in this report format"...
>
> This is what I have in my servlet:
>
>
> SubReport folio = new SubReport();
> ByteArrayOutputStream baos = folio.getFolioBC("123456");
>
> byte[] bytes = baos.toByteArray();
> task.getAppContext().put("imageBarcode", bytes);
>
>
> That code gets a ByteArray that starts with %PDF... and so on, so I
> assume it is a whole PDF with the barcode I need.
>
> The SubReport class that outputs the ByteArrays is as follows:
>
>
> public ByteArrayOutputStream getFolioBC (String folio) throws
> IOException, DocumentException {
> ByteArrayOutputStream baos = new ByteArrayOutputStream();
> Document document = new Document();
> PdfWriter writer = PdfWriter.getInstance(document, baos);
> document.open();
> PdfContentByte cb = writer.getDirectContent();
>
> //Barcode 3 of 9 extended
> Barcode39 code39ext = new Barcode39();
> code39ext.setCode(folio);
> code39ext.setStartStopText(false);
> code39ext.setExtended(true);
> document.add(code39ext.createImageWithBarcode(cb, null, null));
>
> document.close();
>
> return baos;
> }
>
>
> Can you suggest me a way in with I don't have to depend on barcode fonts?
>
> Hope to hear from you.
icon4.gif  Re: PDF and barcode generation through iText [message #517994 is a reply to message #517985] Tue, 02 March 2010 11:58 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Hey Jason, so you are the Man behind BIRT as I see. Thanks for your help but I tried with a com.lowagie.text.Image instead of a com.lowagie.text.pdf.PdfWriter to get an image raw but BIRT tells me it doesn't know the image format...

Since I already have a piece of a pdf with the barcode (as fas as I know) is there a way to insert it with some sort of obscure api method?

If you have any other approach I can use, that would be great.

Thanks man.
Re: PDF and barcode generation through iText [message #518015 is a reply to message #517994] Tue, 02 March 2010 13:10 Go to previous messageGo to next message
Jason Weathersby is currently offline Jason Weathersby
Messages: 9167
Registered: July 2009
Senior Member

Ivan,

We have a lot of developers on BIRT. I am just one of the team members.

Using iText you can combine the pdf generated from BIRT with the PDF you
generated. I will post the code at the end of this post. I would like
to play with the image a bit. If you could post your code that would be
great.

Jason


//This is just a sample. Do not start and stop the report engine more
//than once in your app as it is very expensive.



import java.util.logging.Level;

import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.PDFRenderOption;

import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;



import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;







public class CombineReportsPDF {

public void concat(byte[] ba1, byte[] ba2, String outpath){

try{

Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
writer.addJavaScript("this.print(true);", true);
document.add(new Paragraph("This is Test silent print feature"));
document.close();
writer.close();

PdfReader js1 = new PdfReader(baos.toByteArray());
PdfReader rd1 = new PdfReader( ba1 );
PdfReader rd2 = new PdfReader( ba2 );
PdfCopyFields cpy = new PdfCopyFields( new FileOutputStream( outpath ));
cpy.addDocument(js1);
cpy.addDocument(rd1);
cpy.addDocument(rd2);
cpy.close();

}catch(Exception e){
e.printStackTrace();
}

}

public void runReport() throws EngineException
{

IReportEngine engine=null;
EngineConfig config = null;

try{

config = new EngineConfig( );

config.setBIRTHome(" C:\\birt\\birt-runtime-2_2_1\\birt-runtime-2_2_1\\ReportEngi ne ");
config.setLogConfig(null, Level.OFF);
Platform.startup( config );
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject(
IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
engine = factory.createReportEngine( config );
}catch( Exception ex){
ex.printStackTrace();
}

IReportRunnable design, design2 = null;
//Open the report design
design = engine.openReportDesign("Reports/TopNPercent.rptdesign");
design2 =
engine.openReportDesign("Reports/TopSellingProducts.rptdesign ");



//Create task to run and render the report,
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
task.setParameterValue("Top Percentage", (new Integer(3)));
task.setParameterValue("Top Count", (new Integer(5)));
task.validateParameters();

PDFRenderOption options = new PDFRenderOption();
ByteArrayOutputStream fso= new ByteArrayOutputStream();
byte[] rbytes = fso.toByteArray();

FileOutputStream fsof;
try {
fsof = new FileOutputStream("c:/test/mydata.txt");
fsof.write(rbytes);
fsof.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



ByteArrayOutputStream fso2= new ByteArrayOutputStream();
options.setOutputStream(fso);
options.setOutputFormat("pdf");

task.setRenderOption(options);
task.run();
task.close();

//Create task to run and render the report,
task = engine.createRunAndRenderTask(design2);


options.setOutputStream(fso2);
options.setOutputFormat("pdf");

task.setRenderOption(options);


task.run();
task.close();

concat( fso.toByteArray(), fso2.toByteArray(),
"output/resample/Combined.pdf");

engine.destroy();
Platform.shutdown();
System.out.println("Finished");
}


/**
* @param args
*/
public static void main(String[] args) {
try
{

CombineReportsPDF ex = new CombineReportsPDF( );
ex.runReport();

}
catch ( Exception e )
{
e.printStackTrace();
}
}



}





Ivan Hoe wrote:
> Hey Jason, so you are the Man behind BIRT as I see. Thanks for your help
> but I tried with a com.lowagie.text.Image instead of a
> com.lowagie.text.pdf.PdfWriter to get an image raw but BIRT tells me it
> doesn't know the image format...
>
> Since I already have a piece of a pdf with the barcode (as fas as I
> know) is there a way to insert it with some sort of obscure api method?
>
> If you have any other approach I can use, that would be great.
>
> Thanks man.
Re: PDF and barcode generation through iText [message #518289 is a reply to message #518015] Wed, 03 March 2010 12:01 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Thanks Jason. I'll try that and keep you posted on the results.

I appreciate a lot your help and time in doing so.

Best of regards.
Re: PDF and barcode generation through iText [message #518381 is a reply to message #518015] Wed, 03 March 2010 17:54 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Hey Jason. Still playing with your code.

This is my original code:

The Servlet WebReport.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.PDFRenderOption;

public class WebReport extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IReportEngine birtReportEngine = null;
	protected static Logger logger = Logger.getLogger( "org.eclipse.birt" );

	public WebReport() {
		super();
	}

	public void init(ServletConfig sc) throws ServletException {
		BirtEngine.initBirtConfig();
		this.birtReportEngine = BirtEngine.getBirtEngine(sc.getServletContext());
	}

	public void destroy() {
		super.destroy(); 
		BirtEngine.destroyBirtEngine();
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html");
		String reportName = req.getParameter("ReportName");
		ServletContext sc = req.getSession().getServletContext();
		this.birtReportEngine = BirtEngine.getBirtEngine(sc);

		IReportRunnable design;

		try {
			design = birtReportEngine.openReportDesign( sc.getResource("/Reports/"+reportName+".rptdesign").toString().substring(6) );
			IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );		
			task.getAppContext().put("BIRT_VIEWER_HTTPSERVLET_REQUEST", req);

			// *******************************************************************
			// For barcode insertion
			SubReport folio = new SubReport();
			ByteArrayOutputStream baos = folio.getFolioBC("123456");
						
			byte[] bytes = baos.toByteArray();
			task.getAppContext().put("imageBarcode", bytes);
			// *******************************************************************

			PDFRenderOption options = new PDFRenderOption();
			options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
			resp.setHeader( "Content-Disposition", "inline; filename=\""+reportName+".pdf\"" );			
			options.setOutputStream(resp.getOutputStream());

			options.setSupportedImageFormats("JPG;BMP");

			task.setRenderOption(options);

			task.run();
			task.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException( e );
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.println(" Post Not Supported");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
}


This one is the Engine class BirtEngine.java
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;

import javax.servlet.ServletContext;

import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;

public class BirtEngine {
	private static IReportEngine birtEngine = null;
	private static Properties configProps = new Properties();
	private final static String configFile = "BirtConfig.properties";

	public static synchronized void initBirtConfig() {
		loadEngineProps();
	}

	@SuppressWarnings("unchecked")
	public static synchronized IReportEngine getBirtEngine(ServletContext sc) {
		if (birtEngine == null) {
			EngineConfig config = new EngineConfig();
			if( configProps != null){
				String logLevel = configProps.getProperty("logLevel");
				Level level = Level.OFF;
				
				if ("SEVERE".equalsIgnoreCase(logLevel)) {
					level = Level.SEVERE;
				} else if ("WARNING".equalsIgnoreCase(logLevel)) {
					level = Level.WARNING;
				} else if ("INFO".equalsIgnoreCase(logLevel)) {
					level = Level.INFO;
				} else if ("CONFIG".equalsIgnoreCase(logLevel)) {
					level = Level.CONFIG;
				} else if ("FINE".equalsIgnoreCase(logLevel)) {
					level = Level.FINE;
				} else if ("FINER".equalsIgnoreCase(logLevel)) {
					level = Level.FINER;
				} else if ("FINEST".equalsIgnoreCase(logLevel)) {
					level = Level.FINEST;
				} else if ("OFF".equalsIgnoreCase(logLevel)) {
					level = Level.OFF;
				}

				config.setLogConfig(configProps.getProperty("logDirectory"), level);
			}

			config.setEngineHome("");
			config.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, BirtEngine.class.getClassLoader()); 

			IPlatformContext context = new PlatformServletContext( sc );
			config.setPlatformContext( context );

			try {
				Platform.startup( config );
			} catch ( BirtException e ) {
				e.printStackTrace( );
			}

			IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
			birtEngine = factory.createReportEngine( config );
		}
		
		return birtEngine;
	}

	public static synchronized void destroyBirtEngine() {
		if (birtEngine == null) {
			return;
		}
		
		birtEngine.destroy();
		Platform.shutdown();
		birtEngine = null;
	}

	public Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
	}

	private static void loadEngineProps() {
		try {
			ClassLoader cl = Thread.currentThread().getContextClassLoader();
			InputStream in = null;
			in = cl.getResourceAsStream(configFile);
			configProps.load(in);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


And finally the class that constructs the barcode SubReport.java
package org.data.report.pdf;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.Barcode39;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

public class SubReport {
	public SubReport() {
	}
	
	public ByteArrayOutputStream getFolioBC (String folio) throws IOException, DocumentException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		Document document = new Document();
		
		PdfWriter writer = PdfWriter.getInstance(document, baos);
		
		document.open();
		PdfContentByte cb = writer.getDirectContent();

		//Barcode 3 of 9 extended
		Barcode39 code39ext = new Barcode39();
		code39ext.setCode(folio);
		code39ext.setStartStopText(false);
		code39ext.setExtended(true);
		document.add(code39ext.createImageWithBarcode(cb, null, null));

		document.close();
		
		return baos;
	}
}


I'm tweaking it to adapt your example code to test it.

I'll tell you my results.

Very Happy
icon4.gif  Re: PDF and barcode generation through iText [message #518397 is a reply to message #518015] Wed, 03 March 2010 18:35 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Jason,

Your example is great and I can definitely make use of it but the thing is that the part where the magic happends:

PdfReader js1 = new PdfReader(baos.toByteArray());
PdfReader rd1 = new PdfReader( ba1 );
PdfReader rd2 = new PdfReader( ba2 );
PdfCopyFields cpy = new PdfCopyFields( new FileOutputStream( outpath ));
cpy.addDocument(js1);
cpy.addDocument(rd1);
cpy.addDocument(rd2);
cpy.close();


What it does is append the documents to create a PDF. The thing is that I need to have a barcode on every page of the report.

The approach I had was to insert a dynamic image to my report.rptdesign where I intended to create the barcode using the iText that BIRT already includes. While your approach might enlight me in this quest (That is excellent to output a dozen reports in a single file Cool ) The fact to include a barcode in a report is still missing.

I know tons of developers here will thank you and like it if we can solve this issue.
Re: PDF and barcode generation through iText [message #518411 is a reply to message #518015] Wed, 03 March 2010 20:51 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Hi Jason,

I tweaked a bit your code to produce the results I wanted... Sort of.

This class:
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;

import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.PDFRenderOption;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.Barcode39;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;

public class InsertPDF {
	
	public void insert(byte[] ba1, byte[] ba2, String outpath) {
		try {
			PdfReader reader = new PdfReader(ba1);
			PdfReader reader2 = new PdfReader(ba2);
			PdfStamper stamp = new PdfStamper(reader2, new FileOutputStream(outpath));
			PdfContentByte under = stamp.getOverContent(1);
			under.addTemplate(stamp.getImportedPage(reader, 1), 420, -30);
			stamp.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	public void runReport() throws EngineException {
		IReportEngine engine = null;
		EngineConfig config = null;

		try{
			config = new EngineConfig( );

			config.setBIRTHome("C:\\birt-runtime-2_5_2\\ReportEngine");
			config.setLogConfig(null, Level.OFF);
			Platform.startup( config );
			IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
			engine = factory.createReportEngine( config );
		}catch( Exception ex){
			ex.printStackTrace();
		}

		//IReportRunnable design, design2 = null;
		IReportRunnable design2 = null;
		//Open the report design
		design2 = engine.openReportDesign("Reports/TopSellingProducts.rptdesign");

		//Create task to run and render the report,
		IRunAndRenderTask task = null;
		
		PDFRenderOption options = new PDFRenderOption();
		ByteArrayOutputStream fso = null;
		try {
			fso = getFolioBC("1234567890");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ByteArrayOutputStream fso2 = new ByteArrayOutputStream();

		//Create task to run and render the report,
		task = engine.createRunAndRenderTask(design2);
		task.setParameterValue("Top Percentage", (new Integer(3)));
		task.setParameterValue("Top Count", (new Integer(5)));
		task.validateParameters();

		options.setOutputStream(fso2);
		options.setOutputFormat("pdf");

		task.setRenderOption(options);

		task.run();
		task.close();

		insert( fso.toByteArray(), fso2.toByteArray(), "c:/temp/Watermarked.pdf");

		engine.destroy();
		Platform.shutdown();
		System.out.println("Finished");
	}
	
	public ByteArrayOutputStream getFolioBC (String folio) throws IOException, DocumentException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		Document document = new Document();
		
		PdfWriter writer = PdfWriter.getInstance(document, baos);
		
		document.open();
		PdfContentByte cb = writer.getDirectContent();

		//Barcode 3 of 9 extended
		Barcode39 code39ext = new Barcode39();
		code39ext.setCode(folio);
		code39ext.setStartStopText(false);
		code39ext.setExtended(true);
		document.add(code39ext.createImageWithBarcode(cb, null, null));

		document.close();
		
		return baos;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			InsertPDF ex = new InsertPDF( );
			ex.runReport();
		}
		catch ( Exception e ) {
			e.printStackTrace();
		}
	}
}


But since I need many different report designs, the barcode section varies its position...

Isn't there a way to place it in a container inside the report.rptdesign file like a dynamic image (my first approach)?

Thanks for your support man.

Ivan
Re: PDF and barcode generation through iText [message #518637 is a reply to message #518397] Thu, 04 March 2010 06:50 Go to previous messageGo to next message
Jason Weathersby is currently offline Jason Weathersby
Messages: 9167
Registered: July 2009
Senior Member

Ivan,

If you can get the image bytes you could use something similar to the
following image oncreate script:

importPackage(Packages.java.io);
importPackage(Packages.java.lang);

var file = new File("c:/temp/test.png");
var ist = new FileInputStream(file);
var lengthi = file.length();

bytesa = new ByteArrayOutputStream( lengthi);
var c;
while((c=ist.read()) != -1){
bytesa.write(c);
}
ist.close();
this.data = bytesa.toByteArray();


Jason

Ivan Hoe wrote:
> Jason,
>
> Your example is great and I can definitely make use of it but the thing
> is that the part where the magic happends:
>
>
> PdfReader js1 = new PdfReader(baos.toByteArray());
> PdfReader rd1 = new PdfReader( ba1 );
> PdfReader rd2 = new PdfReader( ba2 );
> PdfCopyFields cpy = new PdfCopyFields( new FileOutputStream( outpath ));
> cpy.addDocument(js1);
> cpy.addDocument(rd1);
> cpy.addDocument(rd2);
> cpy.close();
>
>
> What it does is append the documents to create a PDF. The thing is that
> I need to have a barcode on every page of the report.
>
> The approach I had was to insert a dynamic image to my report.rptdesign
> where I intended to create the barcode using the iText that BIRT already
> includes. While your approach might enlight me in this quest (That is
> excellent to output a dozen reports in a single file 8) ) The fact to
> include a barcode in a report is still missing.
>
> I know tons of developers here will thank you and like it if we can
> solve this issue.
Re: PDF and barcode generation through iText [message #519487 is a reply to message #518637] Mon, 08 March 2010 19:57 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Jason,

Sorry for this late reply.

I found a library to create Barcodes (BarCode4J) that return them as Images (and ByteArrays for the purpose here). I want to take your approach but I don't know how to get the ByteArrayOutputStream from the image I'm trying to create and put it instead of your File.

In this code of yours:
importPackage(Packages.java.io);
importPackage(Packages.java.lang);

var file = new File("c:/temp/test.png");
var ist = new FileInputStream(file);
var lengthi = file.length();

bytesa = new ByteArrayOutputStream( lengthi);
var c;
while((c=ist.read()) != -1){
bytesa.write(c);
}
ist.close();
this.data = bytesa.toByteArray();


I want to replace the line:
var file = new File("c:/temp/test.png");
var ist = new FileInputStream(file);
var lengthi = file.length();


With the ByteArraysOutputStream I already get from the Servlet while constructing the image with the barcode...

This is how I construct the image:
1. In the Report Servlet:
SubReport folio = new SubReport();
ByteArrayOutputStream baos = folio.getFolioImage("123456");

byte[] bytes = baos.toByteArray();
task.getAppContext().put("imageBarcode", bytes);


2. The image creation:
public ByteArrayOutputStream getFolioImage (String folio) throws IOException, DocumentException {
	ByteArrayOutputStream baos = null;
	
	try {
         //Create the barcode bean
         Code39Bean bean = new Code39Bean();
         
         final int dpi = 150;
         
         //Configure the barcode generator
         bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
                                                          //width exactly one pixel
         bean.setWideFactor(3);
         bean.doQuietZone(false);
         
         //Open output file
         baos = new ByteArrayOutputStream();
         
         try {
             //Set up the canvas provider for monochrome JPEG output 
             BitmapCanvasProvider canvas = new BitmapCanvasProvider(
             		baos, "image/jpeg", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
         
             //Generate the barcode
             bean.generateBarcode(canvas, folio);
         
             //Signal end of generation
             canvas.finish();
         } finally {
         	baos.close();
         }
     } catch (Exception e) {
         e.printStackTrace();
     }
	
	return baos;
}


I use a Dynamic Image as the container of these bytes as follows:
# Define "Dynamic Image" as Type
# In the DataBinding Dialog click the "Add..." Button
# Define "folio" as "Column Binding Name"
# Define "String" as "Data Type"
# Use the expression "reportContext.getAppContext().get("imageBarcode");"
# Check the checkbox in front of the "folio" entry in dialog


I'm getting a "The resource of this report item is not reachable." message instead of the actual barcode. I configure the output image to be a "image/jpeg" as you can see on my code.

Any suggestion?

Ivan

[Updated on: Mon, 08 March 2010 19:58]

Report message to a moderator

Re: PDF and barcode generation through iText [message #519495 is a reply to message #517780] Mon, 08 March 2010 21:37 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Also, I obtain the same bytes bit by bit using the following code using iText to convert to image the resulting barcode:

public ByteArrayOutputStream getFolioBC (String folio) throws IOException, DocumentException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	
	//Barcode 3 of 9 extended
	Barcode39 code39ext = new Barcode39();
	code39ext.setCode(folio);
	code39ext.setStartStopText(false);
	code39ext.setExtended(true);
	
	Image image = code39ext.createAwtImage(Color.black, Color.white);
	
	BufferedImage bffImg = new BufferedImage(image.getWidth(null),image.getHeight(null),
	BufferedImage.TYPE_3BYTE_BGR);
	Graphics offg = bffImg.createGraphics();
	offg.drawImage(image, 0, 0, null);
	
	ImageIO.write(bffImg, "jpeg", baos);
	
	return baos;
}


So I guess there's no need to use external jars since BIRT provides pretty much everything...

Ivan
Re: PDF and barcode generation through iText [message #519629 is a reply to message #519487] Tue, 09 March 2010 04:34 Go to previous messageGo to next message
Jason Weathersby is currently offline Jason Weathersby
Messages: 9167
Registered: July 2009
Senior Member

Ivan,

Can you set the image type to a dynamic image(important) an put in an
oncreate script like:

this.data = reportContext.getAppContext().get("imageBarcode");

BTW there may be an issue with the byte[] not storing properly in the
appcontext. If the above does not work try:

change
> byte[] bytes = baos.toByteArray();
> task.getAppContext().put("imageBarcode", bytes);
to
> task.getAppContext().put("imageBarcode", baos);
and the above script to

importPackage(Packages.java.io);
var ba = reportContext.getAppContext().get("imageBarcode");
this.data = ba.toByteArray();


Jason

Ivan Hoe wrote:
> Jason,
>
> Sorry for this late reply.
>
> I found a library to create Barcodes (http://barcode4j.sourceforge.net/)
> that return them as Images (and ByteArrays for the purpose here). I want
> to take your approach but I don't know how to get the
> ByteArrayOutputStream from the image I'm trying to create and put it
> instead of your File.
>
> In this code of yours:
>
> importPackage(Packages.java.io);
> importPackage(Packages.java.lang);
>
> var file = new File("c:/temp/test.png");
> var ist = new FileInputStream(file);
> var lengthi = file.length();
>
> bytesa = new ByteArrayOutputStream( lengthi);
> var c;
> while((c=ist.read()) != -1){
> bytesa.write(c);
> }
> ist.close();
> this.data = bytesa.toByteArray();
>
>
> I want to replace the line:
>
> var file = new File("c:/temp/test.png");
> var ist = new FileInputStream(file);
> var lengthi = file.length();
>
>
> With the ByteArraysOutputStream I already get from the Servlet while
> constructing the image with the barcode...
>
> This is how I construct the image:
> 1. In the Report Servlet:
>
> SubReport folio = new SubReport();
> ByteArrayOutputStream baos = folio.getFolioImage("123456");
>
> byte[] bytes = baos.toByteArray();
> task.getAppContext().put("imageBarcode", bytes);
>
>
> 2. The image creation:
>
> public ByteArrayOutputStream getFolioImage (String folio) throws
> IOException, DocumentException {
> ByteArrayOutputStream baos = null;
>
> try {
> //Create the barcode bean
> Code39Bean bean = new Code39Bean();
> final int dpi = 150;
> //Configure the barcode generator
> bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the
> narrow bar
> //width exactly one pixel
> bean.setWideFactor(3);
> bean.doQuietZone(false);
> //Open output file
> baos = new ByteArrayOutputStream();
> try {
> //Set up the canvas provider for monochrome JPEG output
> BitmapCanvasProvider canvas = new BitmapCanvasProvider(
> baos, "image/jpeg", dpi,
> BufferedImage.TYPE_BYTE_BINARY, false, 0);
> //Generate the barcode
> bean.generateBarcode(canvas, folio);
> //Signal end of generation
> canvas.finish();
> } finally {
> baos.close();
> }
> } catch (Exception e) {
> e.printStackTrace();
> }
>
> return baos;
> }
>
>
> I use a Dynamic Image as the container of this bytes as follows:
>
> # Define "Dynamic Image" as Type
> # In the DataBinding Dialog click the "Add..." Button
> # Define "folio" as "Column Binding Name"
> # Define "String" as "Data Type"
> # Use the expression "reportContext.getAppContext().get("imageBarcode");"
> # Check the checkbox in front of the "folio" entry in dialog
>
>
> I'm getting a "The resource of this report item is not reachable."
> message instead of the actual barcode. I configure the output image to
> be a "image/jpeg" as you can see on my code.
>
> Any suggestion?
>
> Ivan
Re: PDF and barcode generation through iText [message #519721 is a reply to message #519629] Tue, 09 March 2010 13:53 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Hi Jason.

I'm trying just that with no luck.

I can't find the onCreate section of the report, so I'm using the Initialize to place the script:
this.data = reportContext.getAppContext().get("imageBarcode");


But nothing changes.

Do I need to change anything on expression on the DataBinding dialog? (reportContext.getAppContext().get("imageBarcode"); )

Ivan
Re: PDF and barcode generation through iText [message #519769 is a reply to message #519721] Tue, 09 March 2010 11:34 Go to previous messageGo to next message
Jason Weathersby is currently offline Jason Weathersby
Messages: 9167
Registered: July 2009
Senior Member

Ivan,

Select the image and then hit the script tab. This will not work on any
of the report level events, it needs to be the image.

Jason

Ivan Hoe wrote:
> Hi Jason.
>
> I'm trying just that with no luck.
>
> I can't find the onCreate section of the report, so I'm using the
> Initialize to place the script:
>
> this.data = reportContext.getAppContext().get("imageBarcode");
>
>
> But nothing changes.
>
> Do I need to change anything on expression on the DataBinding dialog?
> (reportContext.getAppContext().get("imageBarcode"); )
>
> Ivan
Re: PDF and barcode generation through iText [message #519782 is a reply to message #519629] Tue, 09 March 2010 18:21 Go to previous messageGo to next message
Ivan Hoe is currently offline Ivan Hoe
Messages: 12
Registered: March 2010
Junior Member
Jason!!!! My man the first approach from your last code suggestions works alright!!!

Using the bytes[] array and nothing more than plain old iText.

Damn what a pain but thanks a lot!!!

Ivan, pleased and happy Cool
Re: PDF and barcode generation through iText [message #519811 is a reply to message #519782] Tue, 09 March 2010 17:24 Go to previous messageGo to next message
Jason Weathersby is currently offline Jason Weathersby
Messages: 9167
Registered: July 2009
Senior Member

Ivan,

It would be great if you could post an example of this in the Birt
Exchange devshare.

Glad all is well.

Jason

Ivan Hoe wrote:
> Jason!!!! My man the first approach from your last code suggestions
> works alright!!!
>
> Using the bytes[] array and nothing more than plain old iText.
>
> Damn what a pain but thanks a lot!!!
>
> Ivan, pleased and happy 8)
Re: PDF and barcode generation through iText [message #664800 is a reply to message #517780] Tue, 12 April 2011 02:39 Go to previous messageGo to next message
Adam Barlow is currently offline Adam Barlow
Messages: 1
Registered: April 2011
Junior Member
Hi,
I have applied the BIRT Barcode Plugin to generate barcodes in BIRT reports. www.onbarcode.com/products/birt_barcode

[Updated on: Mon, 30 June 2014 09:59] by Moderator

Report message to a moderator

Re: PDF and barcode generation through iText [message #664848 is a reply to message #664800] Tue, 12 April 2011 05:23 Go to previous messageGo to next message
Jason Weathersby is currently offline Jason Weathersby
Messages: 9167
Registered: July 2009
Senior Member

Adam,

Have you also put this write-up on Birt-exchange.org as a dev share item?
It would be good if you could.

Jason

On 4/12/2011 2:39 AM, Adam Barlow wrote:
> Hi,
> I have applied the BIRT Barcode Plugin to generate barcodes in BIRT
> reports.You can try BIRT Barcode
> Pluginhttp://www.onbarcode.com/products/birt_barcode/.It's easy to
> integrate.You can follow the 6 steps BIRT Barcode Generation
> Guidehttp://www.onbarcode.com/tutorial/java-barcode-eclipse- birt.html:
> 1.Download BIRT Barcode free Trial Version
> 2.Copy com.onbarcode.barcode.birt_2.2.1.jar to your Eclipse plugins
> directory ""\eclipse\plugins\""
> 3.Create a new BIRT report, and open ""Palette"", you can find a report
> item named ""Barcode"".
> 4.Drag and drop the ""Barcode"" report item to your report
> 5.It's done. You have added a barcode to your BIRT report successfully.
> 6.View more details about how to set BIRT barcode properties using BIRT
> Barcode
>
> Hope it's helpful for you.
>
Re: PDF and barcode generation through iText [message #707388 is a reply to message #664848] Mon, 01 August 2011 11:30 Go to previous messageGo to next message
Jose Carlos de Missias is currently offline Jose Carlos de Missias
Messages: 41
Registered: July 2009
Member
Hello! Ivan,

Interestingly before reading these posts and tried to use iText and BarCode4J with scripted datasource without success, Birt prints the following message in the report: "The resource of this report item is not reachable."

I am experiencing the same problems you described as solved? Using BIRT Barcode Plugin?

thanks!
Re: PDF and barcode generation through iText [message #765994 is a reply to message #707388] Wed, 14 December 2011 22:22 Go to previous messageGo to next message
Juluia  is currently offline Juluia
Messages: 5
Registered: December 2011
Junior Member
Hey!
How about trying this one(www.onbarcode.com/eclipse_birt/). Onbarcode's Eclipse Barcode provides several methods to generate and print barcodes in Eclipse BIRT reports, which may help you. Have a try!Hope it helped.
Re: PDF and barcode generation through iText [message #940020 is a reply to message #517780] Thu, 11 October 2012 04:38 Go to previous messageGo to next message
Muzammil A A is currently offline Muzammil A A
Messages: 3
Registered: October 2012
Junior Member
Is it possible to generate Barcode with text using iText?
Re: PDF and barcode generation through iText [message #941653 is a reply to message #940020] Fri, 12 October 2012 14:58 Go to previous messageGo to next message
Jason Weathersby is currently offline Jason Weathersby
Messages: 9167
Registered: July 2009
Senior Member

BIRT includes iText so you should be able to call the iText libraries to generate a barcode and return a set of image bytes in the oncreate script of an image. Do you have a snippet of Java to generate a barcode using iText?

Jason
Re: PDF and barcode generation through iText [message #969536 is a reply to message #941653] Sat, 03 November 2012 05:55 Go to previous messageGo to next message
Muzammil A A is currently offline Muzammil A A
Messages: 3
Registered: October 2012
Junior Member
My code is

public static ByteArrayOutputStream getFolioBC (String key) throws IOException, DocumentException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();

Barcode128 code128 = new Barcode128 ();
code128.setCode(key);
code128.setAltText(key);
code128.setCodeType(Barcode.CODE128);

java.awt.Image image = code128.createAwtImage(Color.black, Color.white);

BufferedImage bffImg = new BufferedImage(image.getWidth(null),image.getHeight(null),
BufferedImage.TYPE_3BYTE_BGR);
Graphics offg = bffImg.createGraphics();
offg.drawImage(image, 0, 0, null);

ImageIO.write(bffImg, "jpeg", baos);
return baos;
}

I will get ByteArrayOutputstream and put that in appcontext

task.getAppContext().put("imageBarcode", baos);

and in the onCreate script of the image I will put this code

importPackage(Packages.java.io);
var ba = reportContext.getAppContext().get("imageBarcode");
this.data = ba.toByteArray();

But I am getting only the barcode not the text below it
Re: PDF and barcode generation through iText [message #1091231 is a reply to message #517780] Wed, 21 August 2013 04:03 Go to previous messageGo to next message
clinton edgar is currently offline clinton edgar
Messages: 1
Registered: August 2013
Junior Member
hello, I'm learning the knowledge about barcode, barcode generator, QR code, and so on. I saw many people had already replied about barcode knowledge, now, I want you to help me solve a problem, is there any similarity between this one
Re: PDF and barcode generation through iText [message #1393638 is a reply to message #517780] Fri, 04 July 2014 00:02 Go to previous message
Burlesque Carillon is currently offline Burlesque Carillon
Messages: 1
Registered: July 2014
Junior Member
Adding Barcodes to PDF Forms When creating PDF forms, just adding a plug-in into the PDF software can allow the user to add barcodes in the forms. Alternatively we can process barcode generation using barcode.jar for the PDF documents. www.keepdynamic.com/java-barcode/
Previous Topic:Formatter.format for date format is not thread safe?
Next Topic:NPE when added chart
Goto Forum:
  


Current Time: Fri Aug 22 02:15:17 EDT 2014

Powered by FUDForum. Page generated in 0.03042 seconds