I want to generate QR code with some text using JAVA like this.
please check this image. This is how I want to generate my QR code.
(with user name and event name text)
This is my code and this generate only (QR) code, (not any additional text). If anyone know how to generate QR code with text please help me.
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class Create_QR {
public static void main(String[] args) {
try {
String qrCodeData = "This is the text";
String filePath = "C:\\Users\\Nirmalw\\Desktop\\Projects\\QR\\test\\test_img\\my_QR.png";
String charset = "UTF-8"; // or "ISO-8859-1"
Map < EncodeHintType, ErrorCorrectionLevel > hintMap = new HashMap < EncodeHintType, ErrorCorrectionLevel > ();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
BitMatrix matrix = new MultiFormatWriter().encode(new String(qrCodeData.getBytes(charset), charset),
BarcodeFormat.QR_CODE, 500, 500, hintMap);
MatrixToImageWriter.writeToFile (matrix, filePath.substring(filePath.lastIndexOf('.') + 1), new File(filePath));
System.out.println("QR Code created successfully!");
} catch (Exception e) {
System.err.println(e);
}
}
}
You can generate a QR code with text in Java using Free Spire.Barcode for Java API. First, download the API's jar from this link or install it from Maven Repository:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.barcode.free</artifactId>
<version>5.1.1</version>
</dependency>
</dependencies>
Next, refer to the following code sample:
import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
import com.spire.barcode.QRCodeECL;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class GenerateQRCode {
public static void main(String []args) throws IOException {
//Instantiate a BarcodeSettings object
BarcodeSettings settings = new BarcodeSettings();
//Set barcode type
settings.setType(BarCodeType.QR_Code);
//Set barcode data
String data = "https://stackoverflow.com/";
settings.setData(data);
//Set barcode module width
settings.setX(2);
//Set error correction level
settings.setQRCodeECL(QRCodeECL.M);
//Set top text
settings.setTopText("User Name");
//Set bottom text
settings.setBottomText("Event Name");
//Set text visibility
settings.setShowText(false);
settings.setShowTopText(true);
settings.setShowBottomText(true);
//Set border visibility
settings.hasBorder(false);
//Instantiate a BarCodeGenerator object based on the specific settings
BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
//Generate QR code image
BufferedImage bufferedImage = barCodeGenerator.generateImage();
//save the image to a .png file
ImageIO.write(bufferedImage,"png",new File("QR_Code.png"));
}
}
The following is the generated QR code image with text:
To generate a QR code in Java, we need to use a third-party library named ZXing (Zebra Crossing). It is a popular API that allows us to process with QR code. With the help of the library, we can easily generate and read the QR code. Before moving towards the Java program, we need to add the ZXing library to the project. We can download it from the official site.
zxing core-3.3.0.jar
zxing javase-3.3.0.jar
After downloading, add it to the classpath. Or add the following dependency in pom.xml file.
<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
Let's create a Java program that generates a QR code.
GenerateQrCode.java
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class GenerateQRCode
{
//static function that creates QR Code
public static void generateQRcode(String data, String path, String charset, Map map, int h, int w) throws WriterException, IOException
{
//the BitMatrix class represents the 2D matrix of bits
//MultiFormatWriter is a factory class that finds the appropriate Writer subclass for the BarcodeFormat requested and encodes the barcode with the supplied contents.
BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, w, h);
MatrixToImageWriter.writeToFile(matrix, path.substring(path.lastIndexOf('.') + 1), new File(path));
}
//main() method
public static void main(String args[]) throws WriterException, IOException, NotFoundException
{
//data that we want to store in the QR code
String str= "THE HABIT OF PERSISTENCE IS THE HABIT OF VICTORY.";
//path where we want to get QR Code
String path = "C:\\Users\\Anubhav\\Desktop\\QRDemo\\Quote.png";
//Encoding charset to be used
String charset = "UTF-8";
Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
//generates QR code with Low level(L) error correction capability
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
//invoking the user-defined method that creates the QR code
generateQRcode(str, path, charset, hashMap, 200, 200);//increase or decrease height and width accodingly
//prints if the QR code is generated
System.out.println("QR Code created successfully.");
}
}
Related
In a Java backend server application I want to decode a QR code embedded into a PDF file using the zxing library.
I adapted the example from https://gist.github.com/JoelGeraci-Datalogics/dd9e214d4c584d61f5b1 to work with the pdfbox library as follows:
ReadBarcodeFromPDF.java
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
public class ReadBarcodeFromPDF {
private static final List<String> urlList = Arrays.asList(
"http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_QRCode.pdf",
"http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_DataMatrix.pdf",
"http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_PDF417.pdf"
);
public static void main(String[] args) throws Exception {
for (String url : urlList) {
readCode(url);
}
}
private static String readCode(String url) throws MalformedURLException, IOException, NotFoundException {
URLConnection connection = new URL(url).openConnection();
connection.connect();
try (InputStream inputStream = connection.getInputStream()) {
try (PDDocument document = PDDocument.load(inputStream)) {
PDFRenderer pdfRenderer = new PDFRenderer(document);
BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(0, 300, ImageType.BINARY);
LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
HybridBinarizer hybridBinarizer = new HybridBinarizer(luminanceSource);
BinaryBitmap bitmap = new BinaryBitmap(hybridBinarizer);
MultiFormatReader reader = new MultiFormatReader();
Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(
BarcodeFormat.QR_CODE,
BarcodeFormat.DATA_MATRIX,
BarcodeFormat.PDF_417
));
hints.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
reader.setHints(hints);
Result result = reader.decodeWithState(bitmap);
return result.getText();
}
}
}
}
The example is supposed to recognize codes from PDF documents with different code types:
QR Code: http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_QRCode.pdf
Data Matrix: http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_DataMatrix.pdf
PDF417: http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_PDF417.pdf
But it fact it recognizes only the PDF417. The QR Code (in which I am interested) and the data matrix (in which I am not interested) are not recognized.
The output is
com.google.zxing.NotFoundException
com.google.zxing.NotFoundException
11/15/2010 Tony Blue
I also tried
Different arguments in line
pdfRenderer.renderImageWithDPI(0, 300, ImageType.BINARY);
Different values for dpi (2nd argument) between 100 and 300
All available values for imageType (3rd argument)
Newest version of the library (3.5.0)
pom.xml
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.26</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
Your code works if one removes
hints.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);
I suspect that ZXIng only checks whether there is an entry for the key and not its value. The javadoc mentions "Doesn't matter what it maps to; use Boolean.TRUE."
If we search image to qr code, there are many websites which converts image to qr code online.
But how can I do this in java?
I am using the following code for converting text to qr code:-
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class MyQr {
public static void createQR(String data, String path,
String charset, Map hashMap,
int height, int width)
throws WriterException, IOException
{
BitMatrix matrix = new MultiFormatWriter().encode(
new String(data.getBytes(charset), charset),
BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToFile(
matrix,
path.substring(path.lastIndexOf('.') + 1),
new File(path));
}
public static void main(String[] args)
throws WriterException, IOException,
NotFoundException
{
String data = "TEXT IN QR CODE";
String path = "image.png";
String charset = "UTF-8";
Map<EncodeHintType, ErrorCorrectionLevel> hashMap
= new HashMap<EncodeHintType,
ErrorCorrectionLevel>();
hashMap.put(EncodeHintType.ERROR_CORRECTION,
ErrorCorrectionLevel.L);
createQR(data, path, charset, hashMap, 200, 200);
}
}
But how to encode a image in qr code?
Images are too big to be embedded into QR codes (with the exception of tiny icons). So instead, the image is put on a publicly accessible server and the URL of the image is embedded in the QR code.
Thus you need access to a server that can fulfill this. That's probably the bigger part of what you are about to implement.
Otherwise, it's straight-forward:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class MyQr {
/**
* Uploads the image to a server and returns to image URL.
* #param imagePath path to the image
* #return image URL
*/
public static URL uploadImage(String imagePath)
{
// implement a solution to put an image on a public server
try {
return new URL("https://yourserver/some_path/image.jpg");
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public static void createQR(String payloadImagePath, String qrCodeImagePath,
Map<EncodeHintType, ?> hints, int height, int width)
throws WriterException, IOException
{
URL imageURL = uploadImage(payloadImagePath);
BitMatrix matrix = new MultiFormatWriter().encode(
imageURL.toString(), BarcodeFormat.QR_CODE, width, height, hints);
String imageFormat = qrCodeImagePath.substring(qrCodeImagePath.lastIndexOf('.') + 1);
MatrixToImageWriter.writeToPath(matrix, imageFormat, Path.of(qrCodeImagePath));
}
public static void main(String[] args)
throws WriterException, IOException
{
String payloadImagePath = "embed_this.jpg";
String qrCodeImagePath = "qrcode.png";
Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
createQR(payloadImagePath, qrCodeImagePath, hints, 200, 200);
}
}
BTW: The below code (from your code sample) is non-sense. At best, it creates a copy of the string, which is unnecessary. At worst, it corrupts all characters not supported by charset. I don't think you intended either one.
new String(data.getBytes(charset), charset)
I assume that you mean that you want to add an image (e.g. logo) to the QR Code.
This is generally done by overlaying a small image on top of the QR Code, usually in the center. QR Codes are still readable when a small portion is obscured, especially in the center.
You can use MatrixToImageWriter.toBufferedImage(matrix) to get a BufferedImage containing the QR Code image, and then use Java image methods to overlay the image. See, for example, overlay images in java
I want to create pptx file having linked-Video in slides using Apache-poi.
I got one example in Apache-Examples code
poi-4.1.2\src\scratchpad\testcases\org\apache\poi\hslf\model\TestMovieShape.
Using this example I can able to create .ppt file but it's not creating .pptx file.
Also using this example media-controls are not visible.
Only a few lines needed to be changed opposed to the embedded video case.
The video URI is not a real URI, but simply a relative .mp4 filename in the same directory. Although I haven't tested it, absolute file URIs should also work.
I haven't implemented the frame extraction, as it's mentioned in the embedded example - so either look for an archived version of xuggler or find a different library to extract the preview image.
Tested with Powerpoint 2016 / POI 5.0.0-Snapshot.
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink;
import org.openxmlformats.schemas.presentationml.x2006.main.*;
import javax.xml.namespace.QName;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS;
public class LinkVideoToPptx {
public static void main(String[] args) throws IOException, URISyntaxException {
XMLSlideShow pptx = new XMLSlideShow();
String videoFileName = "file_example_MP4_640_3MG.mp4";
XSLFSlide slide1 = pptx.createSlide();
PackagePart pp = slide1.getPackagePart();
URI mp4uri = new URI("./"+videoFileName);
PackageRelationship prsEmbed1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.microsoft.com/office/2007/relationships/media");
PackageRelationship prsExec1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
File previewJpg = new File("preview.jpg");
XSLFPictureData snap = pptx.addPicture(previewJpg, PictureData.PictureType.JPEG);
XSLFPictureShape pic1 = slide1.createPicture(snap);
pic1.setAnchor(new Rectangle(100, 100, 500, 400));
CTPicture xpic1 = (CTPicture)pic1.getXmlObject();
CTHyperlink link1 = xpic1.getNvPicPr().getCNvPr().addNewHlinkClick();
link1.setId("");
link1.setAction("ppaction://media");
CTApplicationNonVisualDrawingProps nvPr = xpic1.getNvPicPr().getNvPr();
nvPr.addNewVideoFile().setLink(prsExec1.getId());
CTExtension ext = nvPr.addNewExtLst().addNewExt();
ext.setUri("{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}");
String p14Ns = "http://schemas.microsoft.com/office/powerpoint/2010/main";
XmlCursor cur = ext.newCursor();
cur.toEndToken();
cur.beginElement(new QName(p14Ns, "media", "p14"));
cur.insertNamespace("p14", p14Ns);
cur.insertAttributeWithValue(new QName(CORE_PROPERTIES_ECMA376_NS, "link"), prsEmbed1.getId());
cur.dispose();
CTSlide xslide = slide1.getXmlObject();
CTTimeNodeList ctnl;
if (!xslide.isSetTiming()) {
CTTLCommonTimeNodeData ctn = xslide.addNewTiming().addNewTnLst().addNewPar().addNewCTn();
ctn.setDur(STTLTimeIndefinite.INDEFINITE);
ctn.setRestart(STTLTimeNodeRestartType.NEVER);
ctn.setNodeType(STTLTimeNodeType.TM_ROOT);
ctnl = ctn.addNewChildTnLst();
} else {
ctnl = xslide.getTiming().getTnLst().getParArray(0).getCTn().getChildTnLst();
}
CTTLCommonMediaNodeData cmedia = ctnl.addNewVideo().addNewCMediaNode();
cmedia.setVol(80000);
CTTLCommonTimeNodeData ctn = cmedia.addNewCTn();
ctn.setFill(STTLTimeNodeFillType.HOLD);
ctn.setDisplay(false);
ctn.addNewStCondLst().addNewCond().setDelay(STTLTimeIndefinite.INDEFINITE);
cmedia.addNewTgtEl().addNewSpTgt().setSpid(""+pic1.getShapeId());
try (FileOutputStream fos = new FileOutputStream("mp4test-poi.pptx")) {
pptx.write(fos);
}
}
}
I have used iText PdfRender, which converts a non-OCR PDF to an image, after which I used iText PdfOcr to convert that image to an OCR'd PDF. Is there a tool that lets me perform this process in one step?
It would also be helpful if there was some documentation on how I can process multi-page PDFs using PdfRender, which I can't seem to find. The following is the code I used to convert 1 image to an OCR PDF document.
import com.itextpdf.pdfocr.OcrPdfCreator;
import com.itextpdf.pdfocr.tesseract4.Tesseract4LibOcrEngine;
import com.itextpdf.pdfocr.tesseract4.Tesseract4OcrEngineProperties;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class img2pdfocr {
static final Tesseract4OcrEngineProperties tesseract4OcrEngineProperties = new Tesseract4OcrEngineProperties();
private static List LIST_IMAGES_OCR = Arrays.asList(new File("image1.jpg"));
private static String OUTPUT_PDF = "F:\\ITEXT_workspace\\jumpstart\\bizdoc.pdf";
public static void main(String[] args) throws IOException {
final Tesseract4LibOcrEngine tesseractReader = new Tesseract4LibOcrEngine(tesseract4OcrEngineProperties);
tesseract4OcrEngineProperties.setPathToTessData(new File("F:\\ITEXT_workspace\\jumpstart\\TESS_DATA_FOLDER"));
OcrPdfCreator ocrPdfCreator = new OcrPdfCreator(tesseractReader);
try (PdfWriter writer = new PdfWriter(OUTPUT_PDF)) {
ocrPdfCreator.createPdf(LIST_IMAGES_OCR, writer).close();
}
}
}
EDIT
As pointed out in the comments, I need not use pdfRender, iText core itself can be used to extract images from a PDF. Use this for the code. You can check on this documentation
I'm getting some error while converting document to pdf using docx4j library in Java. Sadly, my error is this
NOT IMPLEMENTED support for w:pict without v:imagedata
and it's showing up on the converted pdf instead of displaying the error in my java terminal.
I have gone through some article and questions,thus found this converting docx to pdf . However, I am uncertain how to use this in my code or convert it. This is my code :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.model.structure.SectionWrapper;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
public class docTopdf {
public static void main(String[] args) {
try {
InputStream is = new FileInputStream(
new File(
"test.docx"));
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(is);
List<SectionWrapper> sections = wordMLPackage.getDocumentModel().getSections();
for (int i = 0; i < sections.size(); i++) {
wordMLPackage.getDocumentModel().getSections().get(i)
.getPageDimensions();
}
PhysicalFonts.discoverPhysicalFonts();
#Deprecated
Map<String, PhysicalFont> physicalFonts = PhysicalFonts.getPhysicalFonts();
// 2) Prepare Pdf settings
#Deprecated
PdfSettings pdfSettings = new PdfSettings();
// 3) Convert WordprocessingMLPackage to Pdf
#Deprecated
org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
wordMLPackage);
#Deprecated
OutputStream out = new FileOutputStream(
new File(
"test.pdf"));
conversion.output(out, pdfSettings);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
And my pom.xml
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>3.2.1</version>
</dependency>
any help would be appreciated as I am noob to this conversion. Thanks in advance
Creating a PDF via XSL FO doesn't support w:pict without v:imagedata (ie a graphic which isn't a simple image).
Whilst you could suppress the message by configuring logging appropriately, your PDF output would be lossy.
Your options are to correct the input docx (ie use an image instead of whatever you currently have), or to use a PDF converter with appropriate support. For one option, see https://www.docx4java.org/blog/2020/03/documents4j-for-pdf-output/