I need to decode a DataMatrix in a PDF, in my case the DataMatrix it's not a image.
My first idea was transform the Page to a Image and crop the area with the DataMatrix and after decode, but it seems the (image)result it's corrupted and I can't decode properly. Any idea How I can keep the quality of the PDF??
String sourceDir = "data/test2.pdf";
File pdf = new File(sourceDir);
PDDocument document = PDDocument.load(sourceDir);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
String key;
for (PDPage page : list) {
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
BufferedImage dest = image.getSubimage(0, 2600, 800, 800);
File outputFile = new File( "data/test2.jpg");
ImageIO.write(dest, "png", outputFile);
LuminanceSource lumSource = new BufferedImageLuminanceSource (dest);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
Hashtable<DecodeHintType, Object> hint = new Hashtable<DecodeHintType, Object>();
hint.put(DecodeHintType.TRY_HARDER, BarcodeFormat.DATA_MATRIX);
DataMatrixReader DMreader = new DataMatrixReader();
try {
Result result = DMreader.decode(bitmap, hint);
System.out.println(result);
}catch(Exception e){
System.out.println("NO Data Matrix");
}
}
}
Version 2.0
PDDocument document = PDDocument.load(new File(sourceDir));
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(page, 600, ImageType.RGB);
BufferedImage datamatrixImg = bufferedImage.getSubimage(150, 6000, 600, 900);
File outputfile = new File("out/image_"+page+".jpg");
ImageIO.write(datamatrixImg, "jpg", outputfile);
LuminanceSource lumSource = new BufferedImageLuminanceSource(datamatrixImg);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
Hashtable<DecodeHintType, Object> hint = new Hashtable<DecodeHintType, Object>();
hint.put(DecodeHintType.TRY_HARDER, BarcodeFormat.DATA_MATRIX);
DataMatrixReader DMreader = new DataMatrixReader();
try {
Result result = DMreader.decode(bitmap, hint);
System.out.println("Decode: "+ result );
} catch (Exception e) {
System.out.println("No DataMatrix");
}
}
document.close();
Related
I have an xml file and .doj template file. trying to download a PDF using itext.jar and ACTRuntime.jar. It is working in java 1.6 and Websphere 7 but after migrating to java 8 and websphere 8, it is just downloading blank white pages in PDF format.
Below is the code that I'm using to produce PDF.
public ByteArrayOutputStream generatePdf(){
ArrayList<Object> bean = new ArrayList<Object>();
BeanOne beanOne = new BeanOne();
beanOne.setId(1);
beanOne.setName("Sai");
beanOne.setPhone("1234567890");
BeanOne beanOne1 = new BeanOne();
beanOne1.setId(2);
beanOne1.setName("Ram");
beanOne1.setPhone("9876543210");
bean.add(beanOne);
bean.add(beanOne1);
AppDataHandler ds = new AppDataHandler();
String tableName = "First Talbe";
Object obj= bean.get(0);
Vector fields = new Vector();
fields.addElement("id = getId");
fields.addElement("name = getName");
fields.addElement("phone = getPhone");
ds.registerObjectAsTable(obj, tableName, fields);
ds.registerDataSet(tableName, bean);
FileInputStream reportTemplateInputStream = new FileInputStream(new File("/template.jod"));
ACJEngine acjEngine = new ACJEngine();
acjEngine.readTemplate(reportTemplateInputStream);
TemplateManager templateManager = acjEngine.getTemplateManager();
templateManager.setLabel("ID", "ID");
templateManager.setLabel("NAME", "NAME");
templateManager.setLabel("PHONE", "PHONE");
acjEngine.setX11GfxAvailibility(false);
acjEngine.setDataSource(ds);
ACJOutputProcessor ec = new ACJOutputProcessor();
IViewerInterface ivi = acjEngine.generateReport();
ByteArrayOutputStream generatedPDFStream = new ByteArrayOutputStream();
ec.setPDFProperty("OutputStream", generatedPDFStream);
ec.generatePDF();
reportTemplateInputStream.close();
Object[] pdfFromActuateArray = new Object[1];
pdfFromActuateArray[0] = generatedPDFStream.toByteArray();
return mergePdfsUsingItext(pdfFromActuateArray);
}
private ByteArrayOutputStream mergePdfsUsingItext(Object[] documents) throws com.itextpdf.text.DocumentException {
ByteArrayOutputStream content = new ByteArrayOutputStream();
int f;
byte[] byteDoc = null;
for (f = 0; f < documents.length; ++f) {
byteDoc = (byte[]) documents[f];
if (byteDoc != null)
break;
}
PdfReader reader = new PdfReader(byteDoc);
int n = reader.getNumberOfPages();
Document document = new Document(reader.getPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.getInstance(document, content);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page;
int rotation;
while (f < documents.length) {
int i = 0;
while (i < n) {
i++;
document.setPageSize(reader.getPageSizeWithRotation(i));
document.newPage();
page = writer.getImportedPage(reader, i);
cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
f++;
if (f < documents.length) {
reader = new PdfReader((byte[]) documents[f]);
n = reader.getNumberOfPages();
}
}
document.close();
return content;
}
With the above code I'm getting the ByteArrayOutputStream which I'm printing on the jsp page with content-type as application/pdf.
The result pdf is completely blank. Hope Someone could explain the issue. Also please suggest any good alternative to this code.
Thanks in Advance.
I am using PDF box to create PDF, I am trying to print image into pdf , it works all the format except PNG. Mycode as follows :
String image = "c:/image.png";
PDXObjectImage ximage = null;
if( image.toLowerCase().endsWith( ".jpg" ) )
{
ximage = new PDJpeg(doc, new FileInputStream( image ) );
}
else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
{
ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
}
else
{
BufferedImage awtImage = ImageIO.read( new File( image ) );
ximage = new PDPixelMap(doc, awtImage);
throw new IOException( "Image type not supported:" + image );
}
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.drawImage( ximage, 20, 20 );
When ever I give png image it is going to the :
else
{
BufferedImage awtImage = ImageIO.read( new File( image ) );
ximage = new PDPixelMap(doc, awtImage);
//throw new IOException( "Image type not supported:" + image );
}
and showing image stream IO exception cant read image file. What changes am I need to make to accept png image also in this? Please help...
String image = "c:/"+rst.getString(8);
PDXObjectImage ximage = null;
if( image.toLowerCase().endsWith( ".jpg" ) )
{
ximage = new PDJpeg(doc, new FileInputStream( image ) );
}
else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
{
ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
}
else
{
BufferedImage awtImage = ImageIO.read( new File( image ) );
ximage = new PDPixelMap(doc, awtImage);
}
contentStream.drawXObject(ximage, 20, pageYaxis-120, 80, 80);
pageYaxis = pageYaxis-56;
After loading the image, I want to create an exact copy of the image whereby the quality and scale can remain the same. With my current code, the quality was reduced.
public class Image {
private static final String path = "C:/Users.../src/7horses.jpg";
private static final File file = new File(path);
static BufferedImage deepCopy(BufferedImage bi) throws IOException {
String saveAs = "copy.jpg";
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(null);
BufferedImage cImg = new BufferedImage(cm, raster, isAlphaPremultiplied, null);
File saveImage = new File("C:/Users.../src", saveAs);
ImageIO.write(cImg, "jpg", saveImage);
return cImg;
}
public static void main(String[] args) throws IOException {
BufferedImage cp, img;
img = ImageIO.read(file);
cp = deepCopy(img);
}
}
try just to copy your image file, use this code :
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(new File("path/to/img/src"));
os = new FileOutputStream(new File("path/to/img/dest"));
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
if you are using Java 8 then you can just call Files.copy method, check it in the docs
Go from using:
ImageIO.write(cImg, "jpg", saveImage);
To the following: (Don't have my dev environment here to test this but think I have this close for you.)
Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iterator.next();
ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();
imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParam.setCompressionQuality(1); //0 is max Compression 1 is max quality
FileImageOutputStream output = new FileImageOutputStream(saveImage);
writer.setOutput(output);
IIOImage image = new IIOImage(cImg, null, null);
writer.write(null, image, iwp);
writer.dispose();
output.close();
I am using the following code to merge two pdfs:
File firstPdfFile = new File("firstPdf.pdf");
File secondPdfFile = new File("secondPdf.pdf");
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource(firstPdfFile);
merger.addSource(secondPdfFile);
String pdfPath = "PdfFile.pdf";
OutputStream bout2 = new BufferedOutputStream(new FileOutputStream(pdfPath));
merger.setDestinationStream(bout2);
merger.mergeDocuments();
File pdfFile = new File(pdfPath);
I am getting the merged pdf correctly but I want to add page number in this pdf file.
Try this code.
File firstPdfFile = new File("firstPdf.pdf");
File secondPdfFile = new File("firstPdf.pdf");
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource(firstPdfFile);
merger.addSource(secondPdfFile);
String pdfPath = "PdfFile.pdf";
OutputStream bout2 = new BufferedOutputStream(new FileOutputStream(pdfPath));
merger.setDestinationStream(bout2);
merger.mergeDocuments();
PDDocument doc = null;
try {
URL file = new URL("file:///PdfFile.pdf");
doc = PDDocument.load(file);
List<?> allPages = doc.getDocumentCatalog().getAllPages();
PDFont font = PDType1Font.HELVETICA_BOLD;
float fontSize = 36.0f;
for (int i = 0; i < allPages.size(); i++) {
PDPage page = (PDPage) allPages.get(i);
PDPageContentStream footercontentStream = new PDPageContentStream(doc, page, true, true);
footercontentStream.beginText();
footercontentStream.setFont(font, fontSize);
footercontentStream.moveTextPositionByAmount((PDPage.PAGE_SIZE_A4.getUpperRightX() / 2), (PDPage.PAGE_SIZE_A4.getLowerLeftY()));
footercontentStream.drawString(String.valueOf(i + 1));
footercontentStream.endText();
footercontentStream.close();
}
doc.save("PdfFile.pdf");
} finally {
if (doc != null) {
doc.close();
}
}
Try below code for PDFBox 2.0
public class PageNumberExample {
final boolean isCompress = false;
final boolean isContextReset = true;
public static void main(String[] args) throws IOException {
new PageNumberExample().addPageNumber("merged PDF path");
}
public void addPageNumber(String pdfPath) throws IOException {
File mergePpdfFile = new File(pdfPath);
PDDocument document = PDDocument.load(mergePpdfFile);
int totalPage = document.getNumberOfPages();
for(int i=0; i<totalPage; i++) {
PDPage page = document.getPage(i);
PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, isCompress, isContextReset);
stream.setNonStrokingColor(Color.BLACK);
stream.beginText();
stream.setFont(PDType1Font.COURIER, 10);
stream.newLineAtOffset(100, 100); //Set position where you want to print page number.
stream.showText("Page " + (i+1) + " of " + totalPage);
stream.endText();
stream.close();
}
document.save(pdfPath);
document.close();
}
}
I am trying to add an image to a report template. I am adding the String values with this code:
form.setField("name", name);
But I can not add an image to the form using a similar code:
form.setField("photo", photo);
I searched the web but couldn't find a solution. The whole code is:
public static ByteArrayOutputStream personelSicilFormOlustur(String sablonDir, String name, byte[] photo) {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
BaseFont fontTimes = BaseFont.createFont(sablonDir + "\\" + fontName, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
BaseFont fontTimesBold = BaseFont.createFont(sablonDir + "\\" + fontNameBold, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
BaseFont fontTimesItalic = BaseFont.createFont(sablonDir + "\\" + fontNameItalic, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
PdfReader reader = new PdfReader(sablonDir + "\\" + tmSablonForSicilKaydiName);
PdfStamper stamper = new PdfStamper(reader, baos);
AcroFields form = stamper.getAcroFields();
form.setField("name", name);
form.setField("photo", photo);
stamper.setFormFlattening(true);
stamper.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
return baos;
}
}
I solved the problem with this code:
InputStream photoImage = new ByteArrayInputStream(photo);
BufferedImage bImageFromConvert = ImageIO.read(photoImage);
int type = bImageFromConvert.getType() == 0? BufferedImage.TYPE_INT_ARGB : bImageFromConvert.getType();
BufferedImage dimensionedImage = resizeImage(bImageFromConvert, type);
ImageIO.write(dimensionedImage, "jpg", new File("c:/new-darksouls.jpg"));
Image image1 = Image.getInstance("c:/new-darksouls.jpg");
image1.setAbsolutePosition(450f, 650f);
canvas.addImage(image1);