Reading QR code within PDF file

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Hashtable;
import java.util.Vector;

import javax.activation.DataSource;
import javax.mail.util.ByteArrayDataSource;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

	private String scanQRCode() {

		// Hints for scanning
		Vector<BarcodeFormat> decodeFormat = new Vector<BarcodeFormat>();
		decodeFormat.add(BarcodeFormat.QR_CODE);

		Hashtable<DecodeHintType, Object> hintMap = new Hashtable<DecodeHintType, Object>();
		hintMap.put(DecodeHintType.TRY_HARDER, true);
		hintMap.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormat);

		MultiFormatReader qrcodeReader = new MultiFormatReader();
		qrcodeReader.setHints(hintMap);

		try {
			// Try lowest DPI first.
			// BufferedImage pageImage = getPageImage(pageIndex, dpiSettings[i]);
			BufferedImage pageImage = getPageImage();
			LuminanceSource source = new BufferedImageLuminanceSource(pageImage);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
			// By using decodeWithState, we keep the Hints that we set earlier.
			Result result = qrcodeReader.decodeWithState(bitmap);
			String text = result.getText();
			return text;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		// This should never happen, ever...
		return null;
	}

	private BufferedImage getPageImage() throws IOException {		
		Path docPath = Paths.get("C:\\NS2\\test_files\\java3.pdf");		
		PDDocument pdfDoc = PDDocument.load(docPath.toFile());
		PDFRenderer renderer = new PDFRenderer(pdfDoc);
		// renderImageWithDPI(page number, image size, format)
		BufferedImage image = renderer.renderImageWithDPI(0, 150, ImageType.BINARY); // entire page info
		pdfDoc.close();
		return image;
	}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.