Barcode128 barcode is thicker and not scannable in iText pdf - java

I am generating code128 type barcodes, then converting it to image and then printing it on itext pdf pdfcell. The barcodes are fitting inside the cell, but the issue is the bars are thicker than it should be.
And that is why probably they are not scannable.
Can you please help on how to scael it prperly.
Below is the code-
Barcode128 code128 = new Barcode128();
code128.setCode(bc.trim());
code128.setCodeType(Barcode128.CODE128_UCC);
code128.setBarHeight(15f);
System.out.println("GETX" + code128.getX());
code128.setX(.3f);
System.out.println("After setX" + code128.getX());
java.awt.Image rawImage = code128.createAwtImage(Color.BLACK, Color.WHITE);
Image img = Image.getInstance(rawImage, null);
img.setBorder(Image.ORIGINAL_NONE);
return img;
and in the itext pdf, i'm using -
PdfPCell cell_header_barcode = new PdfPCell(BarCode.createBarcode(""+123456 ));
cell_header_barcode.setRowspan(4);
cell_header_barcode.setPaddingTop(6);
cell_header_barcode.setBackgroundColor(BaseColor.LIGHT_GRAY);
cell_header_barcode.setHorizontalAlignment(Element.ALIGN_CENTER);
cell_header_barcode.setBorder(Rectangle.NO_BORDER);
cell_header_barcode.setRowspan(4);
table_header.addCell(cell_header_barcode);
doc.add(table_header);
Thanks in advance.

Related

How can I set background fill of a run (a word in line or a paragraph) in a docx file by using Apache POI?

I know that it is possible to set the color of the run by: How can I set background colour of a run (a word in line or a paragraph) in a docx file by using Apache POI?
The relevant code is for example (see the answer in the referenced question):
XWPFRun run=paragraph.createRun();
run.setText("background color");
CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
cTShd.setVal(STShd.CLEAR);
cTShd.setColor("auto");
cTShd.setFill("00FFFF");
I would like to use an image instead as a pattern, is it possible? I know that the argument used for the fill argument is an object, so is it possible to use a picture reference or something like that?
I also know how to add directly a picture in a docx document, for example:
Image image = // my image to use
float widthEMU = // the width of the image in EMU
float heightEMU = // the height of the image in EMU
BufferedImage bimage = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(_image, 0, 0, null);
bGr.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bimage, "png", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
XWPFPicture pic = run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, "Picture", widthEMU, heightEMU);

Itextpdf blur text in pdf

