如何使用 javascript 在浏览器中显示 PDF 流

问题描述 投票:0回答:3

我正在使用 jquery 的 ajax 方法访问现有的 WCF Web 服务(它以字节流的形式返回 PDF)。

当对服务的调用完成时,我最终得到一个包含 PDF 的 JavaScript 变量(该变量包含二进制数据,以“%PDF-1.4...”开头)。

我想在新的浏览器窗口中显示此 PDF,但我很难实现这一点。

到目前为止,我的研究表明,我也许能够使用 data: uri 来实现我想要的目标,因此 ajax 调用完成时调用的代码如下:

function GotPDF(data)
{
    // Here, data contains "%PDF-1.4 ..." etc.
    var datauri = 'data:application/pdf;base64,' + Base64.encode(data);
    var win = window.open("", "Your PDF", "width=1024,height=768,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no");
    win.document.location.href = datauri;
}

这会打开一个新的浏览器窗口,但内容是空白的。

有趣的是,如果我使用 file: uri 将浏览器(IE9)指向本地磁盘上的现有文件,例如 file://c:/tmp/example.pdf,那么我会得到相同的结果,即空白窗口。

有什么办法可以显示这个PDF数据吗?

javascript jquery pdf browser
3个回答
19
投票

您编写的代码不会显示任何内容,只需打开一个空白窗口(

location.href
是浏览历史记录的哈希值,而不是页面的内容)。

要显示 PDF,您至少有以下选项:

× 将 PDF 查看器嵌入到

object
标签内。它可能不像您想象的那么简单,请查看this post获取示例代码。简而言之应该是这样的:

<object data="your_url_to_pdf" type="application/pdf">
    <div>No PDF viewer available</div>
</object>

这是基本代码,但如果您需要更高的跨浏览器兼容性,我建议遵循我在链接帖子中所说的内容(它还包含一些关于如何可能尝试检测对 PDF 查看器的支持的示例)。

× 将文件下载到本地计算机(只需添加生成文件的 Web 服务方法的完整 URL,不要忘记在标题中添加正确的

Content-Disposition
)。

× 在新的浏览器窗口中打开文件。当您指向要在新窗口中显示的在线 PDF 文件时,创建一个 normal

a
标签。将
href
更改为
javascript:functionName
,并在该函数中生成您将用于调用 Web 服务方法的 URI。

无论您做什么,都不要忘记在响应中设置正确的 MIME 类型,而且您的方法不应返回字节流(即使已编码),而应返回 Web 浏览器的有效响应。


8
投票

如果您使用

<embed>
<object>
标签来显示来自服务器的流式 PDF 文件(或其他文件类型),如下所示:

<object data="SomeServlet?do=get_doc&id=6" type="application/pdf" width="800" height="400">

确保服务器发送正确的 http

content-disposition
值,在本例中为
inline


0
投票

document.getElementById('uploadForm').addEventListener('submit', function(event) {
    event.preventDefault();

    // ทำการโหลดไฟล์ PDF และบันทึก
    var pdfFileURL = '/web/viewer.html?file=%2Fassets%2Fpdf%2Fuploaded-file.pdf'; // เปลี่ยนเส้นทางไฟล์ตามที่คุณเก็บไฟล์

    var xhr = new XMLHttpRequest();
    xhr.open('GET', pdfFileURL, true);
    xhr.responseType = 'arraybuffer';

    xhr.onload = function() {
        var arrayBuffer = xhr.response;
        if (arrayBuffer) {
            // เรียกใช้ PDF.js library เพื่อดึงข้อมูลจากไฟล์ PDF
            pdfjsLib.getDocument(arrayBuffer).then(function(pdf) {
                // ดึงหน้าแรกของไฟล์ PDF
                pdf.getPage(1).then(function(page) {
                    // สร้าง canvas เพื่อแสดงรูปภาพจากตราปั๊ม
                    var canvas = document.createElement('canvas');
                    var context = canvas.getContext('2d');
                    var viewport = page.getViewport({ scale: 1.0 });

                    // ตั้งค่าขนาดของ canvas ตาม viewport
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;

                    // ดึงข้อมูลจาก PDF และวาดลงบน canvas
                    var renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };

                    page.render(renderContext).then(function() {
                        // นำ canvas ไปแปลงเป็น data URL
                        var dataURL = canvas.toDataURL();

                        // แสดงตราปั๊มในฟอร์ม
                        var pumpImageContainer = document.getElementById('pumpImageContainer');
                        var pumpImage = document.getElementById('pumpImage');

                        // สร้างเส้นคั่นตราปั๊ม
                        context.beginPath();
                        context.moveTo(0, canvas.height / 2);
                        context.lineTo(canvas.width, canvas.height / 2);
                        context.strokeStyle = 'blue'; // สีน้ำเงิน
                        context.lineWidth = 5;
                        context.stroke();

                        // แสดงข้อความตามที่ระบุ
                        context.fillStyle = 'blue'; // สีน้ำเงิน
                        context.font = '20px Arial';

                        var textLines = ['CHT', 'ชื่อ', 'วันที่ ' + new Date().toLocaleDateString()];
                        var lineHeight = 30;
                        var startY = canvas.height / 2 - (lineHeight * textLines.length) / 2;

                        textLines.forEach(function(line, index) {
                            context.fillText(line, canvas.width / 2 - context.measureText(line).width / 2, startY + index * lineHeight);
                        });

                        // แสดงรูปตราปั๊มในฟอร์ม
                        pumpImage.src = dataURL;
                        pumpImage.alt = 'รูปตราปั๊ม';
                        pumpImageContainer.style.display = 'block';
                    });
                });
            });
        }
    };

    xhr.send();
});
<form id="uploadForm" action="/YourController/Upload" method="post" enctype="multipart/form-data">
    <label for="pdfFile">เลือกไฟล์ PDF:</label>
    <input type="file" name="pdfFile" id="pdfFile" required />
    
    <label for="name">ชื่อ:</label>
    <input type="text" name="name" id="name" required />
    
    <input type="submit" value="อัปโหลด" />
</form>

<div id="pumpImageContainer">
    <img id="pumpImage" alt="รูปตราปั๊ม" />
</div>

© www.soinside.com 2019 - 2024. All rights reserved.