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

Struts1项目从PDF.js升级至PDF.js Express的实现方案咨询

可行实现方案

方案1:前端请求字节流转Blob加载(推荐)

无需修改后端现有逻辑,前端通过AJAX获取getImage.do返回的PDF字节流,转换为Blob后直接传给PDF.js Express加载。

代码示例

HTML部分(替换原iframe)

<div id="viewer" style="height: 600px; width: 98%; min-width: 900px;"></div>

Script部分

$(document).ready(function() {
    // 初始化PDF.js Express(替换path为你的资源目录)
    WebViewer({
        path: 'web/pdfjs-express',
        enableReadOnlyMode: true
    }, document.getElementById('viewer')).then(instance => {
        const { documentViewer } = instance.Core;
        const imageDocID = document.getElementById('imageDocID').value;
        const pdfUrl = `${pageContext.request.contextPath}/getImage.do?imageDocID=${imageDocID}`;
        
        // 以二进制数组形式请求PDF数据
        $.ajax({
            url: pdfUrl,
            method: 'GET',
            responseType: 'arraybuffer',
            success: function(data) {
                // 转换为Blob对象
                const pdfBlob = new Blob([data], { type: 'application/pdf' });
                // 加载到PDF.js Express
                documentViewer.loadDocument(pdfBlob);
            },
            error: function(err) {
                console.error('PDF加载失败:', err);
            }
        });
    });
});

方案2:后端生成临时PDF文件返回访问路径

修改GetImageAction.java,将生成的PDF保存到服务器临时目录,返回文件的访问URL,前端用该URL设置initialDoc。

后端代码修改(GetImageAction.java)

// 替换原输出流写入部分
if (actionForward == null) {
    byte[] dest = addWatemark(image);
    
    try{
        PdfReader reader = new PdfReader(dest);
        int pages = reader.getNumberOfPages();
    }catch(Exception ex){
        ex.printStackTrace();
        image = ImageManager.optimizePDF(image);
        dest = addWatemark(image);
    }
    
    // 创建临时文件存储目录
    String tempDir = request.getServletContext().getRealPath("/temp-pdfs");
    File dir = new File(tempDir);
    if (!dir.exists()) dir.mkdirs();
    
    // 生成唯一临时文件名
    String tempFileName = UUID.randomUUID().toString() + ".pdf";
    File tempPdf = new File(dir, tempFileName);
    
    // 写入PDF文件
    FileOutputStream fos = new FileOutputStream(tempPdf);
    fos.write(dest);
    fos.close();
    
    // 返回临时文件的访问URL
    String fileUrl = request.getContextPath() + "/temp-pdfs/" + tempFileName;
    response.setContentType("text/plain");
    response.getWriter().write(fileUrl);
    
    actionForward = null;
    // 建议:添加定时任务清理7天以上的临时文件
}

前端代码示例

$(document).ready(function() {
    const imageDocID = document.getElementById('imageDocID').value;
    const url = `${pageContext.request.contextPath}/getImage.do?imageDocID=${imageDocID}`;
    
    $.get(url, function(fileUrl) {
        WebViewer({
            path: 'web/pdfjs-express',
            initialDoc: fileUrl,
            enableReadOnlyMode: true
        }, document.getElementById('viewer'));
    }).fail(function(err) {
        console.error('获取PDF路径失败:', err);
    });
});

方案3:Data URI加载(仅适合小体积PDF)

将后端返回的字节流转换为Base64格式的Data URI,传给PDF.js Express。大文件可能导致性能问题,不推荐使用。

前端代码示例

$(document).ready(function() {
    WebViewer({
        path: 'web/pdfjs-express',
        enableReadOnlyMode: true
    }, document.getElementById('viewer')).then(instance => {
        const { documentViewer } = instance.Core;
        const imageDocID = document.getElementById('imageDocID').value;
        const pdfUrl = `${pageContext.request.contextPath}/getImage.do?imageDocID=${imageDocID}`;
        
        $.ajax({
            url: pdfUrl,
            method: 'GET',
            responseType: 'blob',
            success: function(blob) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    // 转换为Data URI
                    const dataUri = e.target.result;
                    documentViewer.loadDocument(dataUri);
                };
                reader.readAsDataURL(blob);
            }
        });
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:39:53