Is there a way to blur text (text is not random text but it comes from db) added with showTextAligned(PdfContentByte.ALIGN_LEFT,"Random text",297,606,rotation) to PdfContentByte ? Or any other way to blur text (it can be image but the image must be generated from input text and it's not image that you added to your project) and added it to the pdf ? I'm using itextpdf:5.5.12 (on android)
Small example what i have in mind:
PdfWriter pdfWriter=PdfWriter.getInstance(document, new FileOutputStream(file));
PdfContentByte cb = pdfWriter.getDirectContent();
cb.saveState();
cb.beginText();
cb.setColorFill(baseCol);
cb.setFontAndSize(myBaseFontArialNarrowBold,7);
//some function that blurs the text ??
//here
cb.showTextAligned(PdfContentByte.ALIGN_LEFT,"Random text that we want to blur",297,638,rotation);
cb.endText();
cb.restoreState();
//another option would be to add generated image from canvas
Bitmap btmp=bBlur.getBitmap();
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
btmp.compress(Bitmap.CompressFormat.PNG, 100, stream2);
byte[] byteArray2 = stream2.toByteArray();
Image img2 = Image.getInstance(byteArray2);
cb.addImage(img,250,0,0,250,290,398);
Using canvas in android (if going with option two):
//arial narrow bold
paint.setTypeface(typeface);
paint.setColor(Color.argb(190,0,0,0));
paint.setTextAlign(Paint.Align.LEFT);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setSubpixelText(true);
paint.setLinearText(true);
//paint.setMaskFilter(new BlurMaskFilter(1, BlurMaskFilter.Blur.NORMAL));
paint.setTextSize(8);
canvas.rotate(-0.9876f);
canvas.drawText(textAr[0],6.8f,11.78f,paint);
paint.setTextSize(7);
canvas.drawText(textAr[1],6.8f,20,paint);
canvas.drawText(textAr[2],6.8f,45,paint);
canvas.setBitmap(bitmap);
The only problem with the second option is that generated text in canvas is very very bad and it doesn't look nice when image is added in pdf... So where could be a problem with "bad font"?
Any help or advice is very much appreciated.
Solution:
Going with second option.
Increase bitmap size (set Bitmap.Config.ARGB_8888), increase font size to something bigger then size 7 or 8 and then apply blur to it (in my case i increased the font size to 24), save image as bitmap and then add image to PdfContentByte or add image directly to document (apply scaleAbsolute to image and absolutePosition).

Poor image quality in itext

I am using itext7 to create pdf file
,and at the footer I am trying to add png images as follows:
PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
PdfPage page = documentEvent.getPage();
PdfCanvas canvas = new PdfCanvas(page);
byte[] signature = null; // retrieved from database
PngImageData imageData = (PngImageData) ImageDataFactory.createPng(signature);
canvas.addImageAt(imageData, 5f, 25f, false);
the original image itself has good resolution, but when the image is added to the pdf it appears with poor quality although I am adding the image without any changes or scaling.
how can I improve the image quality in the final pdf ?
This is snippet of my code for adding image to PDF:
PdfContentByte cbLogo = writer.getDirectContent();
if (instanceSettings.getDocumentHeaderImageLocation() != null) {
try {
String encodedString = instanceSettings.getDocumentHeaderImageLocation();
byte[] decodedBytes = Base64
.getDecoder()
.decode(encodedString);
Image imgLogo = Image.getInstance(decodedBytes);
imgLogo.scaleToFit(220f, 150f);
imgLogo.setAbsolutePosition((writer.getPageSize().getWidth() / 4) - (imgLogo.getScaledWidth() / 2),
writer.getPageSize().getHeight() - imgLogo.getScaledHeight() - 30);
cbLogo.addImage(imgLogo);
} catch (Exception e){
ErrorHandler.handle(e);
}
}
And here is another:
Image qr = Image.getInstance(file.getAbsolutePath());
qr.scaleToFit(70f, 70f);
qr.setSpacingBefore(0);
qr.setSpacingAfter(0);
qr.setPaddingTop(0);
PdfPCell cell = new PdfPCell();
cell.setPadding(0f);
cell.setUseAscender(true);
cell.setUseDescender(true);
cell.addElement(qr);
Image is of type:
import com.itextpdf.text.Image;
You can give it a try with this code. For me, both works as expected but as I said in the comments, I sometimes have dificulties viewing it in PDF application. As far as I know, itext has nothing to do with it.

iText 7 SVG as a background

I'm trying to add a background in a PDF using Scalable Vector Graphics (.svg). Initially the recommended way was to transform the SVG into an Image object and then use scaleToFit to get it to the right size, then add it to the document. This works partially as it transforms the small and scalable SVG into a Bitmap. Next I've made a PdfFormXObject in order to get back the scaling by having it drawn on each page. However, now it does not display anything at all.
ByteArrayInputStream inputStream = new ByteArrayInputStream(backgroundBytes);
PdfFormXObject svg = SvgConverter.convertToXObject(inputStream, pdf);
PdfCanvas canvas = new PdfCanvas(pdf.getFirstPage());
Rectangle rect = new Rectangle(PageSize.A4.getWidth(), PageSize.A4.getHeight());
canvas.addXObject(svg, rect);
How should I be adding SVG backgrounds to iText 7 PDFs? Can this be done properly in the first place? I have not been able to find good code examples.
Update:
Here is the code for converting the SVG to a properly scaled Image. The issue with this is that it works for adding the image, but it adds it as an element so it pushes everything else down.
ByteArrayInputStream inputStream = new ByteArrayInputStream(svgAsBytes);
Image image = SvgConverter.convertToImage(inputStream, pdf);
image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());
int totalPages = pdf.getNumberOfPages()+1;
for(int pageNumber = 1; pageNumber < totalPages; pageNumber++ ) {
document.add(image);
}
Hi i have a similar Problem. I am trying to add a SVG image as a table cell background. The problem is that i can not scale the image. Here is my code:
InputStream triangleSteam = this.getClass().getResourceAsStream("/AH-AddressTriangle.svg");
Image triangle = SvgConverter.convertToImage(triangleSteam, pdfDocument);
//triangle.setHeight(UnitValue.createPointValue(127.83f));
//triangle.setWidth(UnitValue.createPointValue(78.63f));
triangle.scaleAbsolute(78.63f, 127.83f);
Cell headerCell_12 = new Cell();
headerCell_12.setBorder(Border.NO_BORDER);
headerCell_12.setPadding(0f);
headerCell_12.setHeight(UnitValue.createPointValue(127.83f));
headerCell_12.setWidth(UnitValue.createPointValue(78.63f));
headerCell_12.setNextRenderer(new ImageBackgroundCellRenderer(headerCell_12, triangle));
headerTable.addCell(headerCell_12);
And here ist the BackgroundCellRenderer I am using:
protected class ImageBackgroundCellRenderer extends CellRenderer {
Image img;
public ImageBackgroundCellRenderer(Cell modelElement, Image img) {
super(modelElement);
this.img = img;
}
#Override
public IRenderer getNextRenderer() {
return new ImageBackgroundCellRenderer((Cell) modelElement, img);
}
#Override
public void draw(DrawContext drawContext) {
try {
img.scaleToFit(getOccupiedAreaBBox().getWidth(), getOccupiedAreaBBox().getHeight());
drawContext.getCanvas().addXObject(img.getXObject(), getOccupiedAreaBBox());
super.draw(drawContext);
} catch(Exception e) {
e.printStackTrace();
}
}
}
The background is added but the image is not scaled (see picture)
Screenshot from Adobe Illustrator
The SVG becomes even bigger that it actually was!
Thank you!

