Adding an Image to a PDF File - java

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);

Related

Decode (No Image) DataMatrix in PDF with zXing and PDFBox

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();

Apache pdfbox .doc to .pdf conversion

I'm trying to convert .doc to .pdf, but I got this exception and I don't know how to fix it.
java.io.IOException: Missing root object specification in trailer
at org.apache.pdfbox.pdfparser.COSParser.parseTrailerValuesDynamically(COSParser.java:2042)
This is where the exception is thrown:
PDDocument pdfDocument = PDDocument.load(convertDocToPdf(documentInputStream));
Here is my conversion method:
private byte[] convertDocToPdf(InputStream documentInputStream) throws Exception {
Document document = null;
WordExtractor we = null;
ByteArrayOutputStream out = null;
byte[] documentByteArray = null;
try {
document = new Document();
POIFSFileSystem fs = new POIFSFileSystem(documentInputStream);
HWPFDocument doc = new HWPFDocument(fs);
we = new WordExtractor(doc);
out = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, out);
Range range = doc.getRange();
document.open();
writer.setPageEmpty(true);
document.newPage();
writer.setPageEmpty(true);
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
document.add(new Paragraph(paragraphs[i]));
}
documentByteArray = out.toByteArray();
} catch (Exception ex) {
ex.printStackTrace(System.out);
throw new Exception(STATE.FAILED_CONVERSION.name());
} finally {
document.close();
try {
we.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return documentByteArray;
}
You use iText classes and do
documentByteArray = out.toByteArray();
before you finish the document
document.close();
Thus, the documentByteArray only contains an incomplete PDF which PDFBox complains about.

Cant scan display image charset qr zxing android

Sorry for my english. I cant scan qr image, I have this "???????". I use zxing library. I try but not success. Bellow my code. String equals russian charset. I don't know why scan instance symbol to ??????.
final QRCodeWriter writer = new QRCodeWriter();
ImageView tnsd_iv_qr = (ImageView)findViewById(R.id.qrImage);
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
byte[] b = null;
try {
// Convert a string to UTF-8 bytes in a ByteBuffer
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(summ.getText().toString() + "/"
+ getNumber.substring(1) + "/"
+ getName + "/"
+ getIdDepartament + "/"
+ getIdUser + "/"
+ getSpinnerItem));
b = bbuf.array();
} catch (CharacterCodingException e) {
//
}
String data;
try {
data = new String(b, "UTF-8");
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
ByteMatrix bitMatrix = writer.encode( data
,BarcodeFormat.QR_CODE, 512, 512, hints);
int width = 512;
int height = 512;
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (bitMatrix.get(x, y)==0)
bmp.setPixel(x, y, Color.BLACK);
else
bmp.setPixel(x, y, Color.WHITE);
}
}
tnsd_iv_qr.setImageBitmap(bmp);
} catch (WriterException | UnsupportedEncodingException e) {
e.printStackTrace();
}
I fix this line
data = new String(b, "ISO-8859-1");
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
hints.put(EncodeHintType.CHARACTER_SET, "ISO-8859-1");
and its work!

image read and write java.lang.IllegalArgumentException

