Create a byte array barcode using B4j - java

#Override
public String generateBrcodeForId(String Id) {
BarcodeUtil util = BarcodeUtil.getInstance();
BarcodeGenerator gen;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
gen = util.createBarcodeGenerator(buildCfg("code128"));
OutputStream fout;
fout = new FileOutputStream("code128.jpg");
byteArrayOutputStream = new ByteArrayOutputStream();
int resolution = 200;
BitmapCanvasProvider canvas = new BitmapCanvasProvider(
fout, "image/jpeg", resolution, BufferedImage.TYPE_BYTE_BINARY, false, 0);
gen.generateBarcode(canvas, "12345678");
canvas.finish();
} catch (ConfigurationException | BarcodeException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static Configuration buildCfg(String type) {
DefaultConfiguration cfg = new DefaultConfiguration("barcode");
//Bar code type
DefaultConfiguration child = new DefaultConfiguration(type);
cfg.addChild(child);
//Human readable text position
DefaultConfiguration attr = new DefaultConfiguration("human-readable");
DefaultConfiguration subAttr = new DefaultConfiguration("placement");
subAttr.setValue("bottom");
attr.addChild(subAttr);
child.addChild(attr);
return cfg;
}
Have created a bar code using Barcode4j, Here its creating a image code128.jpg. Can I create a byte array instead Of creating an image in the filesystem and send that to the web service client.

Got the solution, solved it using ByteArrayOutputStream
#Override
public byte[] generateBarcodeForId(String Id) {
BarcodeUtil util = BarcodeUtil.getInstance();
BarcodeGenerator gen;
ByteArrayOutputStream bao = null;
try {
gen = util.createBarcodeGenerator(buildCfg("code128"));
OutputStream fout;
int resolution = 100;
bao = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(
bao, "image/jpeg", resolution, BufferedImage.TYPE_BYTE_BINARY, false, 0);
gen.generateBarcode(canvas, Id);
canvas.finish();
} catch (ConfigurationException | BarcodeException | IOException e) {
e.printStackTrace();
} finally {
try {
bao.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bao.toByteArray();
}
private static Configuration buildCfg(String type) {
DefaultConfiguration cfg = new DefaultConfiguration("barcode");
//Bar code type
DefaultConfiguration child = new DefaultConfiguration(type);
cfg.addChild(child);
//Human readable text position
DefaultConfiguration attr = new DefaultConfiguration("human-readable");
DefaultConfiguration subAttr = new DefaultConfiguration("placement");
subAttr.setValue("bottom");
attr.addChild(subAttr);
child.addChild(attr);
return cfg;
}

Related

Itext7 Hebrew reverse issue

I have simple piece of code that writes a PDF sometime this PDF will contain RTL languages like Hebrew or Arabic.
I was able to manipulate the text and mirror it using Bidi (Ibm lib)
But the text is still running in reverse
In English it would be something like:
instead of:
The quick
brown fox
jumps over
the lazy dog
It appears as:
the lazy dog
jumps over
brown fox
The quick
Complete code:
#Test
public void generatePdf() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
String dest = "c:\\temp\\" + formatter.format(Calendar.getInstance().getTime()) + ".pdf";
String fontPath = "C:\\Windows\\Fonts\\ARIALUNI.TTF";
FontProgramFactory.registerFont(fontPath, "arialUnicode");
OutputStream pdfFile = null;
Document doc = null;
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
PdfFont PdfFont = PdfFontFactory.createRegisteredFont("arialUnicode", PdfEncodings.IDENTITY_H, true);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(output));
pdfDoc.setDefaultPageSize(PageSize.A4);
pdfDoc.addFont(PdfFont);
doc = new Document(pdfDoc);
doc.setBaseDirection(BaseDirection.RIGHT_TO_LEFT);
String txt = "בתשרי נתן הדקל פרי שחום נחמד בחשוון ירד יורה ועל גגי רקד בכסלו נרקיס הופיע בטבת ברד ובשבט חמה הפציעה ליום אחד. 1234 באדר עלה ניחוח מן הפרדסים בניסן הונפו בכוח כל החרמשים";
Bidi bidi = new Bidi();
bidi.setPara(txt, Bidi.RTL, null);
String mirrTxt = bidi.writeReordered(Bidi.DO_MIRRORING);
Paragraph paragraph1 = new Paragraph(mirrTxt)
.setFont(PdfFont)
.setFontSize(9)
.setTextAlignment(TextAlignment.CENTER)
.setHeight(200)
.setWidth(70);
paragraph1.setBorder(new SolidBorder(3));
doc.add(paragraph1);
Paragraph paragraph2 = new Paragraph(txt)
.setFont(PdfFont)
.setFontSize(9)
.setTextAlignment(TextAlignment.CENTER)
.setHeight(200)
.setWidth(70);
paragraph2.setBorder(new SolidBorder(3));
doc.add(paragraph2);
doc.close();
doc.flush();
pdfFile = new FileOutputStream(dest);
pdfFile.write(output.toByteArray());
ProcessBuilder b = new ProcessBuilder("cmd.exe","/C","explorer " + dest);
b.start();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {pdfFile.close();} catch (IOException e) {e.printStackTrace();}
}
}
The only solution that I have found with iText7 and IBM ICU4J without any other third party libraries is to first render the lines and then mirror them one by one. This requires a helper class LineMirroring and it's not precisely the most elegant solution, but will produce the output that you expect.
Lines mirroring class:
public class LineMirroring {
private final PageSize pageSize;
private final String fontName;
private final int fontSize;
public LineMirroring(PageSize pageSize, String fontName, int fontSize) {
this.pageSize = pageSize;
this.fontName = fontName;
this.fontSize = fontSize;
}
public String mirrorParagraph(String input, int height, int width, Border border) {
final StringBuilder mirrored = new StringBuilder();
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
PdfFont font = PdfFontFactory.createRegisteredFont(fontName, PdfEncodings.IDENTITY_H, true);
final PdfWriter writer = new PdfWriter(output);
final PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.setDefaultPageSize(pageSize);
pdfDoc.addFont(font);
final Document doc = new Document(pdfDoc);
doc.setBaseDirection(BaseDirection.RIGHT_TO_LEFT);
final LineTrackingParagraph paragraph = new LineTrackingParagraph(input);
paragraph.setFont(font)
.setFontSize(fontSize)
.setTextAlignment(TextAlignment.RIGHT)
.setHeight(height)
.setWidth(width)
.setBorder(border);
LineTrackingParagraphRenderer renderer = new LineTrackingParagraphRenderer(paragraph);
doc.add(paragraph);
Bidi bidi;
for (LineRenderer lr : paragraph.getWrittenLines()) {
bidi = new Bidi(((TextRenderer) lr.getChildRenderers().get(0)).getText().toString(), Bidi.RTL);
mirrored.append(bidi.writeReordered(Bidi.DO_MIRRORING));
}
doc.close();
pdfDoc.close();
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return mirrored.toString();
}
private class LineTrackingParagraph extends Paragraph {
private List<LineRenderer> lines;
public LineTrackingParagraph(String text) {
super(text);
}
public void addWrittenLines(List<LineRenderer> lines) {
this.lines = lines;
}
public List<LineRenderer> getWrittenLines() {
return lines;
}
#Override
protected IRenderer makeNewRenderer() {
return new LineTrackingParagraphRenderer(this);
}
}
private class LineTrackingParagraphRenderer extends ParagraphRenderer {
public LineTrackingParagraphRenderer(LineTrackingParagraph modelElement) {
super(modelElement);
}
#Override
public void drawChildren(DrawContext drawContext) {
((LineTrackingParagraph)modelElement).addWrittenLines(lines);
super.drawChildren(drawContext);
}
#Override
public IRenderer getNextRenderer() {
return new LineTrackingParagraphRenderer((LineTrackingParagraph) modelElement);
}
}
}
Minimal JUnit Test:
public class Itext7HebrewTest {
#Test
public void generatePdf() {
final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
final String dest = "F:\\Temp\\" + formatter.format(Calendar.getInstance().getTime()) + ".pdf";
final String fontPath = "C:\\Windows\\Fonts\\ARIALUNI.TTF";
final String fontName = "arialUnicode";
FontProgramFactory.registerFont(fontPath, "arialUnicode");
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
PdfFont arial = PdfFontFactory.createRegisteredFont(fontName, PdfEncodings.IDENTITY_H, true);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(output));
pdfDoc.setDefaultPageSize(PageSize.A4);
pdfDoc.addFont(arial);
LineMirroring mirroring = new LineMirroring(pdfDoc.getDefaultPageSize(), fontName,9);
Document doc = new Document(pdfDoc);
doc.setBaseDirection(BaseDirection.RIGHT_TO_LEFT);
final String txt = "בתשרי נתן הדקל פרי שחום נחמד בחשוון ירד יורה ועל גגי רקד בכסלו נרקיס הופיע בטבת ברד ובשבט חמה הפציעה ליום אחד. 1234 באדר עלה ניחוח מן הפרדסים בניסן הונפו בכוח כל החרמשים";
final int height = 200;
final int width = 70;
final Border border = new SolidBorder(3);
Paragraph paragraph1 = new Paragraph(mirroring.mirrorParagraph(txt, height, width, border));
paragraph1.setFont(arial)
.setFontSize(9)
.setTextAlignment(TextAlignment.RIGHT)
.setHeight(height)
.setWidth(width)
.setBorder(border);
doc.add(paragraph1);
doc.close();
doc.flush();
try (FileOutputStream pdfFile = new FileOutputStream(dest)) {
pdfFile.write(output.toByteArray());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Flatbuffer writing in binary file in android give only single response

I am new at flatbuffer. I had created a schema file from outside the project and adding the user(Monster as in Flatbuffer document) inside the binary via java code in android. everything works fine. but the time of reading binary file data it only gives me the user length 1. I had added 3 people but it's give me the length of monsters is 1 at the time of reading. can anyone help to figure this out. Here is the code->
this is the full code ->
enter code here
builder = new FlatBufferBuilder(1024);
public void addNewData(String emailOffset, String nameOffset,String
contactNoOffset, String DOJOffset, String departmentOffset,
String empIdOffset, float[] embeddingOffset)
{
int storeembedd = SingleJson.createEmbeddingVector(builder,
embeddingOffset);
int hereEmailOffset = builder.createString(emailOffset);
int hereNameOffset = builder.createString(nameOffset);
int hereContactOffset = builder.createString(contactNoOffset);
int hereDOJOffset = builder.createString(DOJOffset);
int hereDepartmentOffset=builder.createString(departmentOffset);
int hereImpIdOffset = builder.createString(empIdOffset);
int test = SingleJson.createSingleJson(builder, hereEmailOffset,
hereNameOffset, hereContactOffset
, hereDOJOffset, hereDepartmentOffset, hereImpIdOffset,
storeembedd);
int [] offsetOfMonster = new int[1];
offsetOfMonster[0] = test;
int temp = Monsters.createMonstersVector(builder,
offsetOfMonster);
Monsters.startMonsters(builder);
Monsters.addMonsters(builder, temp);
int orc = Monsters.endMonsters(builder);
builder.finish(orc);
byte[] buf1 = builder.sizedByteArray();
openAndAppenedInBinary(buf1);
}
private void openAndAppenedInBinary(byte[] buf1) {
FileOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(newFile());
byte[] buffer = new byte[inputStream.available()];
if (inputStream.available() == 0) {
output = new FileOutputStream(newFile(), true);
output.write(buf1);
} else {
while (inputStream.read(buffer) != -1) {
output = new FileOutputStream(newFile(), true);
output.write(buffer);
output.write(buf1);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String newFile() {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getPackageName()
+ "/binFile");
if (!file.exists()) {
if (!file.mkdir()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
Path dir = Paths.get(file.getAbsolutePath());
Files.createDirectory(dir);
} catch (IOException e) {
Path parentDir = Paths.get(file.getParent());
if (!Files.exists(parentDir)) {
try {
Files.createDirectories(parentDir);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
File binFile = new File(file, "renamed.bin");
try {
FileWriter writer = new FileWriter(binFile);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
return binFile.getAbsolutePath();
}
here is my reading code of flatbiffer->
new FlatParsingForPerticularId().execute(readRawResource(R.raw.renamed));//renamed is my bin file
private class FlatParsingForPerticularId extends AsyncTask {
#Override
protected String doInBackground(Object... params) {
byte[] buffer = (byte[]) params[0];
long startTime = System.currentTimeMillis();
ByteBuffer bb = ByteBuffer.wrap(buffer);
Monsters monsterList = Monsters.getRootAsMonsters(bb);
int length = monsterList.monstersLength();
SingleJson monster = null;
for (int i = 0; i < length; i++) {//here I m getting length 1 intead of 3
monster = monsterList.monsters(i);
if (i == outputval[0]) {
outputval[0] = (int) monster.EmpNo();
break;
}
}
long endTime = System.currentTimeMillis() - startTime;
String textToShow = "Elements: " + monsterList.monstersLength() + ": load time: " + endTime + "ms";
String[] monsterArr = monster.Name().split(" ");
return monsterArr[0];
}

Issue in creating portfolio, if internal PDF size is large

While creating portfolio pdf, if any pdf size is large or it is having large no if pages in it, then portfolio pdf is not getting created. It does not throw any error as well. Please find the code below:
public byte[] createPortFolio(String directoryName) throws DocumentException, IOException {
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("This document contains a collection of PDFs, one per Stanley Kubrick movie."));
PdfIndirectReference parentFolderObjectReference = writer.getPdfIndirectReference();
PdfDictionary parentFolderObject = GetFolderDictionary(folderCount);
parentFolderObject.put(PdfName.NAME, new PdfString("Root"));
PdfCollection collection = new PdfCollection(PdfCollection.CUSTOM);
PdfCollectionSchema schema = getCollectionSchema();
collection.setSchema(schema);
PdfCollectionSort sort = new PdfCollectionSort("File");
sort.setSortOrder(true);
collection.setSort(sort);
collection.put(new PdfName("Folders"), parentFolderObjectReference);
writer.setCollection(collection);
listFilesAndFilesSubDirectories(writer, collection, schema, directoryName, parentFolderObject, parentFolderObjectReference);
document.close();
return baos.toByteArray();
}
public void listFilesAndFilesSubDirectories(PdfWriter writer, PdfCollection collection, PdfCollectionSchema schema, String directoryName, PdfDictionary parentFolderObject, PdfIndirectReference parentIndirectReference) throws DocumentException, IOException {
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
String sStatus = "";
PdfIndirectReference siblingFolderObjectReference = null;
PdfDictionary siblingFolderObject = null;
PdfIndirectReference childFolderObjectReference = null;
PdfDictionary childFolderObject = null;
for (File file : fList) {
if (file.isFile()) {
createPdf(writer, schema, file, parentFolderObject);//adding PDF in Portfolio
} else if (file.isDirectory()) {
childFolderObjectReference = writer.getPdfIndirectReference();
folderCount++;
if (siblingFolderObject != null && parentIndirectReference.equals(siblingFolderObject.get(PdfName.PARENT))) {
siblingFolderObject.put(PdfName.NEXT, childFolderObjectReference);
writer.addToBody(siblingFolderObject, siblingFolderObjectReference);
} else {
parentFolderObject.put(new PdfName("Child"), childFolderObjectReference);
}
childFolderObject = GetFolderDictionary(folderCount);
childFolderObject.put(PdfName.NAME, new PdfString(file.getName()));
childFolderObject.put(PdfName.PARENT, parentIndirectReference);
siblingFolderObjectReference = childFolderObjectReference;
siblingFolderObject = childFolderObject;
writer.addToBody(parentFolderObject, parentIndirectReference);
writer.addToBody(childFolderObject, childFolderObjectReference);
listFilesAndFilesSubDirectories(writer, collection, schema, file.getAbsolutePath(), childFolderObject, childFolderObjectReference);
}
}
}
private void createPdf(PdfWriter writer, PdfCollectionSchema schema, File fileObj, PdfDictionary parentFolderObject) {
PdfFileSpecification fs=null;
PdfCollectionItem item;
//Adding first File
try{
fs = PdfFileSpecification.fileEmbedded(writer, fileObj.getPath(), fileObj.getName(), null, true, null, null);
//fs=fileEmbedded(writer, fileObj.getPath(), fileObj.getName(), null, true, null, null);
}
catch(Exception ex)
{
System.out.println("in Exception "+ex.getMessage());
ex.printStackTrace();
}
finally
{
System.out.println("in finally block");
}
item = new PdfCollectionItem(schema);
item.addItem("Type", "pdf");
fs.addCollectionItem(item);
try{
writer.addFileAttachment(fs);
}
catch(Exception ex)
{
System.out.println("in Exception2 "+ex.getMessage());
ex.printStackTrace();
}
finally{
System.out.println("in finally 2");
}
}
In createPdf() function, after first try block code neither runs nor throws any exception.

FileBackedOutputStream on Appengine

My application on Appengine create a csv file with more 65535 rows
But, I have an error of type OutOfMemoryError when writing :
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2271)
at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118)
at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153)
White this code :
public static byte[] joinLines(Collection<String> lines) {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
boolean firstElement = true;
for (final String part : lines) {
String value = part + LINE_SEPARATOR;
if (firstElement) {
value = addExcelPrefix(value);
firstElement = false;
}
final int currentSize = value.length();
try {
stream.write(value.getBytes(ENCODING), 0, currentSize); // OutOfMemoryError HERE
} catch (UnsupportedEncodingException e) {
LOGGER.info(e.getMessage());
}
}
return stream.toByteArray();
}
So I used FileBackedOutputStream of Guava for solve the problem of OutOfMemoryError :
public static byte[] joinLines(Collection<String> lines) throws IOException {
final FileBackedOutputStream stream = new FileBackedOutputStream(THRESHOLD, true);
boolean firstElement = true;
for (final String part : lines) {
String value = part + LINE_SEPARATOR;
if (firstElement) {
value = addExcelPrefix(value);
firstElement = false;
}
final int currentSize = value.length();
try {
stream.write(value.getBytes(ENCODING), 0, currentSize);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
return stream.asByteSource().read();
}
But, on appengine, I now an error of type SecurityException when creating of temporary file :
java.lang.SecurityException: Unable to create temporary file
at java.io.File.checkAndCreate(File.java:2083)
at java.io.File.createTempFile(File.java:2198)
at java.io.File.createTempFile(File.java:2244)
at com.google.common.io.FileBackedOutputStream.update(FileBackedOutputStream.java:196)
at com.google.common.io.FileBackedOutputStream.write(FileBackedOutputStream.java:178)
How to allow create temporary file on Appengine with FileBackedOutputStream ?
In a bucket, how ?
Thanks
I used GcsService that solves my problem :
protected String uploadBytesForCsv(Map<Integer, Map<Integer, Object>> rows) throws IOException {
LOGGER.info("Get Bytes For Csv");
final Collection<String> lines = cellsToCsv(rows);
LOGGER.info("number line : " + lines.size());
boolean firstElement = true;
final String fileName = getFileName();
final GcsFilename gcsFilename = new GcsFilename(config.getBucketName(), fileName);
final GcsService gcsService = GcsServiceFactory.createGcsService();
final GcsOutputChannel outputChannel = gcsService.createOrReplace(gcsFilename, GcsFileOptions.getDefaultInstance());
for (final String part : lines) {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
String value = part + LINE_SEPARATOR;
if (firstElement) {
value = addExcelPrefix(value);
firstElement = false;
}
final int currentSize = value.length();
try {
stream.write(value.getBytes(ENCODING), 0, currentSize);
outputChannel.write(ByteBuffer.wrap(stream.toByteArray()));
} catch (UnsupportedEncodingException e) {
LOGGER.info(e.getMessage());
}
stream.flush();
stream.close();
}
outputChannel.close();
return new UrlBuilder(config.getStorageUrlForExport())
.setBucketName(config.getBucketName())
.setFilename(fileName).build();
}

Vaadin with JasperReports?

I'm looking for a solution to create reports using JasperReports for my application. I found some examples but still could not make it work. I'm using Vaadin7
I'm trying this
public class Report {
public Report(){
createShowReport();
}
private void createShowReport(){
final Map map = new HashMap();
StreamResource.StreamSource source = new StreamResource.StreamSource() {
public InputStream getStream() {
byte[] b = null;
try {
b = JasperRunManager.runReportToPdf(getClass().getClassLoader().getResourceAsStream("br/ind/ibg/reports/report3.jasper"), map, new JREmptyDataSource());
} catch (JRException ex) {
ex.printStackTrace();
}
return new ByteArrayInputStream(b);
}
};
StreamResource resource = new StreamResource(source, "report3.pdf");
resource.setMIMEType("application/pdf");
VerticalLayout v = new VerticalLayout();
Embedded e = new Embedded("", resource);
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
v.addComponent(e);
Window w = getWindow();
w.setContent(v);
UI.getCurrent().addWindow(w);
}
private Window getWindow(){
Window w = new Window();
w.setSizeFull();
w.center();
return w;
}
}
Any idea ?
Problem seems to be on the JasperPrint printer = JasperFillManager.fillReport(file, parametros,dados); line.
Make sure that your report is found (file is not null).
In order to show the report, what I usually do is put the resulted pdf in a stream, then create a streamResource with mimeType='application\pdf' and use window.open(resource) to show it.
Example:
StreamResource.StreamSource source = new StreamResource.StreamSource() {
public InputStream getStream() {
byte[] b = null;
try {
b = JasperRunManager.runReportToPdf(getClass().getClassLoader().getResourceAsStream("reports/report3.jasper"), map, con);
} catch (JRException ex) {
ex.printStackTrace();
}
return new ByteArrayInputStream(b);
}
};
StreamResource resource = new StreamResource(source, "report3.pdf", getApplication());
resource.setMIMEType("application/pdf");
getApplication().getMainWindow().open(resource, "_new");

Categories

Resources