You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PDF模板的WNI方框内正确打印文本“X”?

问题:PDF模板中WNI方框内的"X"被遮挡

我在PDF模板的WNI方框内打印"X"时,"X"显示在方框后方被遮挡,使用的代码如下:

def webRootDir = grailsApplication.mainContext.servletContext.getRealPath("/")
def temp = new File(webRootDir, "/overlayTemp/")
temp.mkdirs()

def rdnPage = ("rdnCIMBpage"+_no+".pdf")
File _page = new File(temp, rdnPage)
def overlayName = ("overlayCIMB"+_no+".pdf")
File overlayID = new File(temp, overlayName)

//load template
template = assetResourceLocator.findAssetForURI( tpl+_no+".pdf" ).getInputStream()?.bytes
PDDocument p_doc = PDDocument.load( new ByteArrayInputStream( template ) )
log.info '[RegistrationService::writeRdnSinarmas][id: ' + registrationInstance.id + '][Write FormRDNSinarmasNew_' + _no + '.pdf]'

PDDocument overlayDoc = new PDDocument()
try
{
    PDPage page = new PDPage()
    overlayDoc.addPage(page)
    PDPageContentStream contentStream = new PDPageContentStream(overlayDoc, page)

    //ininomer1
    //x kalau ditambah akan maju ke kanan
    //y kalau di turunin akan turun ke bawah            
    if(_no==1) {
        if(registrationInstance.personalInformation.citizenship=="WNI"){
            setText(contentStream, "X", 104, 390)       
        }else{
            setText(contentStream, "X", 110, 390)
        }
}
解决方案

问题出在你创建了独立的overlayDoc作为覆盖层,后续合并时该覆盖层会被原模板压在下方。直接操作原文档页面,让新内容叠加在原有内容之上即可解决:

  1. 移除独立的overlayDoc,直接操作原文档的目标页面
  2. 使用AppendMode.APPEND创建内容流,确保新文本绘制在模板内容上方

修改后的核心代码:

//load template
template = assetResourceLocator.findAssetForURI( tpl+_no+".pdf" ).getInputStream()?.bytes
PDDocument p_doc = PDDocument.load( new ByteArrayInputStream( template ) )
log.info '[RegistrationService::writeRdnSinarmas][id: ' + registrationInstance.id + '][Write FormRDNSinarmasNew_' + _no + '.pdf]'

try {
    // 获取原文档的目标页面(PDFBox页码从0开始,_no==1对应第1页即索引0)
    PDPage targetPage = p_doc.getPage(0)
    // 创建内容流,指定APPEND模式,确保新内容叠加在原有内容上方
    PDPageContentStream contentStream = new PDPageContentStream(
        p_doc, 
        targetPage, 
        PDPageContentStream.AppendMode.APPEND, 
        true, // 压缩内容
        true  // 重置上下文,避免继承原有页面的图形状态
    )

    // 设置文本位置和内容
    if(_no==1) {
        if(registrationInstance.personalInformation.citizenship=="WNI"){
            setText(contentStream, "X", 104, 390)       
        }else{
            setText(contentStream, "X", 110, 390)
        }
    }

    // 关闭内容流并保存文档
    contentStream.close()
    p_doc.save(_page) // 根据需求保存到目标文件
} finally {
    p_doc.close()
}
  1. 额外检查
  • 确认setText方法的字体大小、坐标是否精准落在WNI方框内部
  • 若仍有遮挡,可检查原PDF模板中方框的图层优先级,确保后续添加的文本处于更高层级

内容的提问来源于stack exchange,提问作者Kraken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 22:05:40