i want to create a very simple encrypt/decrypt project. but at first i want to read jpg file and write it to a file with a given password then read that file again and check the password in the file and the provided password but i get:
Exception in thread "main" java.lang.IllegalArgumentException: im == null!
at javax.imageio.ImageIO.write(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at GSM.AES.deccryption(AES.java:105)
at GSM.AES.main(AES.java:27)
My codes:
public static void main(String args[])
{
myWrite();
String encryptedFilePath = System.getProperty("user.dir")+ "\\"+"Encrypted"+".mmlooloo";
String destinationFilePath = System.getProperty("user.dir") + "\\";
try {
myRead(encryptedFilePath,destinationFilePath,"123456");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
My encrypt :
public static void myWrite() {
try {
System.out.println("Plesase Enter Number Of Pages !!!!!");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
int numberOfPage = Integer.valueOf(bufferRead.readLine().toString());
String dirName= System.getProperty("user.dir")+"\\";
byte[] base64StringEnc;
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
FileOutputStream myMatLabFileEnc = null;
String filePath = System.getProperty("user.dir")+ "\\"+"Encrypted"+".mmlooloo";
myMatLabFileEnc = new FileOutputStream (filePath);
String imagFileName;
String imgPathString;
String password = "123456";
myMatLabFileEnc.write(password.getBytes());
myMatLabFileEnc.write("\n".getBytes());
for(int i = 1 ; i<=numberOfPage ;i++)
{
imagFileName = Integer.toString(i) +".jpg";
BufferedImage img=ImageIO.read(new File(dirName,imagFileName));
ImageIO.write(img, "jpg", baos);
baos.flush();
myMatLabFileEnc.write(baos.toByteArray());
myMatLabFileEnc.write("\n".getBytes());
baos.reset();
imgPathString = dirName + imagFileName;
File f = new File(imgPathString);
f.delete();
}
myMatLabFileEnc.close();
baos.close();
return;
} catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}catch(IOException ex){
System.out.println(ex.toString());
}
}
and my decrypt:
public static int myRead(String encryptedfilePath,String encryptedFileDir,String inputPassword) throws FileNotFoundException, IOException{
FileReader encryptedFile=new FileReader(encryptedfilePath);
BufferedReader reader = new BufferedReader(encryptedFile);
String encryptedImag;
String encryptedSavesdPassword = reader.readLine();
byte []encryptedInputPassword = inputPassword.getBytes();
byte []temp = encryptedSavesdPassword.getBytes();
if(!Arrays.equals(temp,encryptedInputPassword)){
return -1;
}
int i = 1;
while((encryptedImag = reader.readLine()) != null){
byte[] bytearray = encryptedImag.getBytes();
BufferedImage imagRecover=ImageIO.read(new ByteArrayInputStream(bytearray));
String outputRecoverdFileName = Integer.toString(i)+"_recoverd.jpg";
ImageIO.write(imagRecover, "jpg", new File(encryptedFileDir,outputRecoverdFileName));
++i;
}
return 1;
}
and AES.java:105 is:
ImageIO.write(imagRecover, "jpg", new File(encryptedFileDir,outputRecoverdFileName));
i checked imagRecover is null but i do not know why? i think you can try it just name your image files like 1.jpg, 2.jpg and so on ...
Disclaimer: This is not the complete answer, but it's too long for a comment.
This is what I meant by the comment:
don't decode/encode the image in the first place. Just copy the bytes.
Using this code, you will not recompress the JPEG, and thus not lose quality.
Instead of the following code:
imagFileName = Integer.toString(i) +".jpg";
BufferedImage img=ImageIO.read(new File(dirName,imagFileName));
ImageIO.write(img, "jpg", baos);
baos.flush();
Just copy the bytes from the file to baos like this:
imagFileName = Integer.toString(i) +".jpg";
InputStream input = new FileInputStream(new File(dirName, imagFileName));
try {
copy(input, baos);
}
finally {
input.close();
}
Copy method:
public void copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, len);
}
}
Likewise, in the decrypt part, replace:
byte[] bytearray = encryptedImag.getBytes();
BufferedImage imagRecover=ImageIO.read(new ByteArrayInputStream(bytearray));
String outputRecoverdFileName = Integer.toString(i)+"_recoverd.jpg";
ImageIO.write(imagRecover, "jpg", new File(encryptedFileDir,outputRecoverdFileName));
With:
byte[] bytearray = encryptedImag.getBytes();
InputStream input = new ByteArrayInputStream(bytearray));
String outputRecoverdFileName = Integer.toString(i) + "_recoverd.jpg";
OutputStream output = new FileOutputStream(new File(encryptedFileDir, outputRecoverdFileName)));
try {
copy(input, output);
}
finally {
output.close();
}

How to add a page number to the output pdf when merging two pdfs?

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();
}
}

Categories