ColdFusion使用cfdocument生成PDF时如何让任意尺寸图片铺满Letter全页
你遇到的是cfdocument渲染HTML时默认保留图片原始尺寸、且HTML根元素默认有内置边距导致的小图无法铺满的问题,按以下方案调整即可:
方案1:允许图片轻微变形,完全铺满页面无空白
直接在cfdocument内部添加全局样式重置html和body的默认边距,同时指定图片宽高为100%即可适配所有尺寸的图片,完整代码如下:
<cfoutput> <cfdocument format="pdf" pageHeight="11" pagewidth="8.5" pagetype="custom" margintop="0" marginright="0" marginleft="0" marginbottom="0" orientation="landscape"> <style> html, body { margin: 0 !important; padding: 0 !important; width: 100%; height: 100%; } .full-img { width: 100%; height: 100%; display: block; border: 0; } </style> <img src="images/toy.jpg" class="full-img"> </cfdocument> </cfoutput>
方案2:保留图片原宽高比,铺满页面无空白(自动裁剪超出部分,不会变形)
如果要求图片不变形,改用背景图实现,利用background-size: cover属性自动缩放图片到刚好覆盖整个页面,完整代码如下:
<cfoutput> <cfdocument format="pdf" pageHeight="11" pagewidth="8.5" pagetype="custom" margintop="0" marginright="0" marginleft="0" marginbottom="0" orientation="landscape"> <style> html, body { margin: 0 !important; padding: 0 !important; width: 100%; height: 100%; background: url('images/toy.jpg') center center no-repeat; background-size: cover; } </style> <!-- 无需额外img标签 --> </cfdocument> </cfoutput>
兼容旧版ColdFusion的处理方式
如果你使用的CF版本不支持background-size属性,先读取图片的原始尺寸计算缩放比例,动态指定图片宽高即可:
<cfoutput> <!-- 读取图片信息 --> <cfimage action="info" source="images/toy.jpg" structname="imgInfo"> <cfset pageW = 11 * 72> <!-- 横向页面宽度 单位:PDF默认点,1英寸=72点 --> <cfset pageH = 8.5 * 72> <!-- 横向页面高度 --> <cfset scale = max(pageW / imgInfo.width, pageH / imgInfo.height)> <cfset renderW = round(imgInfo.width * scale)> <cfset renderH = round(imgInfo.height * scale)> <cfset offsetX = round((renderW - pageW) / 2 * -1)> <cfset offsetY = round((renderH - pageH) / 2 * -1)> <cfdocument format="pdf" pageHeight="11" pagewidth="8.5" pagetype="custom" margintop="0" marginright="0" marginleft="0" marginbottom="0" orientation="landscape"> <style> html, body { margin: 0 !important; padding: 0 !important; overflow: hidden; } </style> <img src="images/toy.jpg" width="#renderW#" height="#renderH#" style="margin-left:#offsetX#px;margin-top:#offsetY#px;"> </cfdocument> </cfoutput>
内容的提问来源于stack exchange,提问作者Ginger
相关产品推荐
相关产品推荐