CMYK Image display on pdf using pdfbox

I am trying to create pdf in java using pdfbox 1.8, but problem is I am not able to show CMYK image on pdf so I try to solution on same like below code:
File filePath = new File("C:/Users/msuryawanshi/Documents/10734730431625_C1LA.jpg");
JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(new FileInputStream(filePath));
BufferedImage image = jpegDecoder.decodeAsBufferedImage();
imageUrl = "http://extranet.handgards.com/gs1/10734730431625_C1LA.jpg";
File f = new File("C:/Users/msuryawanshi/Documents/10734730431625_C1LA.jpg");
String url = "http://extranet.handgards.com/gs1/10734730431625_C1LA.jpg";
Iterator readers = ImageIO.getImageReadersByFormatName("JPEG");
ImageReader reader = null;
while (readers.hasNext()) {
reader = (ImageReader) readers.next();
if (reader.canReadRaster()) {
break;
}
}
//Stream the image file (the original CMYK image)
ImageInputStream input = ImageIO.createImageInputStream(f);
reader.setInput(input);
//Read the image raster
Raster raster = reader.readRaster(0, null);
//Create a new RGB image
BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
//Fill the new image with the old raster
bi.getRaster().setRect(raster);
PDXObjectImage ximage = new PDPixelMap(document, bi);
contentStream.drawXObject(ximage, margin + 5, texty, 170, 100);
but image is not meaningful, I have attached output pdf and original image which i want display on my pdf. please help for the same.
PDFBox doesn't support embedding CMYK images at all because java itself can't read such images. You might be able to embed it as an RGB image by using the twelvemonkeys library instead of Java ImageIO to read the JPEG into a BufferedImage. From there, just use PDPixelMap (in 1.8) or LosslessFactory (in 2.0).

Categories