Flutter中如何获取PDF真实宽高以解决转图片尺寸错误问题
问题根因
page.width、page.height返回的单位是PDF标准的印刷点(pt),而非渲染输出的像素值。PDF默认1pt对应1/72英寸,你测试场景中硬编码得到的457x1078像素,实际是将pt值乘以3倍缩放系数(对应216DPI)得到的结果,直接用pt值作为render入参只会得到72DPI的低清小图,就是你遇到的尺寸偏小的情况。
解决方法
固定DPI渲染(适配绝大多数固定尺寸输出需求)
直接根据业务需要的DPI换算渲染尺寸即可,你当前测试场景下取216DPI就能得到预期的输出尺寸,可灵活调整DPI适配不同清晰度要求:
await Dio().download(urlFile, filePath).whenComplete(() async { File file = File(filePath); Uint8List bytes = file.readAsBytesSync(); final document = await PdfDocument.openData(bytes); final page = await document.getPage(1); // DPI可根据业务需求调整,72为PDF默认DPI,216对应3倍缩放,可匹配你测试场景的输出尺寸 const double targetDpi = 216; final int renderWidth = (page.width * targetDpi / 72).round(); final int renderHeight = (page.height * targetDpi / 72).round(); final pageImage = await page.render(width: renderWidth, height: renderHeight, format: PdfPageFormat.JPEG); await page.close(); await document.close(); // 及时释放PDF资源,避免内存泄漏 });
适配设备屏幕1:1输出
如果需要和PDF物理尺寸在当前设备上1:1显示,直接用设备的像素比作为缩放系数即可,Flutter环境下可以通过MediaQuery.of(context).devicePixelRatio获取当前设备的像素比。
内容的提问来源于stack exchange,提问作者Linesofcode
相关产品推荐
相关产品推荐

