Search code examples
itext7

Why I am unable to change the QR Code's size in iText7?


How to change QR Code size?

            using (iText.Kernel.Pdf.PdfReader _pdf_reader = 
                new iText.Kernel.Pdf.PdfReader("tmp/example.pdf"))
            {
                using (iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(_pdf_reader, new iText.Kernel.Pdf.PdfWriter("tmp/output.pdf").SetSmartMode(true)))
                {
                    BarcodeQRCode qrc = new BarcodeQRCode("https://google.com");

                    PdfFormXObject xObject = qrc.CreateFormXObject(ColorConstants.BLACK, pdfDoc);

                    float _w = pdfDoc.GetPage(1).GetPageSize().GetWidth();
                    float _h = pdfDoc.GetPage(1).GetPageSize().GetHeight();
                    PdfCanvas canvas = new PdfCanvas(pdfDoc.GetPage(1));
                    canvas.SaveState();
                    canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
                    //canvas.Rectangle(_w - 90, _h - 90, 100, 100);
                    canvas.Fill();
                    canvas.RestoreState();
                    canvas.AddXObject(xObject, _w - qrc.GetBarcodeSize().GetWidth(), _h - qrc.GetBarcodeSize().GetHeight());
                }
            }

I try:

 qrc.GetBarcodeSize().GetHeight();
 qrc.GetBarcodeSize().GetWidth();

it returns 33

I try to set Height & Width to 100 like below:

 qrc.GetBarcodeSize().SetHeight(100);
 qrc.GetBarcodeSize().SetWidth(100);

and then check the size again, but it keeps returning 33, is it a bug? or Did I miss something?

please help

thanks Don


Solution

  • I try to set Height & Width to 100 like below:

    Actually, you can`t change the QrCode side this way. In fact, QRcode is an n*n grid where n depends on some parameters as a QR code version and the error correction level. When generating, iText uses the smallest version that can fit the content. This is version 4 (33*33) in your case.

    The easiest way to change the size of QrCode in a document is by using the version of the createFormXObject method which accepts the moduleSide parameter.

    float moduleSize = 100/qrc.GetBarcodeSize().GetHeight();    
    qrc.createFormXObject(foreground, moduleSize, document)
    

    Module size here is size of the barcode`s grid cell (1 by default).