pdf中添加二维码无法扫描解决方案

正常行驶的bitmap类型的二维码格式,加载到PDF中,将会导致二维码失真,无法扫描。

矢量图可根据尺寸大小进行调节,不会出现失真模糊情况

所用依赖

<PackageReference Include="FreeSpire.PDF" Version="8.6.0" />//操作PDF依赖

<PackageReference Include="QRCoder" Version="1.4.3" />//生成二维码SVG依赖

//以下为代码说明

        #region 生成svg格式的矢量二维码

        public static string GetSvgQRCode(string plainText, int pixel)
        {
            var generator = new QRCodeGenerator();
            var qrCodeData = generator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q);
            var qrcode = new SvgQRCode(qrCodeData);
            return qrcode.GetGraphic(pixel);
        }
        #endregion
        #region
//生成并保存矢量图 public IActionResult GetSvgQRPic() { var svgText = QRCodeService.GetSvgQRCode("http://www.baidu.com", 15); string svgName = $"{Guid.NewGuid().ToString()}.svg"; string filePath = "E:\\ZGQM\\QRCODE\\"+ svgName; System.IO.File.WriteAllText(filePath, svgText); byte[] byts = System.IO.File.ReadAllBytes(filePath); return File(byts, "image/svg", svgName); } public IActionResult SvgTOPdf() { string pdfname = "shuangcengSingle.pdf"; string rootPath = "E:\\ZGQM\\QRCODE\\"; //加载示例SVG图片 PdfDocument doc1 = new PdfDocument(); doc1.LoadFromSvg(rootPath + "a2.svg"); //加载示例PDF文档 PdfDocument doc2 = new PdfDocument(); doc2.LoadFromFile(rootPath + pdfname); //设置图片在文档中的位置和大小59 var pdfwidth = doc2.Pages[0].Size.Width; var pdfheight = doc2.Pages[0].Size.Height; //计算两厘米二维码的磅值 double zb = 0; if(pdfwidth<=pdfheight) zb = 20 / (pdfwidth * 25.4 / 72); else zb = 20/ (pdfheight * 25.4 / 72); double twocodezb = zb * (pdfwidth<= pdfheight?pdfwidth:pdfheight); int twotruecode = Convert.ToInt32(Math.Round(twocodezb)); var doctemp = doc1.Pages[0].CreateTemplate();//创建蒙版 var p2 = new System.Drawing.PointF(0, 0); var di = new System.Drawing.SizeF(twotruecode, twotruecode); PdfCanvas d2z = doc2.Pages[0].Canvas; d2z.DrawTemplate(doctemp, p2, di);//通过比例大小进行绘制二维码到PDF //保存PDF文档 doc2.SaveToFile(rootPath + "AddSVGImagetoPDF-"+pdfname+".pdf", FileFormat.PDF); doc1.Close(); doc2.Close(); return null; } #endregion

以上可实现将矢量图进行绑定到PDF中,并且保证不失真。

参考部分连接

https://www.e-iceblue.cn/pdf_java_conversion/convert-svg-to-pdf-and-add-a-svg-image-to-pdf-in-java.html

https://cloud.tencent.com/developer/article/1518580?from=15425&areaSource=102001.24&traceId=X5ThA0l7o2dpqbZKzQB2_

posted @ 2023-02-20 17:02  zwbsoft  阅读(204)  评论(0编辑  收藏  举报