使用itext7生成二维码时如何在不改变整体尺寸前提下调整码点大小
iText7调整二维码内部码点大小解决方案
实现原理
你原来调用的placeBarcode方法默认会让每个二维码码点(数据模块)填满对应单元格,要在不改变二维码整体尺寸的前提下缩小码点,只需要手动遍历二维码的原始编码矩阵,每个有效码点绘制时留空单元格边缘即可。
修改后的实现代码
你只需要替换addQR方法即可:
private static void addQR(String mQRCode, PdfDocument mPdfDocument, int mPage, float mX, float mY) { PdfPage mPdfPage = mPdfDocument.getPage(mPage); BarcodeQRCode mBarcodeQRCode; Map<EncodeHintType, Object> mHints = new HashMap<>(); mHints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); mHints.put(EncodeHintType.MIN_VERSION_NR, 2); mBarcodeQRCode = new BarcodeQRCode(mQRCode, mHints); // 拿到二维码的编码矩阵 byte[][] matrix = mBarcodeQRCode.getBitMatrix(); int matrixSize = matrix.length; // 这里定义整体二维码的总尺寸,和你原来用0.5f模块大小的效果保持一致,可自行调整整体大小 float totalQrSize = 12.5f; // 单个单元格大小 = 总尺寸 / 矩阵边长 float cellSize = totalQrSize / matrixSize; // 码点缩放比例,0.8代表码点占单元格的80%,越小码点越细,可自行调整 float moduleScale = 0.8f; float moduleSize = cellSize * moduleScale; // 每个码点的偏移量,保证码点在单元格内居中显示 float offset = (cellSize - moduleSize) / 2; PdfCanvas over = new PdfCanvas(mPdfPage); over.setFillColor(ColorConstants.RED); // 遍历矩阵绘制每个码点 for (int i = 0; i < matrixSize; i++) { for (int j = 0; j < matrixSize; j++) { // 矩阵坐标默认上下翻转,所以y坐标需要反向计算 if (matrix[j][i] == 1) { float x = mX + i * cellSize + offset; float y = mY + (matrixSize - 1 - j) * cellSize + offset; over.rectangle(x, y, moduleSize, moduleSize); } } } over.fill(); }
参数调整说明
- 调整
totalQrSize可以修改二维码整体尺寸,不需要改大小的话保持默认值即可 - 调整
moduleScale可以修改码点大小,取值范围0-1,数值越小码点越细,不会影响二维码整体尺寸 - 二维码容错等级建议保持M及以上,码点缩小后仍然可以正常识别
内容的提问来源于stack exchange,提问作者Ahn
相关产品推荐
相关产品推荐

